类别:程序开发

日期:2023-06-06 浏览:1563 评论: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://vtzw.com/post/1091.html
作者授权:除特别说明外,本文由 零一 原创编译并授权 零一的世界 刊载发布。
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
 您阅读本篇文章共花了: 

评论区

发表评论 / 取消回复

必填

选填

选填

◎欢迎讨论,请在这里发表您的看法及观点。