C# AES128算法
时间: 2023-07-12 09:33:00 浏览: 170
AES是分组密钥,算法输入128位数据,密钥长度也是128位
4星 · 用户满意度95%
C#提供了AES加密算法的实现,可以使用System.Security.Cryptography命名空间中的AesManaged类。
以下是一个示例代码:
```
using System;
using System.Security.Cryptography;
using System.Text;
class AES128
{
static void Main()
{
string plainText = "Hello, world!";
string key = "0123456789abcdef";
string iv = "1234567890abcdef";
byte[] encrypted = Encrypt(Encoding.UTF8.GetBytes(plainText), Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv));
Console.WriteLine("Encrypted: {0}", Convert.ToBase64String(encrypted));
string decrypted = Decrypt(encrypted, Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv));
Console.WriteLine("Decrypted: {0}", decrypted);
}
public static byte[] Encrypt(byte[] plainTextBytes, byte[] keyBytes, byte[] ivBytes)
{
using (AesManaged aes = new AesManaged())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Key = keyBytes;
aes.IV = ivBytes;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
return encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
}
}
public static string Decrypt(byte[] encryptedBytes, byte[] keyBytes, byte[] ivBytes)
{
using (AesManaged aes = new AesManaged())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Key = keyBytes;
aes.IV = ivBytes;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
```
在上面的代码中,我们使用了128位的密钥和初始化向量,并使用CBC模式和PKCS7填充。你可以根据需要自定义这些参数。
阅读全文