
新建一個控制台來做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有兩種模式,運行后,如下圖:


