解密加密文件时出现“Bad Data”异常

时间:2014-12-23 08:41:09

标签: c# file encryption

当我想要DeserializeObject时,它会出现一个错误,上面写着" Bad Data"。

文件数据转换成功后,它会在处理或关闭流

时出错 #########错误
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey, Byte[] data, Int32 ib, Int32 cb, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode PaddingMode, Boolean fDone)
at System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
   at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
   at System.IO.Stream.Close()
   at System.IO.Stream.Dispose()
   at BinaryFileHelper.DeserializeObject[T](String filename)
#########错误
private static DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider()
{
    Key = System.Text.Encoding.UTF8.GetBytes("12345678".Substring(0, 8)),
    IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }
};

public static void SerializeObject(string filename, object objectToSerialize)
{
    using (Stream stream = File.Open(filename, FileMode.OpenOrCreate))
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        using (Stream cryptoStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write))
        {
            binaryFormatter.Serialize(cryptoStream, objectToSerialize);
        }
    }
}

public static T DeserializeObject<T>(string filename)
{
    T objectFromDeserialize;
    using (Stream stream = File.Open(filename, FileMode.Open))
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        using (Stream cryptoStream = new CryptoStream(stream, cryptic.CreateDecryptor(), CryptoStreamMode.Read))
        {
            objectFromDeserialize = (T)binaryFormatter.Deserialize(cryptoStream);
        } // After conversion succeed, it gives error on disposing or closing at this line
    }
    return objectFromDeserialize;
}

1 个答案:

答案 0 :(得分:0)

问题是使用OpenOrCreate代替Create。原因是如果文件已经存在,OpenOrCreate将创建FileStream以附加到文件的末尾。而Create将在创建新文件之前删除现有文件。

public static void SerializeObject(string filename, object objectToSerialize)
{
    using (Stream stream = File.Open(filename, FileMode.Create))//Changed
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        using (Stream cryptoStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write))
        {
            binaryFormatter.Serialize(cryptoStream, objectToSerialize);
        }
    }
}