Skip to content

Instantly share code, notes, and snippets.

@MinusKelvin
Last active May 4, 2018 20:34
Show Gist options
  • Save MinusKelvin/38bd8e50917a25ab21d2aeef30dc4b34 to your computer and use it in GitHub Desktop.
Save MinusKelvin/38bd8e50917a25ab21d2aeef30dc4b34 to your computer and use it in GitHub Desktop.
Password management utility
#!/bin/bash
usage() {
echo "Usage:"
echo " $0 gen <key>"
echo " $0 view [key]"
echo " $0 add <key> <value>"
echo " $0 copy <key>"
echo " $0 remove <key>"
}
add() {
if [[ "$1" = *:* ]]; then
echo "Key cannot contain a colon"
exit
fi
read -s -p "Encryption Password: " PASS
echo
if [ ! -e passwords.gpg ]; then
echo "$1: $2" | gpg2 --batch --yes --passphrase "$PASS" --no-tty -q -c >.tmp.passwords.gpg
else
if ! gpg2 --batch --yes --passphrase "$PASS" --no-tty -q -d <passwords.gpg >/dev/null; then
echo "Invalid passphrase"
exit
fi
{ gpg2 --batch --yes --passphrase "$PASS" --no-tty -q -d <passwords.gpg; echo "$1: $2"; } | gpg2 --batch --yes --passphrase "$PASS" --no-tty -c >.tmp.passwords.gpg
fi
mv -T .tmp.passwords.gpg passwords.gpg
rm -f .tmp.passwords.gpg
}
if [ "$1" = gen ]; then
if [ -z "$2" ]; then
usage
exit
fi
add "$2" `cat /dev/urandom | tr -dc [:alnum:][:punct:] | head -c 32`
elif [ "$1" = view ]; then
if [ ! -e passwords.gpg ]; then
echo "No password file exists"
exit
fi
if [ -z "$2" ]; then
read -s -p "Encryption Password: " PASS
echo
gpg2 --batch --yes --passphrase "$PASS" --no-tty -q -d <passwords.gpg | grep -E -o '^[^:]+'
exit
fi
if [[ "$2" = *:* ]]; then
echo Key cannot contain a colon
exit
fi
read -s -p "Encryption Password: " PASS
echo
gpg2 --batch --yes --passphrase "$PASS" --no-tty -q -d <passwords.gpg | grep -F "$2: "
elif [ "$1" = copy ]; then
if [ ! -e passwords.gpg ]; then
echo "No password file exists"
exit
fi
if [ -z "$2" ]; then
usage
exit
fi
if [[ "$2" = *:* ]]; then
echo Key cannot contain a colon
exit
fi
read -s -p "Encryption Password: " PASS
echo
gpg2 --batch --yes --passphrase "$PASS" --no-tty -q -d <passwords.gpg | grep -F "$2: " | grep -oP ": \K.+$" | xclip -i -selection c
echo "Copied to clipboard. You have 10 seconds before your clipboard is automatically purged."
for i in {9..0..-1}; do
sleep 1
echo $i
done
echo "" | xclip -i -selection c
elif [ "$1" = add ]; then
if [ -z "$2" -o -z "$3" ]; then
usage
exit
fi
add "$2" "$3"
elif [ "$1" = remove ]; then
if [ ! -e passwords.gpg ]; then
echo "No password file exists"
exit
fi
if [ -z "$2" ]; then
usage
exit
fi
if [[ "$2" = *:* ]]; then
echo "Key cannot contain a colon"
exit
fi
read -s -p "Encryption Password: " PASS
echo
pattern=$(printf '%s\n' "$2" | sed 's/[\[\.*^$]/\\&/g')
gpg2 --batch --yes --passphrase "$PASS" --no-tty -q -d <passwords.gpg | grep -v "^$pattern: " | gpg2 --batch --yes --passphrase "$PASS" --no-tty -c >.tmp.passwords.gpg
mv -T .tmp.passwords.gpg passwords.gpg
rm -f .tmp.passwords.gpg
else
usage
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment