加密异常 - 错误数据

时间:2016-04-04 20:28:17

标签: c# exception encryption cryptography

这是Windows窗体项目。我有解密加密文件的问题。它抛出了一个例外:

  • CryptographicException
  • 其他信息:错误数据。

这是图片链接: http://i.imgur.com/aPggrcP.png

以下是解密所需的代码:

DESCryptoServiceProvider des = new DESCryptoServiceProvider();

OpenFileDialog ofd2 = new OpenFileDialog();

private void button4_Click(object sender, EventArgs e)
{
    if (ofd2.ShowDialog() == DialogResult.OK)
    {
        richTextBox4.Text = ofd2.SafeFileName;
    }
} private void richTextBox4_TextChanged(object sender, EventArgs e){}

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }
}

private void dec_Click(object sender, EventArgs e)
{
    string pathK = ofd2.FileName;

    if (File.Exists(pathK))
    {
        string dirPath = Path.GetDirectoryName(ofd2.FileName);
        string pathH = dirPath + "/DE" + ofd2.SafeFileName;

        if (File.Exists(pathH))
        {
            using (FileStream filestream = new FileStream(pathK, FileMode.Open))
            {
                using (CryptoStream stream = new CryptoStream(filestream, des.CreateDecryptor(des.Key, des.IV), CryptoStreamMode.Read))
                {
                    using (FileStream fsDecrypted = new FileStream(pathH, FileMode.Open, FileAccess.Write))
                    {
                        CopyStream(stream, fsDecrypted);
                    }
                }
            }
        }
        else
        {
            using (FileStream filestream = new FileStream(pathK, FileMode.Open))
            {
                using (CryptoStream stream = new CryptoStream(filestream, des.CreateDecryptor(des.Key, des.IV), CryptoStreamMode.Read))
                {
                    using (FileStream fsDecrypted = new FileStream(pathH, FileMode.CreateNew, FileAccess.Write)) 
                    {
                        CopyStream(stream, fsDecrypted);
                    }
                }
            }
        }
    }
    else 
    {
        decTextBox.Text = "Cannot find encrypted file !";
    }          
} private void decTextBox_TextChanged(object sender, EventArgs e){}

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

通过阅读您的代码,您可能会实例化var des = new DESCryptoServiceProvider()的新实例,该实例会生成随机密钥和IV,并尝试将随机生成的des.Key和des.IV传递给CryptoStream。问题是Key和IV是根据你正在使用的构造函数随机生成的。您需要使用用于加密字节的匹配密钥和IV。

所以在某些时候你应该有类似的代码:

des.Key = theKeyUsedToEncrypt;
des.IV = theIVUsedToEncrypt;

您收到错误的数据异常,因为解密失败,因为随机生成的密钥和IV与用于加密的密钥和IV不匹配。