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

thi*_*per 7 c# encryption rijndael .net-core .net-core-2.1

我正在尝试使用加密字符串,RijndaelManaged以将其发送到第三方服务。我已经在旧版本的.Net Framework(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);
Run Code Online (Sandbox Code Playgroud)

根据文档RijndaelManaged可以与class一起使用BlockSize = 256。但是,当代码在dotenet core 2.1中运行时,会引发异常:

System.PlatformNotSupportedException:在此实现中,BlockSize必须为128。在System.Security.Cryptography.RijndaelManaged.set_BlockSize(Int32值)处

更新

感谢@拒绝访问的响应,根据这个,我已经注意到,它可能是DOTNET核心文档中了一个错误,我不能长期使用256 BlockSizeRijndaelManaged类。如前所述,加密的数据将被发送到第三方服务。我必须使用32长的Rijndael IV。我该如何处理?

Acc*_*ied 6

最好的文档是源代码。根据他们的源代码,仅支持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);
          }
      }
Run Code Online (Sandbox Code Playgroud)

使用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);
Run Code Online (Sandbox Code Playgroud)

  • 最初指定的“Rijndael”允许各种块大小。正是在采用 *as* AES 时,在该化身中添加了块大小限制。因此,您绝对不应该找到声称可以实现提供可变块大小的 AES 的东西。 (3认同)
  • 对于任何使用此代码进行解密的人,应使用“false”调用“cipher.Init” (2认同)