2

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."\n";
}

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!

Community
  • 1
  • 1
emma
  • 761
  • 5
  • 20

1 Answers1

1

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.

AES-GCM is an authenticated cipher. If you're trying to learn how the basic building block works, you want to play with aes-128-ecb instead.

If you want a real-world encryption mode, you want to keep using GCM, never ECB.

And is it safe to store $cipher, $iv, $key and $tag into a MySQL database for later use?

You can store everything except the key, safely. The key lets you decrypt.

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206