Skip to content

Instantly share code, notes, and snippets.

@steverichey
Created November 21, 2018 03:52
Show Gist options
  • Save steverichey/2a99bd0a949e89a2d0b5e1eefe825691 to your computer and use it in GitHub Desktop.
Save steverichey/2a99bd0a949e89a2d0b5e1eefe825691 to your computer and use it in GitHub Desktop.
Password generation script
#!/bin/sh
set -e
# generate allowed_characters number_of_characters
generate()
{
cat /dev/random | env LC_CTYPE=C tr -cd $1 | head -c $2
}
usage()
{
echo "Usage: pw 16 [lim|num|alpha|dice|ware]"
exit 1
}
get_line()
{
awk '/'$1'/{ print NR; exit }' $DICE_WARE_LIST
}
get_word()
{
awk 'NR=='$1'' $DICE_WARE_LIST
}
copied()
{
echo "Password copied to clipboard"
}
if [[ "$#" -lt 1 ]]
then
usage
fi
if [[ "$#" -gt 2 ]]
then
usage
fi
if expr "$1" : '-\?[0-9]\+$' >/dev/null; then
echo "Unknown error in argument"
usage
fi
if [ $1 -gt 65535 ]; then
echo "Requested string is too large"
usage
fi
if [ "$#" -gt 1 ]
then
if [ "$2" != "lim" ] && [ "$2" != "num" ] && [ "$2" != "alpha" ] && [ "$2" != "dice" ] && [ "$2" != "ware" ]
then
echo "Unrecognized second parameter"
usage
fi
fi
if [ "$#" -gt 1 ]
then
if [ "$2" = "lim" ]
then
generate 'a-z0-9' $1 | pbcopy
copied
elif [ "$2" = "num" ]
then
generate '0-9' $1 | xargs echo
elif [ "$2" = "alpha" ]
then
generate 'a-z' $1 | xargs echo
elif [ "$2" = "dice" ]
then
generate '1-6' $1 | xargs echo
elif [ "$2" = "ware" ]
then
# todo: download https://www.eff.org/files/2016/07/18/eff_large_wordlist.txt somehow
if [ -z "$DICE_WARE_LIST" ]
then
echo "Please set DICE_WARE_LIST to the location of your diceware text file."
exit 1
fi
RESULT=""
for i in `seq 1 $1`
do
NUM=`generate '1-6' 5`
LINE=`get_line $NUM`
WORD=`get_word $LINE`
SPLIT=(${WORD// / })
RESULT="$RESULT ${SPLIT[1]}"
done
echo $RESULT
fi
else
generate 'a-zA-Z0-9`~!@#$%^&*()_+-={}[]|;<,>.?/' $1 | pbcopy
copied
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment