簡體   English   中英

使用CryptoStream的“指定的初始化向量(IV)與該算法的塊大小不匹配”

[英]“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM