Here is a way of getting a byte array out of an object (note the object must be serializable). For production code, some error checking should be added. Additionally, you would have your choice of Crypto Providers. To Deserialize this, you basically reverse the process.
public byte[] Serialize(object obj)
{
byte[] bytes = new byte[0];
using (var mStream = new MemoryStream())
{
var crypt = new TripleDESCryptoServiceProvider();
crypt.IV = iv;
crypt.Key = key;
crypt.Padding = PaddingMode.Zeros;
using (var cStream = new CryptoStream(
mStream, crypt.CreateEncryptor(), CryptoStreamMode.Write))
{
var bFormatter = new BinaryFormatter();
bFormatter.Serialize(cStream, obj);
cStream.Close();
mStream.Close();
}
bytes = mStream.ToArray();
}
return bytes;
}
For test purposes I used the following for key and iv, though certainly you would want something different.
private byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
private byte[] iv = { 0, 1, 2, 3, 4, 5, 6, 7 };