What is the best way to store AES encryption keys in a php application?

Viewed 1098

I have a web app that uses AES encryption, everything works well, but I hard code the key in the php file. Here is an example ... encrypt($msg, 'password'); ... It calls my function and sends the password as a second parameter. The glaring flaw is that if someone accesses my server and looks in the php code they can easily take the key and decrypt the database. Should I be calling the password from an alternate server from an alternate database? Anyone have any simple ideas to protect the key? btw. I am stuck using one key for all the encryption because of the nature of the application.

1 Answers

This is the same chicken and egg problem which crops up all over the place in IT.

I expect this will be closed as a duplicate of something else - but its quicker to answer than look for duplicates.

There are different ways to mitigate the risk but none fix the problem. Which solution is right for you depends on what your specific risks are - are your backups encrypted / secure? Do you want the application to recover automatically from reboots? Is your application running on a system which is able to prove its identity/integrity to another machine? Does it run as part of a cluster.....

There are only so many places you can store data:

  • on another machine (access depends on an authentication mechanism)
  • on the filesystem (secret will be visible to anyone with access to that filesystem or a backup of it)
  • in memory (secrets are lot at reboot, and there is limited scope for protecting them from someone with access to the machine).

Don't feel bad. HSMs go to extreme lengths to provide security for secrets where it is practical to do so - but will hand them out to any authorized client (and the authentication schemes are not the most reliable). The model for managing master keys used by most password managers is truly awful.

Another key point is that a lot of the solutions which provide a moderate amount of protection are far from simple. I am current playing with the idea of writing my own password manager where the master encryption key is also encrypted with a key composed of each users password and a secret stored in memory on the computer. But this has issues around how to inject the system key at boot time securely and dealing with password resets.

The Linux kernel now has a virtual HSM capability which allows you to restrict data stored in memory to specific processes, process groups or users - but its not portable across operating systems.

Related