Score:0

AES-GCM can IV be stored alongside in DB?

za flag

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)

kelalaka avatar
in flag
A related question [Line by line encrypted logging stored with iv/salt/iterations. How safe is it?](https://crypto.stackexchange.com/q/78350/18298)
Score:4
cr flag

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.

za flag
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.
Swashbuckler avatar
mc flag
@waffl Kerckhoffs's principle: A cryptosystem should be secure even if everything about the system, *except the key*, is public knowledge.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.