“指定的初始化向量(IV)与使用CryptoStream的此算法的块大小不匹配

时间:2012-04-25 19:43:39

标签: c# .net rijndaelmanaged 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;”似乎不起作用,所以我怎么能修复我的错误?

4 个答案:

答案 0 :(得分:4)

像Rijndael这样的块密码需要长度等于块大小的密钥和IV,通常为256位。

此外,对于每封邮件,IV必须是唯一的,否则您的数据将不安全。

答案 1 :(得分:2)

错误是:

managed.CreateEncryptor(bytes, bytes)

其中bytes需要为128位(16字节),192位(24字节)或256位(32字节),用于第一个(键)第二个参数

注意:

  • 对于 AES 互操作性,您应使用Rijndael,其中BlockSize为128位(16字节)。

  • UnicodeEncoding会(经常)给你弱密码。看看使用PKCS#5从密码创建一个强密钥(和IV)。对于.NET,请查看RFC2898DeriveBytes;

  • 避免对密钥和IV使用相同的数据;

答案 2 :(得分:0)

这一行:

managed.CreateEncryptor(bytes, bytes)

不起作用。第一个参数是键,第二个参数是初始化向量。如果您打算将字符串s用作“密码”或密钥,请尝试使用Rfc2898DeriveBytes从密码生成密钥。

答案 3 :(得分:0)

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);
            }
}