Skip to content

Instantly share code, notes, and snippets.

@heisian
Last active October 9, 2018 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heisian/12f62d8e3732c702ccf7263bead90825 to your computer and use it in GitHub Desktop.
Save heisian/12f62d8e3732c702ccf7263bead90825 to your computer and use it in GitHub Desktop.
Generate a Safari-style password in bash
#!/bin/bash
# ################################################
#
# Generate a Safari-style password: V4R-cG2-Cru-J5d
#
# Usage:
# $ MY_PASSWORD=$(./safari-style-password.sh)
# $ echo $MY_PASSWORD
#
# ################################################
function getRandomASCIICodeForDigitsAndLetters {
# ASCII Codes
# Digits 0-9, range 048 - 057
# Letters A-Z, range 065 - 090
# Letters a-z, range 097 - 122
# :;<=>?@ special chars, range 058 - 064
# [\]~_` special chars, range 091 - 096
# Range of all above: 048 - 122
local UPPER_LIMIT=122
local LOWER_LIMIT=48
# Safari does not use any special characters except for "-"
local DISALLOWED_CODES=( 58 59 60 61 62 63 64 91 92 93 94 95 96 )
# NOTE: Double-parenthesis allow for arithmetic evaluation.
local DIFF=$(($UPPER_LIMIT - $LOWER_LIMIT + 1))
local RANDOM_DIGIT=$(( $(($RANDOM%$DIFF)) + $LOWER_LIMIT))
if [[ " ${DISALLOWED_CODES[@]} " =~ " ${RANDOM_DIGIT} " ]]; then
# Re-roll
local RANDOM_DIGIT=$(getRandomASCIICodeForDigitsAndLetters)
fi
echo $RANDOM_DIGIT
}
function transformASCIICodeToCharacter () {
printf '%b' $(printf '\\x%x' $1)
}
function generateRandomPassword {
RANDOM=$(echo $$) # "Seed" RANDOM w/ PID
local SECURE_PASSWORD="" # Ensure SECURE_PASSWORD starts off as a blank string
# Add hyphens to the password: XXX-XXX-XXX-XXX
local HYPHENATE=( 4 8 12 )
for i in `seq 1 15`;
do
RANDOM_DIGIT=-1
RANDOM_DIGIT=$(getRandomASCIICodeForDigitsAndLetters)
if [[ " ${HYPHENATE[@]} " =~ " ${i} " ]]; then
SECURE_PASSWORD="$SECURE_PASSWORD-"
else
CHAR=$(transformASCIICodeToCharacter "$RANDOM_DIGIT")
SECURE_PASSWORD="$SECURE_PASSWORD$CHAR"
fi
done
echo $SECURE_PASSWORD
}
generateRandomPassword
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment