Security of storing an encryption key in PHP file Security of storing an encryption key in PHP file codeigniter codeigniter

Security of storing an encryption key in PHP file


Storing it above the public_html is a good idea. Your file should have the correct permissions configured so that only the web server or users that require it can read it.

An option is to split the key up and store in different places, for example part of it in a file on the file system, and part in the database. The benefit of this is it's harder to get the full key for an attacker because they need to access both the file system and the database.

Also consider your server environment has an affect on security, for example shared hosting is less secure than a dedicated server.

No one can say that it's impossible for an attacker to access the key because that depends on your entire server setup and config. Server's are most often compromised through vulnerabilities in software such as web servers, so you should follow good security practices such as keeping your software up to date.


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.