C# “國密加密演算法”SM系列的C#實現方法 - 修改版
阿新 • • 發佈:2020-11-28
https://www.jianshu.com/p/7a4c8b75c7cf
C# “國密加密演算法”SM系列的C#實現方法 - 修改版
第二淪陷區 0.0962018.08.28 15:51:40字數 135閱讀 4,025http://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;