using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Utilities.Encoders;
using Com.Bocom.OpenApi.Security.KeyGen;

namespace Com.Bocom.OpenApi
{
    namespace Security
    {
        namespace Sign
        {
            public class SM2Signature
            {
                public static string Sign(string data, string privateKey, string charset)
                {
                    ISigner signer = new SM2Signer();
                    signer.Init(true, SM2KeyGen.GetECPrivateKey(privateKey));
                    byte[] dataByteArray = Encoding.GetEncoding(charset).GetBytes(data);
                    signer.BlockUpdate(dataByteArray, 0, dataByteArray.Length);
                    return Hex.ToHexString(signer.GenerateSignature());
                }

                public static bool Verify(string data, string publicKey, string charset, string signature)
                {
                    ISigner signer = new SM2Signer();
                    signer.Init(false, SM2KeyGen.GetECPublicKey(publicKey));
                    byte[] dataByteArray = Encoding.GetEncoding(charset).GetBytes(data);
                    signer.BlockUpdate(dataByteArray, 0, dataByteArray.Length);
                    return signer.VerifySignature(Hex.Decode(signature));
                }
            }
        }
    }
}