这是我的代码:
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的静态字节数组,我将其用于测试目的。错误如下:
二进制流"178"不包含有效的BinaryHeader。可能的原因是序列化和反序列化之间的无效流或对象版本更改
非常感谢您的帮助!
一个小错误: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);
}
}
}