OK-
I haven't taken the time to comb through the code and find what I was doing wrong. With all the arrays flying around, I suspect I just used the wrong variable somewhere.
The following code works. So it's there for anybody who wants a simple method for encrypting/decrypting byte arrays. It's hard to find examples that aren't written for the writing-an-encrypted-file-to-disk crowd.
Bear in mind that hard coding the key and IV theoretically leaves you open to some hacker reverse engineering your code and being able to easily decrypt your files. But my personal feeling on this matter is that it's infinitely more likely that a user will compromise security by leaving their password on a sticky note stuck to their monitor. And I'm not securing highly sensitive material anyway. If you have a need for greater security, use some other method for generating and keeping track of your keys and IV's.
<br />
public byte[] EncryptStream(byte[] input)<br />
{<br />
RijndaelManaged rijn = new RijndaelManaged(); <br />
byte[] encrypted; <br />
<br />
byte[] key = new byte[]{0x22,0xc0,0x6d,0xcb,0x23,0xa6,0x3,0x1b,0x5a,0x1d,0xd3,<br />
0x9f,0x85,0xd,0xc1,0x72,0xed,0xf4,0x54,0xe6,0xba,0x65,<br />
0xc,0x22,0x62,0xbe,0xf3,0xec,0x14,0x81,0xa8,0xa};
byte[] IV = new byte[]{0x43,0xb1,0x93,0xb,0x1a,0x87,0x52,0x62,0xfb,0x8,0xd,0xc0,<br />
0xca,0x40,0xc2,0xdb};
<br />
ICryptoTransform encryptor = rijn.CreateEncryptor(key, IV);<br />
<br />
MemoryStream msEncrypt = new MemoryStream();<br />
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);<br />
<br />
<br />
csEncrypt.Write(input, 0, input.Length);<br />
csEncrypt.FlushFinalBlock();<br />
csEncrypt.Close();<br />
<br />
encrypted = msEncrypt.ToArray(); <br />
<br />
return encrypted;<br />
<br />
}<br />
<br />
public byte[] DecryptStream(byte[] encrypted)<br />
{<br />
RijndaelManaged myRijndael = new RijndaelManaged(); <br />
byte[] fromEncrypt; <br />
byte[] key = new byte[]{0x22,0xc0,0x6d,0xcb,0x23,0xa6,0x3,0x1b,0x5a,0x1d,0xd3,<br />
0x9f,0x85,0xd,0xc1,0x72,0xed,0xf4,0x54,0xe6,0xba,0x65,<br />
0xc,0x22,0x62,0xbe,0xf3,0xec,0x14,0x81,0xa8,0xa};
byte[] IV = new byte[]{0x43,0xb1,0x93,0xb,0x1a,0x87,0x52,0x62,0xfb,0x8,0xd,0xc0,<br />
0xca,0x40,0xc2,0xdb};
<br />
<br />
<br />
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);<br />
<br />
MemoryStream msDecrypt = new MemoryStream(encrypted);<br />
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);<br />
<br />
fromEncrypt = new byte[encrypted.Length];<br />
<br />
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);<br />
<br />
return fromEncrypt;<br />
}<br />
enjoy-
chlock
|