I was wondering which is the best way to secure data at rest (encrypt / decrypt) in a php application ( eq: stored in a database ) using AES ?

Where is the best way to store the keys ?

  • 4
    What are you protecting? What attacks are you protecting it from? – Neil Smithline May 20 '15 at 21:39

It all depends on the kind of information you want to protect and the database type you are running.

If you are asking this for a company handling people's credit cards, health records or similarly confidential information, I would like to recommend not doing your own implementation. Lots of things can go wrong and it would be really hard to get to compliance level. Also some other practical factors play a role (performance, key management, auditing, etc.). Hard to get it right on your own. There are some affordable commercial products that address this very situation. Some provide column-level encryption for Open Source DBs and the company is targeting SMEs, meaning a a relatively affordable pricing.


As you hint at in your question the problem is all about managing the secrets (access tokens and keys).

Using complex and/or remote encryption solutions is going to have a huge impact on your performance and scalability. You want your keys to be immediately available to your code, but limit the exposure elsewhere (other processes, backups). Shared memory, the APC cache (but not the more recent opcache) are obvious candidates. Using PHP-FPM (running as a different uid) rather than mod_php gives better isolation if you don't have a separate web cache in front of your webserver.

How you encrypt your data is highly dependent on the structure of the data and how it will be accessed. See other questions here on managing database passwords and encrypting data inside the database.


It is depended to network structure and topology of your system, in some cases like distributed system you can use secret sharing scheme, such as shamir,rabin IDA or Krawcyk. Also you can use PKI for that.

Usually in practice only hash of passwords are stored. But for key, shamir secret sharing scheme is powerful for storing key in secure way. That only an acceptable number of participants can recover the key as threshold. Also in some cases shamir or rabin IDA is used between some databases in one server that each one has been secured separately, however it is not recommend.

Also krawcyk method (secret sharing made short) provides a hybrid of shamir for key protection and rabin IDA for data protection and uses AES for encryption.

Read more about secret sharing scheme here.

Also you can use HSM for storing keys in secure manner.

Not the answer you're looking for? Browse other questions tagged or ask your own question.