This project has moved. For the latest updates, please go here.

using GCM with TagSize=96 throws CryptographicException

Jan 16, 2013 at 3:21 PM
Edited Jan 17, 2013 at 6:35 AM

When i try authenticated encryption using GCM, TagSize=96 and plain text >= 16 bytes an CryptographicException throws:

 System.Security.Cryptography.CryptographicException : An invalid parameter was passed to a service or function.
   at Security.Cryptography.BCryptNative.SymmetricEncrypt(SafeBCryptKeyHandle key, Byte[] input, Byte[] chainData, ref BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authenticationInfo) in BCryptNative.cs: line 1028   at Security.Cryptography.BCryptAuthenticatedSymmetricCryptoTransform.CngTransform(Byte[] input, Int32 inputOffset, Int32 inputCount) in BCryptAuthenticatedSymmetricCryptoTransform.cs: line 388   at Security.Cryptography.BCryptAuthenticatedSymmetricCryptoTransform.TransformBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[] outputBuffer, Int32 outputOffset) in BCryptAuthenticatedSymmetricCryptoTransform.cs: line 297   at System.Security.Cryptography.CryptoStream.Write(Byte[] buffer, Int32 offset, Int32 count)

 

using (AuthenticatedAesCng aes = new AuthenticatedAesCng())
{
    aes.CngMode = CngChainingMode.Gcm;
    aes.KeySize = 128;
    aes.TagSize = 96;
    aes.Padding = PaddingMode.None;

    aes.GenerateIV();
    aes.GenerateKey();

    aes.AuthenticatedData = 
        new byte[] { 0x30,0xAA,0xAA,0xAA,0xAA,0xBB,0xBB,0xBB,0xBB,0xCC,0xCC,0xCC,0xCC,0xDD,0x14,0x15,0x16 };

    using (MemoryStream ms = new MemoryStream())
    using (IAuthenticatedCryptoTransform encryptor = aes.CreateAuthenticatedEncryptor())
    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
    {
        byte[] plaintext = 
            new byte[] { 0xAA,0xAA,0xAA,0xAA,0xBB,0xBB,0xBB,0xBB,0xCC,0xCC,0xCC,0xCC,0xDD,0x14,0x15,0x16 };
        cs.Write(plaintext, 0, plaintext.Length);

        cs.FlushFinalBlock();

        byte[] cipherText = ms.ToArray();
        byte[] authenticationTag = encryptor.GetTag();
    }
}