/// <summary> /// Performs AES encryption in GCM chaining mode over plain text /// </summary> /// <param name="key">aes key</param> /// <param name="iv">initialization vector</param> /// <param name="aad">additional authn data</param> /// <param name="plainText">plain text message to be encrypted</param> /// <returns>2 byte[] arrays: [0]=cipher text, [1]=authentication tag</returns> /// /// <exception cref="CryptographicException">if encryption failed by any reason</exception> public static byte[][] Encrypt(byte[] key, byte[] iv, byte[] aad, byte[] plainText) { using var gcm = new System.Security.Cryptography.AesGcm(key); var ciphertext = new byte[plainText.Length]; var tag = new byte[System.Security.Cryptography.AesGcm.TagByteSizes.MaxSize]; gcm.Encrypt(nonce: iv, plaintext: plainText, ciphertext: ciphertext, tag: tag, associatedData: aad); return(new byte[][] { ciphertext, tag }); }
internal static AesGcmAuthenticated Encrypt(byte[] secretKeyBytes, byte[] nonce, byte[] plaintext, byte[] aad) { #if NETSTANDARD2_1 byte[] ciphertext = new byte[plaintext.Length]; byte[] authTag = new byte[System.Security.Cryptography.AesGcm.TagByteSizes.MaxSize]; using (var aes = new System.Security.Cryptography.AesGcm(secretKeyBytes)) { aes.Encrypt(nonce, plaintext, ciphertext, authTag, aad); } return(new AesGcmAuthenticated(ciphertext, authTag)); #else throw new EncryptionException("AES/GCM/NoPadding is unsupported on .NET Standard < 2.1"); #endif }
public void Encrypt(ReadOnlySpan <byte> nonce, ReadOnlySpan <byte> plaintext, Span <byte> ciphertext, Span <byte> tag) { _aesGcm.Encrypt(nonce, plaintext, ciphertext, tag); }
Encrypt(byte[] key, byte[] plainText, byte[] nonce = null) { if (plainText == null) { throw new ArgumentException("AesGcm plaintext must not be null."); } if (key == null || key.Length != 32) { throw new ArgumentException("AesGcm key must be 32 bytes long."); } // Authentication tag. byte[] tag = new byte[16]; // IV. byte[] _nonce = new byte[12]; if (nonce == null) { Rng.GetBytes(_nonce); } else { if (nonce.Length != 12) { throw new ArgumentException("AesGcm must be 12 bytes long."); } _nonce = nonce; } byte[] cipherText = new byte[plainText.Length]; using (var c = new SysCrypto.AesGcm(key)) { try { c.Encrypt(_nonce, plainText, cipherText, tag, null); } catch (Exception e) { Debug.WriteLine(e.Message); return(null); } } byte[] infoCipher = new byte[_nonce.Length + cipherText.Length + tag.Length]; Buffer.BlockCopy( _nonce, 0, infoCipher, 0, _nonce.Length ); Buffer.BlockCopy( cipherText, 0, infoCipher, _nonce.Length, cipherText.Length ); Buffer.BlockCopy( tag, 0, infoCipher, _nonce.Length + cipherText.Length, tag.Length ); return(infoCipher); }