簡體   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