c# - 如何在 dotnet core 2.1 中使用 256 长 block 大小的 Rijndael 算法

标签 c# encryption .net-core rijndael .net-core-2.1

我正在尝试使用 RijndaelManaged 加密字符串,以便将其发送到第三方服务。我已经在旧版本的 .Net 框架(4.5、4.6.x)中实现了该过程,如下所示:

RijndaelManaged rm= new RijndaelManaged();
rm.KeySize = 256;
rm.BlockSize = 256;//causes exception in dotnet core 2.1
rm.Padding = PaddingMode.PKCS7;
rm.Key = Convert.FromBase64String(this.Key);
rm.IV = Convert.FromBase64String(this.IV);

var encrypt = rm.CreateEncryptor(rm.Key, rm.IV);

根据 documentation , RijndaelManaged 类可以与 BlockSize = 256 一起使用。但是,当代码在dotenet core 2.1中运行时,抛出异常:

System.PlatformNotSupportedException: BlockSize must be 128 in this implementation. at System.Security.Cryptography.RijndaelManaged.set_BlockSize(Int32 value)

更新

感谢@Access-Denied 的回复,根据this ,我注意到这可能是 dotnet 核心文档中的一个错误,我不能将 256 长的 BlockSizeRijndaelManaged 类一起使用。正如我提到的,加密数据将被发送到第三方服务。我必须使用带有 32 长 IV 的 Rijndael。我该如何处理?

最佳答案

最好的文档是源代码。根据他们的source code仅支持 128:

public override int BlockSize
{
    get { return _impl.BlockSize; }
    set
    {
        Debug.Assert(BlockSizeValue == 128);

        //Values which were legal in desktop RijndaelManaged but not here in this wrapper type
        if (value == 192 || value == 256)
            throw new PlatformNotSupportedException(SR.Cryptography_Rijndael_BlockSize);

        // Any other invalid block size will get the normal "invalid block size" exception.
        if (value != 128)
            throw new CryptographicException(SR.Cryptography_Rijndael_BlockSize);
    }
}

使用 BouncyCaSTLe.NetCore。在以下 link 处有可用的代码片段:

var keyBytes = password.GetBytes(Keysize / 8);
var engine = new RijndaelEngine(256);
var blockCipher = new CbcBlockCipher(engine);
var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
var keyParam = new KeyParameter(keyBytes);
var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32);

cipher.Init(true, keyParamWithIV);
var comparisonBytes = new byte[cipher.GetOutputSize(cipherTextBytes.Length)];
var length = cipher.ProcessBytes(cipherTextBytes, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length);

关于c# - 如何在 dotnet core 2.1 中使用 256 长 block 大小的 Rijndael 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699604/

相关文章:

c - 推荐的*最小*椭圆曲线库

c# - 如何在不使用 .Net Core 中的第三方记录器的情况下记录到文件?

c# - Lazy<T> ExecutionAndPublication - 可能导致死锁的示例

python - 自定义 Python 加密算法

c# - 在写入文件之前压缩 XML

encryption - 保护Docker文件系统访问

c# - AddSingleton 与异步调用?

python - 有没有办法使用 ADO.Net 连接到数据 block ?

c# - 清除 List<T> 的问题

c# - 在多个复选框上进行循环