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

如何在.NET Core中读取RijndaelManaged 256块大小加密的文件?

解决方案

方案1:使用BouncyCastle加密库(推荐,跨平台)

该方案是目前最成熟的兼容方案,Portable.BouncyCastle库完全支持256位块大小的Rijndael算法,可在所有.NET Core支持的平台运行。

  • 第一步:安装NuGet包
    Install-Package Portable.BouncyCastle
  • 第二步:实现匹配旧逻辑的解密方法,参考代码如下(需根据你旧应用的实际参数调整密钥派生、IV、模式等配置):
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using System.Text;

public static byte[] DecryptRijndael256BlockSize(byte[] cipherText, byte[] key, byte[] iv)
{
    // 配置Rijndael块大小为256位
    RijndaelEngine engine = new RijndaelEngine(256);
    // 匹配旧应用的CBC模式+PKCS7填充,若旧应用用了其他模式/填充需对应修改
    IBlockCipherMode cbcMode = new CbcBlockCipher(engine);
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcMode, new Pkcs7Padding());
    
    KeyParameter keyParam = new KeyParameter(key);
    ParametersWithIV keyWithIv = new ParametersWithIV(keyParam, iv);
    cipher.Init(false, keyWithIv);
    
    byte[] output = new byte[cipher.GetOutputSize(cipherText.Length)];
    int length = cipher.ProcessBytes(cipherText, 0, cipherText.Length, output, 0);
    length += cipher.DoFinal(output, length);
    
    byte[] result = new byte[length];
    Array.Copy(output, result, length);
    return result;
}
  • 参数对齐提示:必须确保解密用的密钥长度、盐值、迭代次数、IV生成规则、加密模式、填充模式和旧应用完全一致,可对照旧应用的加密代码逐一核对。如果旧应用是通过密码、盐值、迭代次数用Rfc2898DeriveBytes派生密钥和IV,.NET Core原生的Rfc2898DeriveBytes实现和.NET Framework完全兼容,可以直接用该类生成对应密钥和IV后传入解密方法。

方案2:Windows平台专属P/Invoke方案

如果你的.NET Core应用仅在Windows环境运行,可以通过调用Windows原生加密API(CNG/CAPI)实现256位块大小的Rijndael解密,该方案不需要引入第三方依赖,但不支持Linux、macOS等非Windows平台。

后续建议

待存量文件解密处理完毕后,建议后续加密切换为标准AES算法(固定128位块大小),该算法为业界通用标准,所有.NET版本及其他编程语言原生支持,兼容性和安全性都更有保障。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 12:54:04