Hello all and Happy Holidays!
I am working on a purely academic project trying to get ready for taking my 70-536 MS cert test. The subject if security and encryption. As a way of reinforcing the encryption concept in my mind I have set out creating a library project for encrypting objects. I was hoping to create one static encrypt method that takes a System.Object, string key and string Vector Initialization and returns that object encrypted. I can do this easily just using strings but, when I make the method accept a Object I have problems.
This is the main 'Encrypt' method:
public static object Encrypt(Object itemToEncrypt, string key, string vi)
{
if (itemToEncrypt == null)
throw new ArgumentNullException
("The item which needs to be encrypted can not be null.");
}
byte[] keyBytes = ASCIIEncoding.ASCII.GetBytes(key);
byte[] viBytes = ASCIIEncoding.ASCII.GetBytes(vi);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
cryptoProvider.CreateEncryptor(keyBytes, viBytes), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream);
writer.Write(itemToEncrypt);
cryptoStream.FlushFinalBlock();
writer.Flush();
return HelperMethods.ByteArrayToObject(memoryStream.GetBuffer());
The problem happens when I call the Helper Method ByteArrayToObject:
public static Object ByteArrayToObject(byte[] arrBytes)
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
memStream.Flush();
memStream.Position = 0;
Object obj = binForm.Deserialize(memStream); <===
return obj;
Where the binForm.Deserialize method is called (Arrow to right) I get the following error:
{"Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization."}
While I see explanations of this error all over, none of the suggestions have helped solve this problem.
Please forgive me in advance if I am missing something obvious. However, any and all suggestions would be greatly appreciated.
Best regards,
rbr