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.


#!/bin/bash

KEYS=""

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

# 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" ]
then
    if [ "`cmp "$HOME/private/${USER}_private_store.txt.md5sum.new" "$HOME/private/${USER}_private_store.txt.md5sum"`" == "" ]
    then
        clear
        rm -f "$HOME/private/${USER}_private_store.txt.md5sum.new"
        echo 'No changes, not re-encrypting'
        exit
    fi
fi

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"
clear

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.