C# 国密SM2使用方法和介绍,附带测试工具源码

1.SM2国密简介:

SM2算法是中国国家密码局推出的国产化算法,是基于椭圆曲线的非对称算法,相对于RSA算法,SM2具有密钥更小,运算速度更快,相同密钥长度下具有更高安全性等优势。

2.未压缩公钥

通常以前缀04开头,后跟两个256位数字;一个用于点的x坐标,另一个用于点的y坐标。前缀04用于区分未压缩的公共密钥和以02或03开头的压缩公共密钥
即04||x||y

3.直接上代码

首先创建一个Winfrom的项目

在NuGet包里面添加两个动态库,注意的是动态库的版本号

SM2Util.cs类

 public class SM2Util
    {
        /**
           * 生成SM2秘钥对
           * string[0] 公钥
           * string[1] 私钥
           */
        public static string[] GenerateKeyPair()
        {
            return SM2.GenerateKeyPair();
        }

        /**
         * SM2签名
         * data 签名的数据
         * priKey 私钥
         */
        public static string Sign(string data, string priKey)
        {
            SM2 sm2 = new SM2(priKey, null);
            return sm2.Sign(data);

        }


        /**
         * SM2签名
         * sign 源数据
         * pubKey 公钥
         * sign 签名的数据
         */
        public static bool verifySign(string msg, string pubKey, string sign)
        {
            SM2 sm2 = new SM2(null, pubKey);
            return sm2.verifySign(msg, sign);
        }


        /**
         * 加密
         * 返回Base64字符串
         *  公钥加密
         *  plainText 要加密的文本
         *  pubKey 公钥
         */
        public static string encryptBase64(string plainText, string pubKey)
        {
            SM2 sm2 = new SM2(null, pubKey);
            byte[] encryptByte = sm2.encrypt(Encoding.UTF8.GetBytes(plainText));
            return Base64.ToBase64String(encryptByte);
        }

        /**
         * 解密
         *  私钥解密
         *  plainText 要加密的文本
         *  pubKey 公钥
         */
        public static string decryptBase64(string plainText, string priKey)
        {
            SM2 sm2 = new SM2(priKey, null);
            byte[] deCode = Base64.Decode(plainText);
            byte[] decryptText = sm2.deceypt(deCode);
            return Encoding.UTF8.GetString(decryptText);
        }

    }

From1.Designer.cs

partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button4 = new System.Windows.Forms.Button();
            this.textBox8 = new System.Windows.Forms.TextBox();
            this.textBox7 = new System.Windows.Forms.TextBox();
            this.label8 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.textBox5 = new System.Windows.Forms.TextBox();
            this.textBox6 = new System.Windows.Forms.TextBox();
            this.butt

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 是一种通用的编程语言,可以用来开发各种类型的应用程序,包括使用国密SM2非对称算法进行加密和解密操作。 要在C#使用国密SM2算法,你可以使用BouncyCastle库。BouncyCastle是一个流行的密码学库,提供了各种加密算法的实现,包括SM2。 首先,你需要将BouncyCastle库添加到你的项目中。你可以通过NuGet包管理器或手动下载并添加引用。 下面是一个使用C#和BouncyCastle库实现SM2加密和解密的示例代码: ```csharp using System; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; public class SM2Example { public static void Main() { // 生成SM2密钥对 AsymmetricCipherKeyPair keyPair = GenerateKeyPair(); // 获取公钥和私钥 ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)keyPair.Private; ECPublicKeyParameters publicKey = (ECPublicKeyParameters)keyPair.Public; // 要加密的明文 string plaintext = "Hello, SM2!"; // 使用公钥进行加密 byte[] ciphertext = Encrypt(publicKey, plaintext); // 使用私钥进行解密 string decryptedText = Decrypt(privateKey, ciphertext); Console.WriteLine("Plaintext: " + plaintext); Console.WriteLine("Ciphertext: " + Convert.ToBase64String(ciphertext)); Console.WriteLine("Decrypted text: " + decryptedText); } // 生成SM2密钥对 public static AsymmetricCipherKeyPair GenerateKeyPair() { ECKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("SM2"); keyPairGenerator.Init(new ECKeyGenerationParameters(SM2NamedCurves.GetByName("sm2p256v1"), new SecureRandom())); return keyPairGenerator.GenerateKeyPair(); } // 使用公钥进行加密 public static byte[] Encrypt(ECPublicKeyParameters publicKey, string plaintext) { IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("SM2"); agreement.Init(publicKey); byte[] input = System.Text.Encoding.UTF8.GetBytes(plaintext); byte[] output = agreement.CalculateAgreement(publicKey.Q).ToByteArrayUnsigned(); return output; } // 使用私钥进行解密 public static string Decrypt(ECPrivateKeyParameters privateKey, byte[] ciphertext) { IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("SM2"); agreement.Init(privateKey); byte[] input = new byte[ciphertext.Length]; Array.Copy(ciphertext, input, ciphertext.Length); BigInteger sharedSecret = new BigInteger(1, input); byte[] output = agreement.CalculateAgreement(privateKey.D, sharedSecret).ToByteArrayUnsigned(); return System.Text.Encoding.UTF8.GetString(output); } } ``` 这个示例代码演示了如何生成SM2密钥对,并使用公钥进行加密,私钥进行解密。注意,在实际应用中,你需要妥善保管私钥,确保安全性。 希望这可以帮助到你!如果有任何问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值