C#中SM2加解密

复制代码
    public class Sm2: IDecryption
    {
        private readonly string _privateKey;
        private readonly Encoding _encoding;
        private readonly string _publickey;

        public Sm2(string privateKey,string publickey,Encoding encoding)
        {
            _privateKey = privateKey;
            _publickey = publickey;
            _encoding = encoding;

        }

        public static AlgKeyPair CreateKeyPair(Encoding encoding)
        {
            var keyPair = SM2.Instance.ecc_key_pair_generator.GenerateKeyPair();
            var privateKeyParameters = (ECPrivateKeyParameters)keyPair.Private;
            var publicKeyParameters = (ECPublicKeyParameters)keyPair.Public;
            var d = privateKeyParameters.D;
            return new AlgKeyPair(encoding.GetString(Hex.Encode(publicKeyParameters.Q.GetEncoded())).ToUpper(),
                encoding.GetString(Hex.Encode(d.ToByteArray())).ToUpper());
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="ciphertext"></param>
        /// <returns></returns>
        public string Decrypt(string ciphertext)
        {
           return  _encoding.GetString(SM2Utils.Decrypt(Hex.Decode(_privateKey),
               (Hex.Decode(ciphertext))));
        }


        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="ciphertext"></param>
        /// <returns></returns>
        public string Encrypt(string ciphertext)
        {
            return (SM2Utils.Encrypt(Hex.Decode(_publickey),
                (_encoding.GetBytes(ciphertext))));
        }




        private byte[] ChangeC1C3C2ToC1C2C3(byte[] data)
        {
            const int c1Len = 65;
            const int c3Len = 32;
            var result = new byte[data.Length];
            Array.Copy(data, 0, result, 0, c1Len);
            Array.Copy(data, c1Len + c3Len, result, c1Len, data.Length - c1Len - c3Len);
            Array.Copy(data, c1Len, result, data.Length - c3Len, c3Len);
            return result;
        }

    }
复制代码

 

posted @   NangFah  阅读(828)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示