繁体   English   中英

指定的初始化向量 (IV) 与此算法的块大小不匹配

[英]Specified initialization vector (IV) does not match the block size for this algorithm

我正在研究一种基本的加密方法。 我正在使用 RijndaelManaged。 我很久以前从某个地方得到了这个代码,但不记得在哪里。

我之前让我的代码工作,但有些事情发生了变化,我无法弄清楚。

当我运行我的代码时,出现以下错误;

指定的初始化向量 (IV) 与此算法的块大小不匹配。

这是我的代码:

string textToEncrypt = "TEST STRING";

int keySize = 256;
string hashAlgorithm = "SHA1";
string passPhrase = "AH!PSB0%FGHR$";
string saltValue = "LRT%YUR#VBNL@1";
string initVector = "HR$2pIjHR$2pIj";

byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

byte[] plainTextBytes = Encoding.UTF8.GetBytes(textToEncrypt);

var password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, 2);

byte[] keyBytes = password.GetBytes(keySize / 8);

RijndaelManaged symmetricKey = new RijndaelManaged();

symmetricKey.Mode = CipherMode.CBC;

ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);

MemoryStream memoryStream = new MemoryStream();

var cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

cryptoStream.FlushFinalBlock();

byte[] cipherTextBytes = memoryStream.ToArray();

memoryStream.Close();
cryptoStream.Close();

string cipherText = Convert.ToBase64String(cipherTextBytes);

任何帮助将不胜感激。

问题是您的初始化向量大小需要为 16 字节。

您的初始向量大小为 14 字节。

您需要将初始向量的大小增加 2 个字节,您的代码才能工作。

例子:

string initVector = "HR$2pIjHR$2pIj12";

然后,您将获得包含当前代码和示例 IV(初始化向量)大小的输出:

hAC8hMf3N5Zb/DZhFKi6Sg==

这篇文章很好地解释了初始化向量是什么。

http://en.wikipedia.org/wiki/Initialization_vector

您应该能够检查 IV 需要使用多少字节:

algorithm.BlockSize / 8

BlockSize 以位为单位,因此 128 位 / 8 给出 16 字节的 ASCII,您可能还会发现Rfc2898DeriveBytes是生成密钥的有用类。

algorithm.IV = rfc2898DeriveBytesForIV.GetBytes(algorithm.BlockSize / 8);

希望能帮助到你。

如果有人将他们的代码从 .NET Framework 迁移到 .NET Core 并开始在RijndaelManaged.CreateEncryptor上收到此异常:由于“ .NET Framework 允许大于 64 位的 IV 并截断它们”,您的旧感冒正在起作用。

要解决,请参阅Kevin Jones评论:“ 只需将您的 IV 更改为仅前 8 个字节

所以,作为一个例子:

private static byte[] IV_192 =  { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 };

会成为:

// Rename field if desired.
private static byte[] IV_192 =  { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };

另外值得注意的是,“ Rijndael 类是 Aes 算法的前身。你应该使用 Aes 算法而不是 Rijndael。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM