Skip to content

Instantly share code, notes, and snippets.

@ansemjo
Created January 17, 2019 19:23
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 ansemjo/0dd88ca03b590c4474163574b5e3dcdf to your computer and use it in GitHub Desktop.
Save ansemjo/0dd88ca03b590c4474163574b5e3dcdf to your computer and use it in GitHub Desktop.
check passwords for matches in haveibeenpwned database
#!/usr/bin/env bash
# script by reddit.com/u/zfa, with modifications to allow piping on stdin and change output format
# https://old.reddit.com/r/netsec/comments/agrrig/troy_hunt_the_773_million_record_collection_1/ee9jenv/
haveibeenpwned() {
printf '\033[1m%-40s\t%9s\t%s\033[0m\n' 'sha1 hash' '# hits' 'password'
while read -r password; do
# calculate hash with uppercase hex
pwhash=$(printf '%s' "${password}" | openssl sha1 | awk '{print $2}');
prefix="${pwhash:0:5}"; suffix="${pwhash:5}";
# check haveibeenpwned api
response=$(curl -s "https://api.pwnedpasswords.com/range/${prefix^^}");
if [[ $? -ne 0 ]] || [[ -z $response ]]; then
printf '%-40s\terror\tfailed to receive response\n' "${prefix}" >&2;
continue
fi
# iterate over lines in response
while read -r line; do
# only first 35 chars of line is hash suffix
if [ "${line:0:35}" == "${suffix^^}" ]; then
printf '%-40s\t% 9d\t%s\n' $(echo "${prefix}${line,,}" | tr -d '\r' | cut -d: -f1,2 --output-delimiter=" ") "${password}"
continue
fi
done <<< "${response}"
done
}
@ansemjo
Copy link
Author

ansemjo commented Jan 17, 2019

example run:

$ source ./haveibeenpwned.sh
$ printf "%s\n" what password 0000 thisisprobablynotinthedb | haveibeenpwned 
sha1 hash                               	   # hits	password
a110e6b9a361653a042e3f5dfbac4c6105693789	    25547	what
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8	  3645804	password
39dfa55283318d31afe5a3ff4a0e3253e2045e43	   149575	0000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment