C# “Bad Data” exception when decrypting encrypted file

こ雲淡風輕ζ 提交于 2019-12-01 11:03:14

Here:

    cryptostream.Write(byteArrayInput, 0, byteArrayInput.Length);
    fsIn.Close();
    fsOut.Close();

You're closing fsOut directly, without closing cryptostream. That means the crypto stream doesn't get the chance to flush any final blocks etc.

Additionally:

  • Use using statements instead of manually calling Close or Dispose
  • You're currently calling Read once, and assuming it will read all the data - you're not checking the return value. (You're also removing the last byte of the input file for some reason... why?) In general, you should loop round, reading into a buffer and then writing out however many bytes you read, until the Read method returns 0. If you're using .NET 4, Stream.CopyTo is your friend.
  objCryptStream.CopyTo(stream);

Worked for me, complete code is

 public static string DecryptString(string encriptedText, string key)
   {

       try
       {


           //Convert the text into bytest
           byte[] ecriptedBytes = System.Convert.FromBase64String(encriptedText);

           // Create a memory stream to the passed buffer
           MemoryStream objMemStream = new MemoryStream(ecriptedBytes);

           //Set the legal keys and initialization verctors
           objCrptoService.Key = GetLegalsecretKey(key);
           objCrptoService.IV = GetLegalIV();

           // Create a CryptoStream using the memory stream and the cryptographic service provider  version
           // of the Data Encryption stanadard algorithm key
           CryptoStream objCryptStream = new CryptoStream(objMemStream, objCrptoService.CreateDecryptor(), CryptoStreamMode.Read);

           // Create a StreamReader for reading the stream.
           //StreamReader objstreamReader = new StreamReader(objCryptStream);
           MemoryStream stream = new MemoryStream();
           objCryptStream.CopyTo(stream);
           stream.Position = 0;
           StreamReader R = new StreamReader(stream);
           string outputText = R.ReadToEnd();

           // Close the streams.
           R.Close();
           objCryptStream.Close();
           objMemStream.Close();

           return outputText;
       }
       catch (Exception exc)
       {
           return "";
       }
   }

What fixed my issue was calling FlushFinalBlock on cryptostream, When creating the file

                CryptoStream cryptostream = new CryptoStream(memoryStream, this._encryptionKeyHelper.Encryptor(), CryptoStreamMode.Write);

            xmlser.Serialize(cryptostream, builderObject);

            cryptostream.FlushFinalBlock();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!