TeamWild TeamWild - 3 months ago 112
C# Question

C# Example of AES256 encryption using System.Security.Cryptography.Aes

I need to implement AES 256 encryption /decryption and I haven't been able to find an example that works correctly.

MSDN suggests that I should use the AES class.


The Rijndael class is the predecessor of the Aes algorithm. You should use the Aes algorithm instead of Rijndael. For more information, see the entry The Differences Between Rijndael and AES in the .NET Security blog.


Could anyone point me in the direction of a good example using the AES class for AES256?

To add a little more clarity:

I have a cipher file that contains the shared key and a string of encrypted text. I need to decrypt the text and then validate it.

All the examples I've seen expect at least 2 parameters to perform the encryption/decryption.

Should I be able to infer the Initialisation vector and the key from the text in the cipher file?

This is an example of the text held in my cipher file:


ÊÚḱÌrá ƒ@†²;Ä;öDWnªóª©©¨¦L

Answer

Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.

The finally implemented code started like this:

    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }
Comments