如何在dotnet core 2.1中使用具有256长块大小的Rijndael算法

17

我正在尝试使用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);
根据文档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的回答,根据此处,我注意到在 dotnet core 文档中可能有错误,我不能使用 256 个字符长度的BlockSizeRijndaelManaged类一起使用。正如我提到的,加密数据将被发送到第三方服务。我必须使用具有 32 个字符长度的 IV 的 Rijndael。我该怎么办?


你真的需要一个不同于128的块大小吗?它与密钥大小无关。密钥大小为256与块大小为128完全匹配。如果加密应该与AES兼容,块大小必须为128,密钥大小为128、192或256。 - Codo
@Codo 是的,我必须使用256作为块大小。加密数据将发送到第三方服务,并且我已经从第三方获得了一个长度为32的“IV”。 - thirdDeveloper
请查看我的更新答案。 - Access Denied
你想要一个块大小为256位的Rijndael,但你使用变量名aes来保存它? 如果这不是有意的混淆,那么你可能很困惑。 - President James K. Polk
这并不是一种有意的混淆或者困惑。我明白它们之间的差别。我只是复制了第三方公司提供的示例代码。但是更改名称是个好建议。 - thirdDeveloper
1个回答

15

最好的文档是源代码。根据他们的源代码,只支持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。以下链接提供了代码片段:

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);

5
最初规定的“Rijndael”允许使用不同的块大小。当它被采用为AES时,才添加了块大小限制。因此,你肯定不应该能够找到声称实现AES并提供可变块大小的东西。 - Damien_The_Unbeliever
4
如果有人使用此代码进行解密,应该调用cipher.Init并将其设置为false - Lourens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接