Click here to Skip to main content
15,885,910 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,
i have to encrypt a Serializable Class (that i have written) into a Stream (that will become a file or a file on a ftp site) and the opposite (from a stream to a class).

this is the code i have written:

Code to encrypt:

Out = new System.IO.FileStream("[Removed path]", System.IO.FileMode.Create);
Rijndael Alg = Rijndael.Create(); 
Alg.IV = ASCIIEncoding.ASCII.GetBytes(K);
Alg.Key = ASCIIEncoding.ASCII.GetBytes(K);
Alg.Padding = PaddingMode.Zeros;
CryptoStream streamC = new CryptoStream(Out, Alg.CreateEncryptor(), CryptoStreamMode.Write);
Form.Serialize(streamC, InstanceOfMyClass);
streamC.FlushFinalBlock();
streamC.Close();
Out.Close();


Code to decrypt:

In = new System.IO.FileStream("[Removed path]", System.IO.FileMode.Open, FileAccess.ReadWrite);
Rijndael Alg = Rijndael.Create();
Alg.IV = ASCIIEncoding.ASCII.GetBytes(K); 
Alg.Key = ASCIIEncoding.ASCII.GetBytes(K); 
Alg.Padding = PaddingMode.Zeros;
byte[] sorg = new byte[(int)In.Length];
In.Read(sorg, 0, (int)In.Length);
MemoryStream tmp = new MemoryStream();
CryptoStream streamC = new CryptoStream(tmp, Alg.CreateDecryptor(), CryptoStreamMode.Write);
streamC.Write(sorg, 0, sorg.Length);
streamC.FlushFinalBlock(); 
MyClass d = (MyClass)Form.Deserialize(tmp);
tmp.Close(); In.Close();
return d;


The encryption goes well, but the decription, at the Deserialization (at the third last line) gives me the error "End of stream reached before the end of analysis.". I have struggled to find a solution, but nothing. What can i do??

Thanks in advance!
Posted
Comments
Henry Minute 3-Dec-10 17:46pm    
I do not have a solution to your problem. However, you are to be congratulated, a search for "End of stream reached before the end of analysis" only gives two hits. Both of them point here.

1 solution

I answer myself:
I don't need to transfer bytes from the decrypted stream to a new stream, and then deserialize the new stream. It's enough to initialize the cryptostream in read mode and to deserialize from it:

In = new System.IO.FileStream("[Removed path]", System.IO.FileMode.Open, FileAccess.ReadWrite);
Rijndael Alg = Rijndael.Create();
Alg.IV = ASCIIEncoding.ASCII.GetBytes(K); 
Alg.Key = ASCIIEncoding.ASCII.GetBytes(K); 
Alg.Padding = PaddingMode.Zeros;
Alg.Mode = CipherMode.CBC;

CryptoStream streamC = new CryptoStream(In, Alg.CreateDecryptor(), CryptoStreamMode.Read);
MyClass d = (MyClass)Form.Deserialize(streamCifrato);
In.Close();
return d;
 
Share this answer
 
Comments
Henry Minute 18-Dec-10 15:46pm    
Well done! Have 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900