2

これが私のコードです:

    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 が含まれていません。考えられる原因は、無効なストリームまたはシリアル化と逆シリアル化の間のオブジェクト バージョンの変更です。

どんな助けでも大歓迎です!

4

1 に答える 1

3

1 つの小さなタイプミス: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);
        }
    }
}
于 2015-03-06T07:13:07.093 に答える