using System;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Com.Bocom.OpenApi.Security.KeyGen;

namespace Com.Bocom.OpenApi
{
    namespace Security
    {
        namespace Crypt
        {
            public class SM2Cryptor
            {
                public static string Encrypt(string data, string publicKey, string charset)
                {
                    SM2Engine sm2Engine = new SM2Engine();

                    sm2Engine.Init(true,
                        new ParametersWithRandom(SM2KeyGen.GetECPublicKey(publicKey), new SecureRandom()));

                    byte[] dataByteArray = Encoding.GetEncoding(charset).GetBytes(data);

                    return Convert.ToBase64String(sm2Engine.ProcessBlock(dataByteArray, 0, dataByteArray.Length));
                }

                public static string Decrypt(string encryptedData, string privateKey, string charset)
                {
                    SM2Engine sm2Engine = new SM2Engine();

                    sm2Engine.Init(false, SM2KeyGen.GetECPrivateKey(privateKey));

                    byte[] encryptedDataByteArray = Convert.FromBase64String(encryptedData);

                    return Encoding.GetEncoding(charset).GetString(sm2Engine.ProcessBlock(encryptedDataByteArray, 0,
                        encryptedDataByteArray.Length));
                }

                public static void Main(string[] args)
                {
                    string data = "bocom-fobp-zhaozheyang";
                    //AsymmetricCipherKeyPair keyPair = SM2KeyGen.GenSM2KeyPair();
                    //string pubKey = SM2KeyGen.GetPublicKeyStr(keyPair);
                    //string priKey = SM2KeyGen.GetPrivateKeyStr(keyPair);
                    string pubKey = "02e4c86e0a58a130d3d4c82e7771304e4ba05f9d86c91b044b735d57702122bf12";
                    string priKey = "009001b7caa52bcc67694b9fdd96d06685878457a97db991a787c51ac0c12eebe7";
                    
                    string encrypted = SM2Cryptor.Encrypt(data, pubKey, "UTF-8");
                    Console.WriteLine("密文：" + encrypted);
                    Console.WriteLine("明文：" + SM2Cryptor.Decrypt(encrypted, priKey, "UTF-8"));
                }
            }
        }
    }
}