So I am encrypting data, storing it in the database, and decrypting it, using mcrypt.
I am wondering if it’s safe to store the key for encryption in a php file outside of the public_html directory?
The reason for storing it in a file is that it needs to be used for multiple encryptions, so that multiple users can decrypt some data, and I figured storing it in a file is more secure than in the database table, right next to the encrypted data.
What are ANY potential security risks? Is it at ALL possible for a hacker to gain access to this file and thus the key?
If your server (as in its OS) is compromised, it is “game over”, no matter whether your key is stored in a file or the database. So yes, it is “at all possible for a hacker to gain access to this file and thus the key” – by breaking into your server’s OS.
If apache or PHP are compromised, but not the OS, you end up in a chicken-and-egg problem: If you put your key somwhere, where apache/PHP can access it, it can be taken by whoever breaks into apache/PHP. If not, you can’t use it in your webapp.
This leaves only a scenario, where your webapp is compromised, but not the surrounding infrastructure – in this case, a file might indeed be a good idea: Many break-ins (e.g. most of the SQL injection variant) gain access to the DB, but not to the file system.
For sensitive environments we sometimes chose a model, where encryption/decryption is handled via a pair of FIFOs, with the real crypto being done by an external process – this can do some heuristics and refuse decryption on suspicious patterns.