这是我的代码:
public static void Save<T>(T toSerialize, string fileSpec) {
BinaryFormatter formatter = new BinaryFormatter();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (FileStream stream = File.Create(fileSpec)) {
using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(key, iv), CryptoStreamMode.Write)) {
formatter.Serialize(cryptoStream, toSerialize);
cryptoStream.FlushFinalBlock();
}
}
}
public static T Load<T>(string fileSpec) {
BinaryFormatter formatter = new BinaryFormatter();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (FileStream stream = File.OpenRead(fileSpec)) {
using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(key, iv), CryptoStreamMode.Read)) {
return (T)formatter.Deserialize(cryptoStream);
}
}
}
Key和iv都是静态字节数组,长度为8,我将其用于测试目的。有错误如下:
二进制流&#39; 178&#39;不包含有效的BinaryHeader。可能的原因是序列化和反序列化之间的无效流或对象版本更改
非常感谢任何帮助!
答案 0 :(得分:3)
一个小错字:您的Load
方法应该使用des.CreateDecryptor
,如下所示:
public static T Load<T>(string fileSpec)
{
BinaryFormatter formatter = new BinaryFormatter();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (FileStream stream = File.OpenRead(fileSpec))
{
using (CryptoStream cryptoStream =
new CryptoStream(stream, des.CreateDecryptor(key, iv),
CryptoStreamMode.Read))
{
return (T)formatter.Deserialize(cryptoStream);
}
}
}