C#SM4加密算法
1.管理NuGet程序包,搜索BouncyCastle,安装 2.代码示例 //加密算法:SM4 //加密模式:ECB //填充模式:PKCS5Padding //编码类型:UTF-8
/// <summary> /// 加密 /// </summary> /// <param name="plainText"></param> /// <param name="secretKey"></param> /// <returns></returns> public string MS4Encrypt_ECB(string plainText, string secretKey) { byte[] plaintext = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = Encoding.UTF8.GetBytes(secretKey); IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS5Padding"); KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes); inCipher.Init(true, key); byte[] cipher = inCipher.DoFinal(plaintext); //加密结果数据格式Hex byte[] encrypted2 = Hex.Encode(cipher); return Encoding.UTF8.GetString(encrypted2).ToUpper(); }
/// <summary> /// 解密 /// </summary> /// <param name="cipherText"></param> /// <param name="secretKey"></param> /// <returns></returns> public string MS4Decrypt_ECB(string cipherText, string secretKey) { byte[] keyBytes = Encoding.UTF8.GetBytes(secretKey); byte[] plaintext = Encoding.UTF8.GetBytes(cipherText); IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS5Padding"); KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes); var cipher = Hex.Encode(plaintext); inCipher.Reset(); inCipher.Init(false, key); byte[] bin = inCipher.DoFinal(cipher); string ans = Encoding.UTF8.GetString(bin); return ans; }
// 当secretKey为Base64位字符串,使用ECB加密为Base64
public static string MS4Encrypt_ECB(string plainText, string secretKey)
{
byte[] keyBytes = Convert.FromBase64String(secretKey);
byte[] plaintext = Encoding.UTF8.GetBytes(plainText);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS5Padding");
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
inCipher.Init(true, key);
byte[] cipher = inCipher.DoFinal(plaintext);
return Convert.ToBase64String(cipher);
}
在线工具:https://lzltool.cn/SM4