/// <summary> /// Encrypts the plain data with AES in Mode GCM /// </summary> /// <param name="key">Must have a length of 128, 192, or 256</param> /// <param name="plain"></param> /// <param name="associatedData">associated data is authenticated and non-confidential, because it isn't encrypted!</param> /// <returns>A encryptedDataContainer which contains the cipher text, the nonce, the tag and the associatedData</returns> public static EncryptedDataContainer Encrypt(byte[] key, byte[] plain, byte[] associatedData) { var nonce = KeyGeneration.CreateRandom(System.Security.Cryptography.AesGcm.NonceByteSizes.MaxSize * 8); // Bug in the corefx documentation, the MaxSize is in this case is in byte not in bit, see https://github.com/dotnet/runtime/issues/1910 var tag = new byte[System.Security.Cryptography.AesGcm.TagByteSizes.MaxSize]; var cipherText = new byte[plain.Length]; var aes = new System.Security.Cryptography.AesGcm(key); aes.Encrypt(nonce, plain, cipherText, tag, associatedData); return(new EncryptedDataContainer { CipherText = cipherText, Nonce = nonce, Tag = tag, AssociatedData = associatedData }); }
public void EncryptSameResultAsDotNetStandard() { byte[] plainText = new byte[] { 0xf5, 0x6e, 0x87, 0x05, 0x5b, 0xc3, 0x2d, 0x0e, 0xeb, 0x31, 0xb2, 0xea, 0xcc, 0x2b, 0xf2, 0xa5 }; var nonce = new byte[12] { 0x99, 0xaa, 0x3e, 0x68, 0xed, 0x81, 0x73, 0xa0, 0xee, 0xd0, 0x66, 0x84 }; byte[] cipherText = new byte[16]; byte[] tag = new byte[16]; _aesGcm.Encrypt(nonce, plainText, cipherText, tag); using (var aesGcmDotnetStandard = new System.Security.Cryptography.AesGcm(_key)) { byte[] expectedCipherText = new byte[16]; byte[] expectedTag = new byte[16]; aesGcmDotnetStandard.Encrypt(nonce, plainText, expectedCipherText, expectedTag); CollectionAssert.AreEqual(expectedCipherText, cipherText); CollectionAssert.AreEqual(expectedTag, tag); } }