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

时间:2018-10-08 09:48:47

标签: c# encryption .net-core rijndael .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);

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

  

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

更新

根据this,由于@ Access-Denied的回复,我注意到这在dotnet核心文档中可能是一个错误,我不能将256长的BlockSize与{{ 1}}类。如前所述,加密的数据将被发送到第三方服务。我必须将Rijndael与32长的RijndaelManaged一起使用。我该如何处理?

1 个答案:

答案 0 :(得分:6)

最好的文档是源代码。根据他们的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);