在使用C#加密音频文件时,我得到一个例外,即“指定的本地化向量(IV)与算法的块大小不匹配”。我正在使用密码学课程提供的Rijndael算法。我该怎么办才能解决这个异常? 我的代码如下:
public void EncryptFile(string inputFile, string outputFile)
{
try
{
inputFile = textBox_path.Text;
String password = "keykey";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
MessageBox.Show("encryption is completed!!");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
我的函数调用是:
答案 0 :(得分:0)
有一个类似的问题here。
使用Rijndael,您可以选择块大小为128,160,192,224或256位。然后,您必须选择相同长度的初始化向量:
using (RijndaelManaged rm = new RijndaelManaged())
{
rm.BlockSize = 128;
Rfc2898DeriveBytes keyDerivator = new Rfc2898DeriveBytes(password, salt, KeyGenIterationCount); //derive key and IV from password and salt using the PBKDF2 algorithm
rm.IV = keyDerivator.GetBytes(16); //16 bytes (128 bits, same as the block size)
rm.Key = keyDerivator.GetBytes(32);
//(encrypt here)
}
无论如何,我建议使用AesCryptoServiceProvider类,因为它是FIPS兼容的。点击此处了解有关差异的更多信息:http://blogs.msdn.com/b/shawnfa/archive/2006/10/09/the-differences-between-rijndael-and-aes.aspx