指定的密钥不是此算法的有效大小

use*_*618 47 c# encryption rijndaelmanaged

我有这个代码:

RijndaelManaged rijndaelCipher = new RijndaelManaged();

            // Set key and IV
            rijndaelCipher.Key = Convert.FromBase64String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912");
            rijndaelCipher.IV = Convert.FromBase64String("1234567890123456789012345678901234567890123456789012345678901234");
Run Code Online (Sandbox Code Playgroud)

我被抛出:

Specified key is not a valid size for this algorithm.

Specified initialization vector (IV) does not match the block size for this algorithm.
Run Code Online (Sandbox Code Playgroud)

这个字符串出了什么问题?我能算一下你的一些例子吗?

Ras*_*ber 71

当base64解码时,字符串"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912"产生48个字节(384位).RijndaelManaged支持128,192和256位密钥.

有效的128位密钥是new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }或者如果您需要从base64获取它:Convert.FromBase64String("AAECAwQFBgcICQoLDA0ODw==").

默认的块大小为128位,因此相同的字节数组将与IV一样工作.

  • 有趣的巧合......这是我用于所有加密算法的密钥... (51认同)
  • 实际上,它似乎支持[更多的密钥大小](http://stackoverflow.com/a/34354643/589259),但这是因为一个错误。只是不要忘记在单元测试期间解决该错误。 (2认同)

小智 5

使用随机数生成器类 (RNGCryptoServiceProvider) 用随机字节填充指定的缓冲区,如下所示:

var numberOfBits = 256; // or 192 or 128, however using a larger bit size renders the encrypted data harder to decipher

var ivBytes = new byte[numberOfBits / 8]; // 8 bits per byte

new RNGCryptoServiceProvider().GetBytes(ivBytes);

var rijndaelManagedCipher = new RijndaelManaged();

//Don't forget to set the explicitly set the block size for the IV if you're not using the default of 128

rijndaelManagedCipher.BlockSize = 256;

rijndaelManagedCipher.IV = ivBytes;
Run Code Online (Sandbox Code Playgroud)

请注意,可以使用相同的过程来派生密钥。希望这可以帮助。

  • 如果你使用随机数生成密钥来加密密码,你如何稍后回来(生成不同的随机密钥)并确认密码正确? (10认同)