Skip to content

Instantly share code, notes, and snippets.

@melmatsuoka
Last active August 29, 2015 14:18
Show Gist options
  • Save melmatsuoka/26959f59f247d51a7ab9 to your computer and use it in GitHub Desktop.
Save melmatsuoka/26959f59f247d51a7ab9 to your computer and use it in GitHub Desktop.
Generates a Diceware passphrase, and copies it to the OSX system clipboard, ready for pasting into a password manager. Usage: diceware <wordcount (default: 8)> <delimiter (default:space)>
#!/bin/bash
#
# diceware(): Generate a Diceware passphrase
#
# note: This script has OSX-specific dependencies (pbcopy, pbpaste)
function diceware() {
# arg1: wordcount (default = 8)
# arg2: delimiter (default = space)
CLIPBOARD_TIMEOUT="60" # number of seconds after which clipboard is cleared
NUMARGS=$#
if [ $NUMARGS -eq 0 ]
then
ARG_WORDCOUNT="8"
ARG_DELIMITER=" "
elif [ $NUMARGS -eq 1 ]
then
ARG_WORDCOUNT="$1"
ARG_DELIMITER=" "
else
ARG_WORDCOUNT="$1"
ARG_DELIMITER="$2"
fi
# Create randomized tmpfile for downloaded wordfile
DW_WORDLIST=$(mktemp $TMPDIR/wordlistXXXXXXXXXX)
# Download the official Diceware wordlist, strip out the PGP signature blocks, then save it to the tempfile
curl -s http://world.std.com/~reinhold/diceware.wordlist.asc | \
awk '/-----BEGIN PGP SIGNED MESSAGE-----/ {flag=1;next} /-----BEGIN PGP SIGNATURE-----/{flag=0} flag {print}' > "$DW_WORDLIST";
# randomly shuffle the wordlist, remove the diceroll column, concatenate the words into a passphrase, then copy to clipboard
# note: the stupid rev/cut pipe sequence is an embarrassing hack to remove the last space from the final passphrase.
echo -e ""
gshuf --random-source=/dev/random -rn $ARG_WORDCOUNT < "$DW_WORDLIST" | cut -f 2 | tr '\n' "${ARG_DELIMITER}" | rev | cut -c2- | rev | tee >(pbcopy)
# store clipboard passwd contents, for later comparison
CLIPBOARD_PASSWD=$(pbpaste)
# clipboard-clearing countdown display
echo -e ""
# Escape sequence in echo command represents an end of line which cleans the rest of line if there are any characters left
# from previous output and \r is a carriage return which moves the cursor to the beginning of the line.
while [ $CLIPBOARD_TIMEOUT -gt 0 ]; do
echo -ne "Clipboard will be cleared in $CLIPBOARD_TIMEOUT seconds\033[0K\r"
sleep 1
: $((CLIPBOARD_TIMEOUT--))
done
# Check to see if the current clipboard still contains the generated passphrase, so we dont clobber the clipboard if the user has copied
# something else to the clipboard in the meantime
CLIPBOARD_CONTENTS=$(pbpaste)
if [ "$CLIPBOARD_CONTENTS" == "$CLIPBOARD_PASSWD" ]
then
# Clear the clipboard, as well as the console display.
clear
pbcopy < /dev/null
echo -e "\033[0K\rClipboard cleared."
else
echo -e "\033[0K\rClipboard already cleared."
fi
CLIPBOARD_PASSWD=""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment