I saw that a doc bug(#80236) were there mentioned that $tag usage. Here is an examples, Hopes those may help someone.
<?php
function encrypt(string $plaintext, string $key, string $iv = '', string $aad = ''): string
{
$ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, $aad, 16);
if (false === $ciphertext) {
throw new UnexpectedValueException('Encrypting the input $plaintext failed, please checking your $key and $iv whether or nor correct.');
}
return base64_encode($ciphertext . $tag);
}
function decrypt(string $ciphertext, string $key, string $iv = '', string $aad = ''): string
{
$ciphertext = base64_decode($ciphertext);
$authTag = substr($ciphertext, -16);
$tagLength = strlen($authTag);
if ($tagLength > 16 || ($tagLength < 12 && $tagLength !== 8 && $tagLength !== 4)) {
throw new RuntimeException('The inputs `$ciphertext` incomplete, the bytes length must be one of 16, 15, 14, 13, 12, 8 or 4.');
}
$plaintext = openssl_decrypt(substr($ciphertext, 0, -16), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $authTag, $aad);
if (false === $plaintext) {
throw new UnexpectedValueException('Decrypting the input $ciphertext failed, please checking your $key and $iv whether or nor correct.');
}
return $plaintext;
}
$aesKey = random_bytes(32);
$aesIv = random_bytes(16);
$ciphertext = encrypt('thing', $aesKey, $aesIv);
$plaintext = decrypt($ciphertext, $aesKey, $aesIv);
var_dump($ciphertext);
var_dump($plaintext);