0

I'm trying to encrypt a buffer with RijndaelManaged class without any success. It always return byte[0]. Here's the code:

    public byte[] Encrypt(byte[] data, byte[] key)
    {
        using (var ms = new MemoryStream())
        {
            using (var aes = RijndaelManaged.Create())
            {
                aes.Key = _checksumProvider.CalculateChecksum(key);
                aes.IV = _checksumProvider.CalculateChecksum(key);
                var stream = new CryptoStream(ms, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write);
                stream.Write(data, 0, data.Length);
                return ms.ToArray();
            }
        }
    }

Key and IV are correctly assigned. Any idea what's wrong with the code? Thanks.

Davita
  • 8,928
  • 14
  • 67
  • 119
  • With CBC mode an IV should never be used again for the same key, here it looks like you are definitely reusing the IV, if not also using the key as the IV! http://crypto.stackexchange.com/questions/5997/two-way-encryption-with-random-iv – jbtule Apr 19 '13 at 19:59
  • 1
    Not sure if you care about FIPS compliance, but just a warning that The RijindaelManaged class is NOT FIPS complaint. Instead you can use the AesCryptoServiceProvider class which is an FIPS equivalent of RijindaelManaged. If a user has “fipsalgorithmpolicy” turned on in the registry this will throw a “Error: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms”. You can find more info at http://blogs.msdn.com/b/winsdk/archive/2009/11/04/is-rijndaelmanaged-class-fips-complaint.aspx – Sam Plus Plus Apr 19 '13 at 20:04
  • Why do you use streams at all? What about simply calling `TransformFinalBlock`? – CodesInChaos Apr 19 '13 at 23:38

1 Answers1

4

You need to call stream.FlushFinalBlock().

This will perform any final steps in the encryption, and flush the CryptoStream's internal buffer into the underlying memory stream.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964