For all those who enjoy working in the console and want to learn an approach for encrypting passwords, today I will quickly show a concept on how to securely and encryptedly store passwords within your HOME directory using PHP.

The concept is easily expandable and well-suited for teaching purposes.

Source code

The current source code can be found as Gist on GitHub.

Encryption

I use AES-256-CBC for data encryption and PHP crypto functions for OpenSSL. The encryption key must be stored in the TGF_PWDMGR_ENCRYPTION_KEY environment variable.

Before encryption, the data itself is converted to a JSON object string makeing it more flexible with additional data.

I also encrypt file names with HMAC 256 using a secret salt provided by TGF_PWDMGR_HASH_SECRET environment variable.

As mentioned in this Stack Overflow answer, the IV for the AES operations can be public and is also stored in the final file data together with the encrypted data.

Run the script

These are the currently 3 supported commands:

# save password with name
# "my secret thing"
php -f pwdmgr.php set "my secret thing" "my_username" "the_password"

# show password with name
# "my secret thing"
php -f pwdmgr.php get "my secret thing"

# deletes password with name
# "my secret thing"
php -f pwdmgr.php delete "my secret thing"

All encrypted files can later be found in a .tgf_passwords subfolder inside the current home directory.

To make the execution much easier, and if you are working in UNIX like enviroments as Linux or MacOS, you should create aliases for each command, e.g.:

alias pw-set='php -f /full/path/to/pwdmgr.php set'
alias pw-get='php -f /full/path/to/pwdmgr.php get'
alias pw-del='php -f /full/path/to/pwdmgr.php delete'

Conclusion

The script can certainly be improved in one way or another, for example in the areas of providing the secrets or the storages for the data.

As mentioned, it is a concept that can be built upon and is intended to demonstrate how data can be securely encrypted in PHP.

Have fun trying it out! 🎉