Best reasonable way to store a secret safely

I'm assuming that your threat model is an attacker gaining access to read files on your webserver via some type of web exploit. If not, you should question what exactly you are mitigating with your proposed encryption strategy.

If it is, an option similar to 2 is probably the most simple.

I would use AES128-CBC as the algorithm for a Key Encrypting Key. With a CSPRNG generated 128 bit encryption key, there is no need to use a key stretching algorithm. Algorithms such as PBKDF2 are only needed when you are attempting to secure weak, user supplied passwords. If you can set the keys yourself, you can simply make sure that they are the required bit strength.

AES256 is slower, and with no additional security over AES128.

Make sure your configuration file and your key file is locked down by access control lists.

Key file:

<128 bit random key>

Can only be read by a custom service account.

Config file:

Passwords to systems, encrypted by the key in the Key file.

Can only be read by the web server identity.


Make sure these files aren't servable by your web server (e.g. example.com/config.txt won't work). The way this should work is that you have a service account that runs a process. The web service calls this process and asks the service to decrypt a configuration file password for it. The service validates that only the web server process can call it.

This will protect your secrets from any LFI exploits in your system or server because an attacker in the context of the web server user won't have permission to read the key file or decrypt any credentials in your config file.

It won't protect against physical access, logical access to the system by another administrator level account, or any vulnerabilities that allow a process to be called. It would basically only protect against file reads of the config file directly by the web identity (the user the website itself runs as). If this is not a concern, then there is no need to encrypt secrets at all - the only thing it would really be protecting was casual observation by parties that may see the configuration file.