.NET怎么实现AES加密和解密_AES加密解密实现教程

煙雲
发布: 2025-11-03 19:00:02
原创
771人浏览过
在.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加密解密实现教程

在.NET中实现AES加密和解密非常常见,主要用于保护敏感数据安全传输与存储。AES(Advanced Encryption Standard)是一种对称加密算法,支持128、192和256位密钥长度,安全性高且性能良好。下面介绍如何使用C#在.NET中实现AES加密与解密。

使用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();
                }
            }
        }
    }
}
登录后复制

生成固定密钥和IV的方法

如果需要跨平台或持久化保存密钥,可以使用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值(应保密但可硬编码),确保每次生成相同的密钥对。

度加剪辑
度加剪辑

度加剪辑(原度咔剪辑),百度旗下AI创作工具

度加剪辑 63
查看详情 度加剪辑

完整使用示例

将上述部分组合起来:

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 VaultDPAPI等安全机制。

基本上就这些。只要保证密钥和IV一致,.NET中的AES加密解密过程稳定可靠。

以上就是.NET怎么实现AES加密和解密_AES加密解密实现教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号