0
$\begingroup$

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)

New contributor
waffl is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
$\endgroup$
1
3
$\begingroup$

Does this apply to GCM as well?

It is even more important for GCM than for CBC to never reuse an IV with the same encryption key. It would completely break the encryption.

The IV is not secret. You can do whatever you want with it, including storing it in a database.

$\endgroup$
2
  • $\begingroup$ Sorry I should have phrased the question more clearly - but you did reiterate it, that the IV is not a secret and can indeed be stored in the DB. Thank you. $\endgroup$ – waffl Jun 10 at 15:45
  • 2
    $\begingroup$ @waffl Kerckhoffs's principle: A cryptosystem should be secure even if everything about the system, except the key, is public knowledge. $\endgroup$ – Swashbuckler Jun 10 at 15:54

Your Answer

waffl is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.