AES Encrypt/Decrypt with authentication code
This example demonstrates how to use AES-GMAC
Example code encrypt:
procedure TFrmMain.btnEncryptPWClick(Sender: TObject);
var
Key: IRwBCryptGCMKey;
Nonce, AuthTag: TRwBytes;
begin
// Create a AES-256 Key for Encryption in CCM mode
// Note that there is a difference between "AES256(bccmGCM)" and "AES256_GMAC"
// With "AES256(bccmGCM)" it's possible to encrypt with GCM mode, however, it does not return a GMAC,
// nor does it verify a GMAC
// The "AES256_GMAC" does return a GMAC value and will allow you to verify the decrypted value
Key := TRwBCrypt.Cipher.AES256_GMAC.DeriveKey_CSP(edtPassword.Text, True, calgSHA256);
Nonce := [1,2,3,4,5,6,7,8,9,10,11,12]; // The "Number Generated Once" must be 12 bytes
edtEncrypted.Text := Key.EncryptString(edtToEncryptPW.Text, True, Nonce, AuthTag).Encode(beBase64);
// Save the GMAC
edtAuthTag.Text := AuthTag.Encode(beBase64);
end;
Example code decrypt and verify:
var
Key: IRwBCryptGCMKey;
Nonce, AuthTag: TRwBytes;
begin
// Create the key
Key := TRwBCrypt.Cipher.AES256_GMAC.DeriveKey_CSP(edtPassword.Text, True, calgSHA256);
// Use the same nonce for decryptiing
Nonce := [1,2,3,4,5,6,7,8,9,10,11,12];
// Load the GMAC
AuthTag := TRwBytes.Decode(edtAuthTag.Text, beBase64);
// Decrypt and verify
// You will get an exception when the verification failes
edtDecrypted.Text := Key.DecryptString(AuthTag, edtEncrypted.Text, beBase64, True, Nonce);
end;