Skip to content

Instantly share code, notes, and snippets.

@marceloalcocer
Last active July 31, 2023 20:18
Show Gist options
  • Save marceloalcocer/7a7aeebf7671ed2351dcb6e6aacef06d to your computer and use it in GitHub Desktop.
Save marceloalcocer/7a7aeebf7671ed2351dcb6e6aacef06d to your computer and use it in GitHub Desktop.
PwnedPasswords client implemented in bash
#!/usr/bin/env bash
#
# PwnedPasswords client implemented in bash
#
# Return the number of times a password has been seen in data breaches by
# querying the [PwnedPasword][hibp] service. Particularly useful for those
# who want to use the service, but are squeamish about typing their
# passwords into a web form…
#
# [hibp]: https://haveibeenpwned.com/Passwords
#
# Usage:
#
# pwnedpasswords [FILE]
#
# Description
#
# The password to be submitted is read from FILE or from stdin if FILE is
# omitted. It is SHA1 hashed (locally), and the first 5 characters of the
# hash are submitted to PwnedPassword. The remaining hash suffix is then
# compared (locally) with the returned hash suffices.
#
# On a match, the hash count — the number of times the passwords has been
# seen in data breaches — is printed to stdout and the exit status is set to
# 1.
#
# On no match, nothing is printed to stdout and exit status is set to 0.
#
# N.b. Be careful to avoid additional EOL characters in FILE or stdin
#
# Examples:
#
# pwnedpasswords my_password_file # Read password from file
#
# echo -n 'my_password' | pwnedpasswords # Read password from stdin
#
# References:
#
# * https://haveibeenpwned.com/Passwords
# * https://haveibeenpwned.com/API/v3?ref=troyhunt.com#PwnedPasswords
# * https://www.troyhunt.com/ive-just-launched-pwned-passwords-version-2/#cloudflareprivacyandkanonymity
#
set -o pipefail
HASH=$(sha1sum $1 | cut -d ' ' -f 1)
! curl \
--silent \
https://api.pwnedpasswords.com/range/$(echo $HASH | cut -c -5) \
| grep -i $(echo $HASH | cut -c 6-) \
| cut -d ':' -f 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment