c# sm4加密解密
时间: 2023-12-13 14:34:19 浏览: 114
SM4加密C#类
3星 · 编辑精心推荐
以下是C#中使用SM4算法进行加密和解密的示例代码:
```csharp
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string plainText = "Hello, world!"; // 待加密的明文
string key = "0123456789abcdef"; // 密钥,必须为16个字符
byte[] encrypted = SM4Encrypt(Encoding.UTF8.GetBytes(plainText), Encoding.UTF8.GetBytes(key));
Console.WriteLine("Encrypted: " + BitConverter.ToString(encrypted).Replace("-", ""));
byte[] decrypted = SM4Decrypt(encrypted, Encoding.UTF8.GetBytes(key));
Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(decrypted));
}
static byte[] SM4Encrypt(byte[] plainText, byte[] key)
{
using (SM4 sm4 = new SM4())
{
sm4.Key = key;
sm4.Mode = CipherMode.ECB;
sm4.Padding = PaddingMode.Zeros;
using (ICryptoTransform encryptor = sm4.CreateEncryptor())
{
return encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
}
}
}
static byte[] SM4Decrypt(byte[] cipherText, byte[] key)
{
using (SM4 sm4 = new SM4())
{
sm4.Key = key;
sm4.Mode = CipherMode.ECB;
sm4.Padding = PaddingMode.Zeros;
using (ICryptoTransform decryptor = sm4.CreateDecryptor())
{
return decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
}
}
}
}
```
需要注意的是,SM4算法的密钥长度必须为16个字符,如果不足16个字符则需要进行补齐。此外,SM4算法的工作模式和填充模式也需要指定,上述示例中使用的是ECB模式和零填充模式。
阅读全文