在.NET中使用C#实现AES加密解密,通过Aes类结合密钥和IV完成数据保护。1. 使用Aes.Create()初始化算法并设置Key与IV;2. 加密时通过CryptoStream写入明文并转换为Base64字符串;3. 解密时用相同Key和IV读取密文流还原原文;4. 可借助Rfc2898DeriveBytes从密码和salt派生固定密钥对;5. 示例验证了加解密一致性。注意生产环境应避免硬编码密钥,推荐安全存储机制如Azure Key Vault。

在.NET中实现AES加密和解密非常常见,主要用于保护敏感数据的安全传输与存储。AES(Advanced Encryption Standard)是一种对称加密算法,支持128、192和256位密钥长度,安全性高且性能良好。下面介绍如何使用C#在.NET中实现AES加密与解密。
.NET提供了System.Security.Cryptography.Aes类来简化AES操作。该类会自动生成密钥和IV(初始化向量),也可以手动设置以保证一致性。
以下是基本的加密方法示例:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static string Encrypt(string plainText, byte[] key, byte[] iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
解密过程需要与加密时相同的密钥和IV,否则无法还原原始数据。
public static string Decrypt(string encryptedText, byte[] key, byte[] iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(encryptedText)))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
return reader.ReadToEnd();
}
}
}
}
}
如果需要跨平台或持久化保存密钥,可以使用Rfc2898DeriveBytes从密码派生出密钥和IV。
public static (byte[] Key, byte[] IV) GenerateKeyAndIV(string password, byte[] salt)
{
using (var rfc = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256))
{
byte[] key = rfc.GetBytes(32); // 256位密钥
byte[] iv = rfc.GetBytes(16); // 128位IV
return (key, iv);
}
}
调用时提供一个固定salt值(应保密但可硬编码),确保每次生成相同的密钥对。
将上述部分组合起来:
string original = "Hello, this is a secret message!";
string password = "MyStrongPassword";
byte[] salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; // 实际项目中建议随机生成并保存
var (key, iv) = GenerateKeyAndIV(password, salt);
string encrypted = Encrypt(original, key, iv);
string decrypted = Decrypt(encrypted, key, iv);
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Encrypted: {encrypted}");
Console.WriteLine($"Decrypted: {decrypted}");
运行结果会显示原文与解密后内容一致,说明加密解密成功。
注意:生产环境中不应将salt或password硬编码,密钥管理推荐使用Azure Key Vault或DPAPI等安全机制。
基本上就这些。只要保证密钥和IV一致,.NET中的AES加密解密过程稳定可靠。
以上就是.NET怎么实现AES加密和解密_AES加密解密实现教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号