![](/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
public static string GenerateKey()
{
AesCryptoServiceProvider aesCrypto = (AesCryptoServiceProvider)AesCryptoServiceProvider.Create();
// Use the Automatically generated key for Encryption.
return ASCIIEncoding.ASCII.GetString(aesCrypto.Key);
}
static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
// Sets the appropriate block size for the AES Encryption Method
AES.BlockSize = 128;
AES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
AES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform aesencrypt = AES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted, aesencrypt, CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
AES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//Set initialization vector.
AES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform aesdecrypt = AES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsread, aesdecrypt, CryptoStreamMode.Read);
//Print the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
我在 EncryptFile 方法的這一行中得到了標題中列出的異常。
AES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
我直接在該行之前設置了 BlockSize,並且我確定 AES 應該使用 16 字節的塊大小,那么我該怎么做才能讓它工作呢? 我不確定為什么代碼仍然存在塊大小問題。
注意:我只是在嘗試我在網上找到的一些示例,這並不意味着是一個鎖緊的 AES 實現,只是我想開始工作,以便我可以繼續了解該算法。
謝謝你的幫助。
IV 必須與塊大小完全相同,在 AES 的情況下為 16 個字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.