引发异常:在 mscorlib 中'System.Security.Cryptography.CryptographicException'.dll 其他信息:错误数据



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

下面是我的代码提供,在出现错误的地方提到了行。

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

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

相关内容

  • 没有找到相关文章

最新更新