Obfuscating sensitive text in shell scripts

For many years I’ve been using a simple method of obfuscating sensitive information in shell scripts. I can’t take the credit for this, as it was something inherited in my work environment.

This technique uses openssl to encrypt and decrypt a string of text without having to embed the sensitive data in plain text. Note, this isn’t proper private/public key-pair encryption, so treat this as simply obfuscating text.

First step in the process is to generate what can be referred to as a key file. The key file must contain a random string. The easiest way I find to do this is to use ssh-keygen and copy a large chunk of text either from the private key, or the public key, and save it in a file.

For example, key.txt contains the following:


The shell script below is an example of this obfuscation/de-obfuscation in process.

secret="cat /var/root/key.txt"
generated_secret=$(echo ${password} | openssl enc -aes-256-cbc -pass "pass:${secret}" -a -e)
cleartext_secret=$(echo ${generated_secret} | openssl enc -aes-256-cbc -pass "pass:${secret}" -a -d)
echo "Obfuscated password: ${generated_secret}"
echo "De-obfuscated password: ${cleartext_secret}"

When this is run:

[frodo@mordor]: # sudo ./foo
Obfuscated password: U2FsdGVkX18FWNJ0K3nFa0QPyb9YksGxavWE0p4Km7g=
De-obfuscated password: test

To make this a little more obscure, the key.txt file should exist somewhere that normal users cannot access, but still readable by root.
For example, /var/root/key.txt with read-only permission for root. Any script that needs to de-obfuscate sensitive information therefore needs to be run as root, or have a suid set.
Additionally, any script that uses this technique should be kept seperate from the key file, and when used in any shell script, make sure any variable containing the de-obfuscated text is used only where required, and unset/destroyed after use.

I typically only use this in single use scripts – for example, creating a local user account when a machine is imaged/deployed.