hs2d
hs2d

Reputation: 6199

C# using already created AES key

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;

Upvotes: 1

Views: 1341

Answers (2)

Petey B
Petey B

Reputation: 11569

If it worked when setting it to ECB mode, that is becuase it was using CBC mode 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 the byte[] RijndaelManagedInstance.IV property 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.

Upvotes: 1

CodesInChaos
CodesInChaos

Reputation: 108880

You need the key as a byte[]. Then you assign it to the Key property.

For encrypting using the autogenerated IV is fine. But you need to store it with your encrypted data and put it into the decryptor to decrypt your data again.

Don't use ECB, CBC is a much better fit for your use.

Upvotes: 0

Related Questions