I'm trying to understand how to AES encrypt a piece of text(16 bytes - 128 bits). This code is from php manual:
$key = openssl_random_pseudo_bytes(32);
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
//store $cipher, $iv, and $tag for decryption later
$original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
echo $original_plaintext."
";
}
The only problem with this is that i don't really understand it. $cipher
is aes-128-gcm
but i'm getting a 32 bytes encryption.
So my questions are: Can somebody help me understand how it actually works?
Is it possible to make it 16 bytes/128 bites?
And is it safe to store $cipher
, $iv
, $key
and $tag
into a MySQL database for later use?
P.S: if i change $key
length to 16
instead of 32
the final output of $ciphertext
is still 32 bytes.
Thank you!