Please check array copying


_DeriveCipher method

Array.Copy for me is not working correctly.

Changed to:
        private void _DeriveCipher()
            SHA512Managed sha = new SHA512Managed();
            sha.TransformBlock(secretKey, 0, secretKey.Length, secretKey, 0);
            sha.TransformFinalBlock(cipherSalt, 0, cipherSalt.Length);

            aes = new AesManaged
                    KeySize = (int) AesKeyBits,
                    IV = IV,
                    Key = sha.Hash.Take((int) (AesKeyBits/8)).ToArray(),
                    Mode = CipherMode.CBC


dangriffin wrote Jun 4, 2013 at 11:03 PM

Is it that it's a .NET 4.5 routine? Or are the bytes values coming out wrong?

Can you please be more specific?

MartinDevillers wrote Nov 28, 2014 at 4:03 PM

I am seeing the same behavior on my side. Specifically the line:

Array.Copy(sha.Hash, aes.Key, aes.Key.Length);

Array.Copy does not copy the actual contents of sha.Hash to the destination array. As a result, aes.Key remains an empty byte array, which means that the actual security key is not used!!!. You can easily test this by using different keys to do the encryption and decryption.

This is a fundamental security flaw!

wrote Nov 28, 2014 at 4:06 PM

MartinDevillers wrote Nov 28, 2014 at 4:27 PM

Here's a very quick and dirty fix. Linq is deifnately not the best way to handle byte arrays but it works. The offending line is at number 71 in CryptoHlper.cs

//Array.Copy(sha.Hash, aes.Key, aes.Key.Length);
aes.Key = sha.Hash.Take(aes.Key.Length).ToArray();

wrote Dec 2, 2014 at 12:12 AM