A simple bash gpg “password safe”

This is definitely not military quality – but if you need a simple way to manage a GPG-encrypted file containing info you want to protect this works pretty well for me. I use this to manage a set of passwords on a trusted machine that I can ssh to.

It assumes you’re using a bash-like shell and have a trusted private key available in the account you’re running it on.



if [ ! -e "$HOME/private" ]
    mkdir -m 700 "$HOME/private"
    umask 77 "$HOME/private/"

# Always delete the unencrypted file at the end of the session. We DO NOT want this hanging around.
trap "rm -f \"$HOME/private/${USER}_private_store.txt\"; chmod 600 \"$HOME/private/${USER}_private_store.txt\"*; exit" INT TERM EXIT

touch "$HOME/private/${USER}_private_store.txt"
chmod 600 "$HOME/private/${USER}_private_store.txt"

gpg --decrypt "$HOME/private/${USER}_private_store.txt.asc" > "$HOME/private/${USER}_private_store.txt"
vim "$HOME/private/${USER}_private_store.txt"

md5sum  "$HOME/private/${USER}_private_store.txt.md5sum.new"

if [ -e "$HOME/private/${USER}_private_store.txt.md5sum" ]
    if [ "`cmp "$HOME/private/${USER}_private_store.txt.md5sum.new" "$HOME/private/${USER}_private_store.txt.md5sum"`" == "" ]
        rm -f "$HOME/private/${USER}_private_store.txt.md5sum.new"
        echo 'No changes, not re-encrypting'

mv "$HOME/private/${USER}_private_store.txt.md5sum.new" "$HOME/private/${USER}_private_store.txt.md5sum"

echo 'File has changed. Re-encrypting. . .'
gpg -a --encrypt -r $KEYS "$HOME/private/${USER}_private_store.txt"

First time it runs it’ll create a private directory, start vim, and encrypt the text you enter into vim. On subsequent runs it’ll prompt you for your private key passphrase and repeat the cycle. It won’t re-encrypt if there haven’t been any changes.

I’m betting wordpress messes up the code, so here’s the text file: edit_password_safe.sh.

One thought on “A simple bash gpg “password safe”

  1. Hey Dan,

    Shoot, that’s some good stuff right there. Thanks for the tip!


Leave a Reply

Your email address will not be published. Required fields are marked *