C# 国密加密 SM2-SM4(.net)

 

 

 

 

新建一个控制台来做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有两种模式,运行后,如下图:

posted @ 2020-12-17 15:45  心中的天空之城  阅读(10977)  评论(6编辑  收藏  举报