首页 > Web开发 > 详细

ASP.NET 国密加密 SM2-SM4

时间:2019-12-30 17:55:49      阅读:483      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

 

新建一个控制台来做demo

nuget引用程序集:KYSharp.SM

技术分享图片

 

安装 2.0 版本,里面才有sm3和sm4的加密

 

一、SM2的用法

  static void SM2Console()
        {
            //公钥
            string publickey = "";
            //私钥
            string privatekey = "";
            //生成公钥和私钥
            SM2Utils.GenerateKeyPair(out publickey, out privatekey);

            System.Console.Out.WriteLine("加密明文: " + "000000");
            System.Console.Out.WriteLine("publickey:" + publickey);
            //开始加密
            string cipherText = SM2Utils.Encrypt(publickey, "000000");
            System.Console.Out.WriteLine("密文: " + cipherText);
            System.Console.Out.WriteLine("privatekey:" + privatekey);
            //解密
            string plainText = SM2Utils.Decrypt(privatekey, cipherText);
            System.Console.Out.WriteLine("明文: " + plainText);
            Console.ReadLine();
        }
  static void Main(string[] args)
        {
            SM2Console();
            Console.ReadLine();
        }

 

 效果如下:

技术分享图片

 

 

该种加密方式得到的密文是长度不固定的密文串,可能几百位。

 

二、SM3 使用

 static void SM3Console()
        {
            SM3 bo = new SM3();
            string str = bo.Encrypt("asdfasde");
            Console.WriteLine("密文:"+str);
            Console.WriteLine("长度:" + str.Length);
            str = bo.Encrypt("asdfasdf");
            Console.WriteLine("密文:" + str);
            Console.WriteLine("长度:" + str.Length);

            Console.ReadLine();
           
        }

 

 运行结果如下:

技术分享图片

 

 

SM3 得到的是一个64位的密文。

 

三、SM4使用

 

 static void SM4Console()
        {
            String plainText = "ererfeiisgod";

            SM4Utils sm4 = new SM4Utils();
            sm4.secretKey = "JeF8U9wHFOMfs2Y8";
            sm4.hexString = false;

            System.Console.Out.WriteLine("ECB模式");
            String cipherText = sm4.Encrypt_ECB(plainText);
            System.Console.Out.WriteLine("密文: " + cipherText);
            System.Console.Out.WriteLine("");

            plainText = sm4.Decrypt_ECB(cipherText);
            System.Console.Out.WriteLine("明文: " + plainText);
            System.Console.Out.WriteLine("");

            System.Console.Out.WriteLine("CBC模式");
            sm4.iv = "UISwD9fW6cFh9SNS";
            cipherText = sm4.Encrypt_CBC(plainText);
            System.Console.Out.WriteLine("密文: " + cipherText);
            System.Console.Out.WriteLine("");

            plainText = sm4.Decrypt_CBC(cipherText);
            System.Console.Out.WriteLine("明文: " + plainText);

            Console.ReadLine();
        }

SM有两种模式,运行后,如下图:

技术分享图片

 

ASP.NET 国密加密 SM2-SM4

原文:https://www.cnblogs.com/fei686868/p/12120772.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!