I have a requirement to store certain data in an encrypted form in Postgres. Obviously, I need to encrypt it, store it, and be able to read and decrypt it. What is the best way to do this?
-
8Your question is too broad. You can either encrypt/decrypt outside of postgres, or use the pgcrypto module to do the encryption in-server. In both cases you might want to use bytea columns or large objects for storage.lanzz– lanzz2011-11-08 17:36:14 +00:00Commented Nov 8, 2011 at 17:36
-
I think the pgcrypto module is probably what I want.Joe– Joe2011-11-08 17:40:25 +00:00Commented Nov 8, 2011 at 17:40
-
1Too broad a question.Honza Zidek– Honza Zidek2014-07-16 11:13:12 +00:00Commented Jul 16, 2014 at 11:13
1 Answer
The best way is to do the crypto on the client or application server, so the database has no idea what the keys are and cannot decrypt the data. If the client / appserver are on a different host, all the better.
If your database is encrypting and decrypting the data for you, then it's vulnerable to having the keys stolen along with the database.
If you use pgcrypto's in-database crypto functions you can have the application send the key along with the data, which is at least somewhat helpful. It still risks having the keys exposed in the logs if a helpful sysadmin turns on aggressive statement logging or automatic plan dumping, though, and in the end if the keys are going to the database machine they're more vulnerable than if they're not. An attacker who takes control of the database machine can also change log settings, replace the postgresql binaries, or sniff traffic to capture keys and data this way.
If the appserver and db are on the same machine and managed by the same role(s) there's less point worrying about isolating them, and it may be sensible to just use pgcrypto.
Either way, remember to salt!