抛出异常:' System.Security.Cryptography.CryptographicException' in mscorlib.dll其他信息:错误数据

时间:2017-04-13 05:33:16

标签: c# wpf cryptography

我使用代码来解密我的文件。但是当我写回输出文件时,它显示错误:BAD DATA

以下是我提供的代码,提到了错误即将发生的行。

public static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
    {
        try
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            //A 64 bit key and IV is required for this provider.
            //Set secret key For DES algorithm.
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            //Set initialization vector.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            //Create a DES decryptor from the DES instance.
            ICryptoTransform desdecrypt = DES.CreateDecryptor();

            //Create a file stream to read the encrypted file back.
            using (FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read))
            {

                //Create crypto stream set to read and do a 
                //DES decryption transform on incoming bytes.
                using (CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read))
                {
                    fsread.Flush();
                    //Print the contents of the decrypted file.
                    StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);

                    ////----ERROR IN THIS LINE----////
                    fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
                    fsDecrypted.Flush();
                    fsDecrypted.Close();
                }
            }
        }
        catch(XamlParseException XEx)
        {
            //throw XEx;
            System.Windows.MessageBox.Show(XEx.Message.ToString());
        }
    } 

加密代码

同时使用相同的GETBYTE

public static void EncryptFile(string sInputFilename,string sOutputFilename,string sKey)
    {
        FileStream fsInput = new FileStream(sInputFilename,FileMode.Open,FileAccess.Read);

        FileStream fsEncrypted = new FileStream(sOutputFilename,FileMode.Create,FileAccess.Write);

        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

        ICryptoTransform desencrypt = DES.CreateEncryptor();
        CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);

        byte[] bytearrayinput = new byte[fsInput.Length - 1];
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
    }

1 个答案:

答案 0 :(得分:0)

最可能的原因是您使用DES.IV字节初始化sKey。您应该在此处使用与使用dyring加密相同的初始化向量。