AES-GCM encrypts and authenticates in one operation: the receiver gets the data back only if nobody changed a single bit of it, and of any associated data - a header, a record id - that was authenticated with it without being encrypted. Use authenticated encryption like this whenever data is stored or sent; encryption alone (CBC, CTR) lets an attacker alter the plaintext.
uses System.SysUtils, stDERUtils, // OctetString, BytesToOS stSecUtils, // MustFindCipherClass, tCipherMAC, iCompoundMode stRandom, // GetRawRandom - the nonce stDrbgAesCtr, // the random generator behind it stAESNI, // AES in hardware, on CPUs that have AES-NI stAESCT; // constant-time software AES everywhere else
Name stAESNI and stAESCT, not stAES: the first two register AES in hardware where the CPU has AES-NI (or the ARMv8 crypto extensions) and a constant-time software AES everywhere else, while stAES is table-driven and its timing depends on the key. MustFindCipherClass takes the class from that registration.
{ nonce (12) || ciphertext || tag (16). aAssociated is authenticated but not encrypted - a header, a record id, a file name - and must be given again, unchanged, to Open. } function SealWithNonce(const aKey, aNonce, aPlain, aAssociated: TBytes): TBytes; var lCipher: tCipherMAC; lLen: Integer; begin lCipher := MustFindCipherClass(caRijndael, cmGCM).CreateBytes(aKey, 0, Length(aKey)) as tCipherMAC; try (lCipher as iCompoundMode).N := BytesToOS(aNonce); (lCipher as iCompoundMode).MACLength := cTagLen; (lCipher as iCompoundMode).Initialize; if Length(aAssociated) > 0 then lCipher.EncryptToNil(aAssociated[0], Length(aAssociated)); SetLength(Result, cNonceLen + Length(aPlain) + cTagLen); Move(aNonce[0], Result[0], cNonceLen); lLen := Length(aPlain); if lLen > 0 then begin Move(aPlain[0], Result[cNonceLen], lLen); lCipher.Encrypt(Result[cNonceLen], lLen); // in place end; lCipher.GetFinalBuf(Result[cNonceLen + Length(aPlain)], cTagLen); finally lCipher.Free; end; end; function Seal(const aKey, aPlain, aAssociated: TBytes): TBytes; var lNonce: TBytes; begin { A fresh random nonce per message. A nonce used twice with one key gives away the XOR of the two plaintexts and lets the tag be forged; 96 random bits are safe for up to 2^32 messages per key (NIST SP 800-38D 8.3). } SetLength(lNonce, cNonceLen); GetRawRandom(True).RawRandom(lNonce); Result := SealWithNonce(aKey, lNonce, aPlain, aAssociated); end;
The cipher is driven through two interfaces: iCompoundMode takes the nonce and the tag length and starts a message (Initialize), and the tCipherMAC methods do the rest - EncryptToNil authenticates the associated data without producing output, Encrypt encrypts, and GetFinalBuf writes the tag. The same sequence drives ChaCha20-Poly1305: MustFindCipherClass(caChaCha20, cmCTR), with stChaCha20Poly1305 in the uses clause and a 32-octet key.
function Open(const aKey, aSealed, aAssociated: TBytes; out aPlain: TBytes): Boolean; var lCipher: tCipherMAC; lLen: Integer; begin aPlain := nil; Result := False; if Length(aSealed) < cNonceLen + cTagLen then Exit; lCipher := MustFindCipherClass(caRijndael, cmGCM).CreateBytes(aKey, 0, Length(aKey)) as tCipherMAC; try (lCipher as iCompoundMode).N := BytesToOS(Copy(aSealed, 0, cNonceLen)); (lCipher as iCompoundMode).MACLength := cTagLen; (lCipher as iCompoundMode).Initialize; if Length(aAssociated) > 0 then lCipher.EncryptToNil(aAssociated[0], Length(aAssociated)); lLen := Length(aSealed) - cNonceLen - cTagLen; SetLength(aPlain, lLen); if lLen > 0 then begin Move(aSealed[cNonceLen], aPlain[0], lLen); lCipher.Decrypt(aPlain[0], lLen); end; { The tag decides. A message that fails it is not a message: wipe what was decrypted and give nothing back. } Result := lCipher.VerifyFinalBuf(aSealed[cNonceLen + lLen], cTagLen); if not Result then begin ProtectClear(aPlain); aPlain := nil; end; finally lCipher.Free; end; end;
VerifyFinalBuf returned True. GCMThe key is 16, 24 or 32 random octets (AES-128, -192, -256); see Generate random bytes and keys. To derive a key from a password, use a password-based KDF - see Store a password safely for Argon2id.
For messages to other parties - with certificates, several recipients, or S/MIME - use CMS enveloped data instead, which carries the algorithm, the key wrapping and the nonce in a standard format.
stSecUtils · stAESNI · stAESCT