I'm currently taking over a service and while looking through the DB, I noticed that we encrypt some of our data using a function in the DB where the encryption key is hardcoded in the DB function.

As far as I know, this is not a good practice and makes the encryption pretty much redundant because the whole point of encrypting DB data is to protect the data should the DB leak to unauthorised parties. But in this case, if the DB is compromised, so is the encryption key and the encryption becomes meaningless.

Am I correct here or am I missing something?

Also, if it's a wrong practice, should I change the encryption/decryption process so that it happens on the server app level?

1 Answer 1


The rule of thumb is that you want to keep the encrypted data and the encryption key "as far apart" as possible, meaning that you want to minimize the probability that, given that the data is leaked, the key is also leaked.

This great answer has a ranking from one (best) to seven (worst) on where to store the encryption key. And, you guessed it, number seven is "in the database":

7. Store the key in the database. Now you're not even trying. Still, a depressingly popular option.

So you might want to consider the other alternatives listed there. That said, storing it hard coded in a function is better than just storing it in a table if the following conditions are true:

  1. The database server is not directly accessible from the internet.
  2. The web user of the database (i.e. the user that the app logs in as) does not have permission to read the source code of the functions (so the web user could not read the encryption key).
  3. Back ups of the database does not include the source code of the function.

Moving the encryption to the app layer does not necesarrily make things much better if the encryption key is just hard coded into the app source code instead of the DB source code.

You must log in to answer this question.

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