I'm looking for a way to encrypt data in MySQL database securely. The data come from a web interface from a POST form and each POST request from the user insert a new line in the database.

Right now, I am trying to achieve this from my PHP code with the functions openssl_encrypt and openssl_decrypt but I'm not sure if I'm doing it the right way and I can't find the answer.

I'm thinking of using a single key (symmetric encryption) that is stored on the web server and only accessible by the web server user (www-data). Is it enough secure or should I use different keys or even store the key elsewhere ?

For the IV, is it OK to use the same IV for every insertion or should I change it and store it in each row of the database?

  • Usually you don't encrypt data in the app before storing in a database as this significantly impairs the useful things the database can do, like indexing. Typically you trust the database, and have it configured to use disk encryption.
    – paj28
    Oct 3, 2022 at 8:36

1 Answer 1


A single key can be fine. But there's a school of thought that one should periodically rotate keys after encrypting lots of data with one. Random keys for data and a wrapping key which only encrypts keys makes the rotation a bit less frequent, if you believe in the need for rotation.

As for where to store the key, that answer depends on risk. Storing the key outside of a KMS or HSM for, say, Medical data would be a massive no-no. For low sensitivity data, maybe it's fine. But the typical answer is to just use some ready made Key Management service.

Whether or not you use a single key or a different key for every entry, the IV shall ALWAYS be totally random and stored with the ciphertext. IV reuse is a concern in every mode of every cipher.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .