![](/img/trans.png)
[英]Specified initialization vector (IV) does not match the block size for this algorithm
[英]Specified initialization vector(IV) does not match the block size for this algorithm
我正在嘗試使用c#創建加密系統。 這是加密的代碼。
public static void EncryptFile(string inFile, string outFile, string @inkey)
{
try
{
UnicodeEncoding ue = new UnicodeEncoding();
byte[] key = ue.GetBytes(inkey);
FileStream fsEncrypt = new FileStream(outFile, FileMode.Create);
RijndaelManaged rmCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsEncrypt, rmCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inFile, FileMode.Open);
int data;
while((data=fsIn.ReadByte()) != 1){
cs.WriteByte((byte)data);
}
fsIn.Close(); cs.Close(); fsEncrypt.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Fail to encrypt", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
現在,這個代碼每次運行時拋出異常,說
指定的初始化向量(IV)與此算法的塊大小不匹配
我已閱讀其他有關此問題的討論,並說字節數存在問題(傳遞給此函數的密鑰長度為255)。 但我已經嘗試使密鑰只有16個字節仍然無法正常工作。
經過一些故障排除我發現這部分:
CryptoStream cs = new CryptoStream(fsEncrypt, rmCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
拋出異常。 我不知道為什么。 有人可以幫忙嗎?
您將密鑰傳遞兩次到CreateEncryptor
,但它需要一個密鑰和一個IV( 初始化向量 )。 第二個參數應該是一個包含128個隨機位的數組。 128位是RijndaelManaged的默認塊大小,但它也接受其他值(例如256)。 閱讀本文以獲取更多信息。 正如Grzegorz W在評論中指出的那樣,您可能還需要選擇不同的密鑰大小 。
如果您不熟悉加密(在這種情況下,您應該在實現自己的解決方案之前停止並了解更多信息,或者使用現成的解決方案), IV的功能是防止相同的消息編碼兩次產生相同的密文。 它應該是隨機的每條消息(以及消息的每次使用),不需要保密,但你需要存儲它以便以后能夠解密消息(即加密后你不能丟棄它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.