c# aes AES/ECB/PKCS5Padding securerandom
时间: 2024-12-24 11:25:52 浏览: 6
C# 中的 AES (Advanced Encryption Standard) 是一种对称加密算法,常用于数据的安全传输。AES/ECB/PKCS5Padding 模式表示 Electronic Codebook (电子密码本) 模式,这是一种基本的块加密模式,将明文分成固定大小的数据块,每个块独立进行加密。PKCS5Padding 则是 Padding Scheme for Privacy-Preserving Cryptosystems (公钥加密系统隐私保护填充方案) 的简称,它添加一些额外的位以保证输入长度为块大小的整数倍。
SecurRandom 是 .NET Framework 提供的一个安全随机数生成器,它用于生成加密密钥、初始化向量(IV)等随机数据,确保加密过程的随机性和不可预测性。
使用示例:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class AesExample
{
public static byte[] Encrypt(string plainText, string key, byte[] iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV, PaddingMode.PKCS7);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
return ms.ToArray();
}
}
}
}
public static string Decrypt(byte[] cipherText, string key, byte[] iv)
{
byte[] decryptedBytes = null;
try
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV, PaddingMode.PKCS7);
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decryptedBytes = Encoding.UTF8.GetBytes(sr.ReadToEnd());
}
}
}
}
}
catch { /* Handle decryption errors */ }
return Encoding.UTF8.GetString(decryptedBytes);
}
public static void Main()
{
// Generate a secure random IV
byte[] iv = new SecureRandom().GetBytes(Aes.BlockSize);
string key = "YourSecretKey"; // Replace with your own 16, 24, or 32-byte key
// Encrypt some text
string plaintext = "Hello, world!";
byte[] encrypted = Encrypt(plaintext, key, iv);
// Decrypt the data back to text
string decrypted = Decrypt(encrypted, key, iv);
Console.WriteLine($"Original: {plaintext}");
Console.WriteLine($"Encrypted: {BitConverter.ToString(encrypted)}");
Console.WriteLine($"Decrypted: {decrypted}");
}
}
```
阅读全文