You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6.0中C# AES加解密二进制数据失败问题排查

AES加解密错误分析与修复

核心错误点

  • 解密数据读取逻辑错误:解密时直接调用cipherStream.ToArray(),拿到的是未经过CryptoStream处理的原始密文,根本没有执行解密操作,自然得不到原始明文。
  • 数组相等判断方式错误:plainBytes.Equals(wrongPlainBytes)是比较两个数组的引用地址,而非内容是否一致,应该用plainBytes.SequenceEqual(wrongPlainBytes)来对比数组内容。

修复后的完整代码

public static byte[] Encrypt(byte[] plainBytes)
{
    using (var aes = System.Security.Cryptography.Aes.Create())
    {
        byte[] cipherBytes;

        // 加密流程优化:直接用ToArray获取密文,无需手动Seek和Read
        using (MemoryStream cipherStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(cipherStream, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
        {
            cryptoStream.Write(plainBytes, 0, plainBytes.Length);
            cryptoStream.FlushFinalBlock();
            cipherBytes = cipherStream.ToArray();
        }

        byte[] correctPlainBytes;
        // 修复解密流程:从CryptoStream读取解密后的数据
        using (MemoryStream cipherStream = new MemoryStream(cipherBytes))
        using (CryptoStream cryptoStream = new CryptoStream(cipherStream, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Read))
        using (MemoryStream plainStream = new MemoryStream())
        {
            cryptoStream.CopyTo(plainStream);
            correctPlainBytes = plainStream.ToArray();
        }

        // 用SequenceEqual对比数组内容
        bool shouldBeTrue = plainBytes.SequenceEqual(correctPlainBytes);

        return cipherBytes;
    }
}

额外注意事项

  • 实际业务场景中,加密生成的aes.Key和aes.IV需要和密文一起存储/传输(Key需安全保管,禁止明文暴露),否则后续无法完成解密。
  • 加密流程中cipherStream.ToArray()可以直接获取完整密文,无需手动执行Seek和Read操作,简化代码逻辑。

内容的提问来源于stack exchange,提问作者user20138168

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:25:17