![](/img/trans.png)
[英]The 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” using an CryptoStream
使用CryptoStream进行文件加密时遇到了麻烦。
码:
public static void EncryptFile(string inputFile, string outputFile)
{
int num;
string s = "PUPlr";
byte[] bytes = new UnicodeEncoding().GetBytes(s);
string path = outputFile;
FileStream stream = new FileStream(path, FileMode.Create);
RijndaelManaged managed = new RijndaelManaged();
CryptoStream crpytStream = new CryptoStream(stream, managed.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
FileStream stream2 = new FileStream(inputFile, FileMode.Open);
while ((num = stream2.ReadByte()) != -1)
{
crpytStream.WriteByte((byte)num);
}
stream2.Close();
crpytStream.Close();
stream.Close();
}
尝试“ managed.BlockSize = 16;” 或“ = 128;” 似乎不起作用,那么如何解决错误?
像Rijndael这样的块密码需要长度等于块大小(通常为256位)的密钥和IV。
此外,IV对于每条消息必须唯一,否则您的数据将不安全。
错误是:
managed.CreateEncryptor(bytes, bytes)
其中第一个(关键字) 和第二个参数的bytes
必须为128位(16字节),192位(24字节)或256位(32字节)。
笔记:
为了实现AES互操作性,您应该使用BlockSize
为128位(16字节)的Rijndael
。
UnicodeEncoding
通常会为您提供弱密码。 看一下使用PKCS#5从密码创建一个强键(和IV)。 对于.NET,请参阅RFC2898DeriveBytes ;
避免对密钥和IV使用相同的数据;
这行在这里:
managed.CreateEncryptor(bytes, bytes)
不起作用 第一个参数是键,第二个参数是初始化向量。 如果您打算将字符串s
用作“密码”或密钥,请尝试使用Rfc2898DeriveBytes
从密码生成密钥。
public static void EncryptFile(string input, string output)
{
string theKey = "urKey";
byte[] salt = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c };
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(theKey, salt);
RijndaelManaged RMCrypto = new RijndaelManaged();
using (var inputStream=new FileStream(input))
using (var outputStream = new FileStream(output))
using (CryptoStream cs = new CryptoStream(inputStream, RMCrypto.CreateEncryptor(pdb.GetBytes(32), pdb.GetBytes(16)), CryptoStreamMode.Read))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
do
{
bytesRead = cs.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.