Skip to content

Instantly share code, notes, and snippets.

@SomajitDey
Last active September 26, 2021 16:01
Show Gist options
  • Save SomajitDey/edbe0e3b6ddde484f814c8df016bb7af to your computer and use it in GitHub Desktop.
Save SomajitDey/edbe0e3b6ddde484f814c8df016bb7af to your computer and use it in GitHub Desktop.
Generate strong password of any given width from any given text or master password
#!/usr/bin/env bash
# Creates strong password of any given width from any given text or master password
# Usage: echo <a line of text> | [SALT=<salt>] ./passgen [-p] [<width>]
# Option: -p generates PIN instead of password
# Default: width=8; SALT=somesalt
# Author: Somajit Dey <dey.somajit@gmail.com>
# License: GNU GPLv2
set -o noglob
hash_salt(){
salt="$(echo "${salt}" | sha512sum | awk '{print $1}')"
}; export -f hash_salt
test_format(){
[[ "${string}" =~ [a-z]+ ]] && [[ "${string}" =~ [A-Z]+ ]] && \
[[ "${string}" =~ [0-9]+ ]] && [[ "${string}" =~ [^a-z^A-Z^0-9]+ ]]
}; export -f test_format
getopts p option
case "${option}" in
p)
export pin_mode="true"
list=({0..9})
;;
*)
export pin_mode="false"
list=({A..Z} {a..z} {0..9})
special_chars=\
('!' '@' '#' '$' '%' '^' '&' '*' '(' ')' '_' '-' '+' '=' '{' '}' '[' ']' '|' '\' ';' ':' "'" '"' ',' '.' '/' '?' '~' '`')
list+=(${special_chars[@]})
;;
esac
base=${#list[@]}
width="${!OPTIND:-8}"
if ! "${pin_mode}"; then ((width<4)) && echo "Desired password width must be >=4" >&2 && exit 1;fi
read -re mpasswd # Master-password
salt="${SALT:-somesalt}_${width}"
until test_format; do
string=
hash_salt
hex=$(python3 -c "import hashlib; print(hashlib.pbkdf2_hmac('sha512', b'${mpasswd}', b'${salt}', 100000, ${width}).hex())")
for i in $(echo "${hex}" | fold -w 2);do
index=$((16#$i % $base))
string="${string}${list[$index]}"
done
salt="${salt}_${string}"
"${pin_mode}" && break
done
echo "${string}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment