Simple password management with Bash and GPG

A while ago I was looking for a password management solution that I could trust, so of course being as paranoid as I am I decided to write my own. Now I’ve decided to share what I came up with.

My system takes the form of two bash functions which inhabit my .bashrc file. First is a password generation function:

# function to generate a new password and add it to the secure file
# also copies the new password to the clipboard
# clipboard is cleared automatically after 10 seconds
pwg()
{
    CB=$(xclip -selection clipboard -out)
    gpg --decrypt $HOME/secure.txt.gpg > $HOME/secure.txt
    PW=$(pwgen -n 12 1)
    echo "$PW   $1" >> $HOME/secure.txt
    gpg --encrypt --recipient $MY_EMAIL $HOME/secure.txt
    rm $HOME/secure.txt

    echo $PW | xclip -selection clipboard
    echo
    echo "New password copied to clipboard!"
    echo "You have 10 seconds..."
    sleep 10
    echo $CB | xclip -selection clipboard
}

This generates a 12 character alphanumeric password using pwgen and appends it to my password file along with a user supplied token (which is later used to retrieve the password. The password file is a tab separated file stored in the the home directory and encrypted with GPG. The password is copied to the clipboard with the xclip tool, where it stays for ten seconds before being wiped.

The second part of the system is a function to retrieve the password:

# function to retrieve a password from the secure file and copy it to the clipboard
# clipboard is cleared automatically after 10 seconds
pw()
{
    CB=$(xclip -selection clipboard -out)
    gpg --decrypt $HOME/secure.txt.gpg | grep $1 | cut -f1 | xclip -selection clipboard
    echo
    echo "Password copied to clipboard!"
    echo "You have 10 seconds..."
    sleep 10
    echo $CB | xclip -selection clipboard
}

This function grabs the password from the secure file and again copies it to the clipboard ready to be pasted to wherever it is needed. Again the clipboard is cleared after ten seconds to prevent passwords hanging around to long.

To use these function just place them in your .bashrc file along with a definition of the MY_EMAIL variable (to allow GPG to find your key) and then source the file (or restart bash). Obviously you’ll need GPG, pwgen and xclip which on Fedora can be installed with:

$ sudo yum install gnupg pwgen xclip

Usage is very simple, just run each function in a terminal with an identification token as the argument:

$ pwg test

<GPG PROMPTS FOR PASSPHRASE>

File `secure.txt.gpg` exists. Overwrite? (y/N) y

New password copied to clipboard!
You have 10 seconds...
[robert@riker ~]$ pw test

<GPG PROMPTS FOR PASSPHRASE>

Password copied to clipboard!
You have 10 seconds...

That’s it! Feel free to give it a try. Improvments are most welcome, so please post them in the comments section.