C# “国密加密算法”SM系列的C#实现方法 - 修改版
https://www.jianshu.com/p/7a4c8b75c7cf
C# “国密加密算法”SM系列的C#实现方法 - 修改版
http://www.zhimengzhe.com/bianchengjiaocheng/Javabiancheng/22144.html
在网上搜索SM实现方法,按照上面网站提供方法总是出错,经过调试终于修改好了,给大家以参考,不走弯路了
base64修改,这个看需求,如果不需要base64格式,可以不修改,但是下面要把 “i” 修改成 “j”,这个可能是原作者写错了,我这里修改一下,然后做记录,然后再把完整的贴出来
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
namespace Common
{
class SM4Utils
{
public string secretKey = "";
public string iv = "";
public bool hexString = false;
public string Encrypt_ECB(string plainText)
{
SM4_Context ctx = new SM4_Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_ENCRYPT;
byte[] keyBytes;
if (hexString)
{
keyBytes = Hex.Decode(secretKey);
}
else
{
keyBytes = Encoding.Default.GetBytes(secretKey);
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_enc(ctx, keyBytes);
byte[] encrypted = sm4.sm4_crypt_ecb(ctx, Encoding.Default.GetBytes(plainText));
string cipherText = Encoding.Default.GetString(Hex.Encode(encrypted));
return cipherText;
}
public string Decrypt_ECB(string cipherText)
{
SM4_Context ctx = new SM4_Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_DECRYPT;
byte[] keyBytes;
if (hexString)
{
keyBytes = Hex.Decode(secretKey);
}
else
{
keyBytes = Encoding.Default.GetBytes(secretKey);
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_dec(ctx, keyBytes);
byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Hex.Decode(cipherText));
return Encoding.Default.GetString(decrypted);
}
public string Encrypt_CBC(string plainText)
{
SM4_Context ctx = new SM4_Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_ENCRYPT;
byte[] keyBytes;
byte[] ivBytes