序列化到内存然后加密

时间:2015-04-13 10:24:40

标签: c# serialization encryption

Object p=new Object();
//stream-this is the stream to the file.

using (MemoryStream ms = new MemoryStream())
{
     BinaryFormatter msSeri = new BinaryFormatter();
     msSeri.Serialize(ms, p);

     DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
     cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
     cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");       
     CryptoStream crStream = new                        
     CryptoStream(ms,cryptic.CreateEncryptor(),CryptoStreamMode.Write);
     byte[] data = ASCIIEncoding.ASCII.GetBytes(ms.ToString());
     crStream.Write(data,0,data.Length);
     crStream.Close();
     BinaryFormatter seri = new BinaryFormatter();
     if (stream != null)
         seri.Serialize(stream, seri.Deserialize(crStream));
}

我需要序列化才能只加密加密数据,所以我先尝试序列化到内存,然后加密,然后序列化为文件。 我在这一行得到了Argument异常 -

seri.Serialize(stream, seri.Deserialize(crStream));

我是新手,欢迎任何帮助。 我不知道我是怎么做的甚至是正确的,我使用的是我在网上找到的例子。

1 个答案:

答案 0 :(得分:1)

        string path = "D:\\changeit.txt";
        Object p = new Object();

        using (Stream stream = File.Create(path))
        {           
            DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
            cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            using (CryptoStream crStream = new
                  CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] data = ASCIIEncoding.ASCII.GetBytes(stream.ToString());
                crStream.Write(data, 0, data.Length);

                BinaryFormatter seri = new BinaryFormatter();
                seri.Serialize(crStream, p);
            }
        }

基本上你需要一个FileStream和一个CryptoStream。并使用using(),没有close()。

反序列化示例:

        using (Stream readStream = File.OpenRead(path))
        {
            DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
            cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            using (CryptoStream crStream = 
                new CryptoStream(readStream, cryptic.CreateDecryptor(), CryptoStreamMode.Read))
            {
                byte[] data = ASCIIEncoding.ASCII.GetBytes(readStream.ToString());
                crStream.Read(data, 0, data.Length);

                BinaryFormatter formatter = new BinaryFormatter();
                object obj = formatter.Deserialize(crStream);                    
            }
        }