I'm trying to encrypt and store strings in PHP as per example #1 on the PHP openssl_encrypt documentation.
<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$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";
}
?>
If the user is responsible for remembering the $key
, is it safe to store the $iv
alongside the encrypted string in the database?
From this other question AES 256 CBC - Storing local data, how to save IV vector? and others I can see the importance of a unique $iv
but the answer mentions:
If you are using AES-CBC, You can store the IV however you like. It is not important to keep the IV secret; you just need to make sure that an adversary cannot predict the IV in advance.
Does this apply to GCM as well?
EDIT: If I'm not mistaken, this SO question, Trying to decrypt with aes-256-gcm with php is the answer. (which is yes, the IV and Tag can be stored alongside the cipher text)