I have my pre generated AES key what i would like to use in C#. Can anybody point me to the right direction how to use pre generated AES key with RijndaelManaged object.
EDIT: I have the key in byte[] array and i need to encrypt a Stream.
I found these code samples online:
private static byte[] Decrypt(byte[] key, byte[] PGPkey)
{
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = key;
//rDel.Mode = CipherMode.ECB; // http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode.aspx
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(PGPkey, 0, PGPkey.Length);
return resultArray;
}
private static byte[] Encrypt(byte[] key, byte[] PGPkey)
{
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = key;
//rDel.Mode = CipherMode.ECB; // http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode.aspx
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(PGPkey, 0, PGPkey.Length);
return resultArray;
}
Im not getting any errors but after decryption the byte array is not the same as it was before going to the ecryption.
EDIT: I think i got it working, had to set the rDel.Mode = CipherMode.ECB;
If it worked when setting it to
ECBmode, that is becuase it was usingCBCmode before, which uses a randomly generated Initialization Vector when encrypting. Initialization Vectors randomize the cipher text so two identical peiced of data, encrypted with the same key, dont produce the same cipher text. You can grab thebyte[] RijndaelManagedInstance.IVproperty and store that with your cipher text. Then when decrypting, set the same property to the Initialization Vector used to encrypt, and then you should recieve the same plain text after decryption.