Reputation: 1
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));
}
I need to serialize to file only the encrypted data,so i've tried to serialize to memory first,then encrypt,then serialize to file. i got Argument exception in this line-
seri.Serialize(stream, seri.Deserialize(crStream));
i'm new at this,any help will be welcomed. i dont know if how i did it is even correct,i used examples i found all over the web.
Upvotes: 0
Views: 336
Reputation: 5801
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);
}
}
Basically you need one FileStream and one CryptoStream. And use using(), no close().
Example for deserializing:
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);
}
}
Upvotes: 1