Created
February 22, 2018 13:27
-
-
Save mrunkel/c19e1b16d509510d176c539859bb5e8f to your computer and use it in GitHub Desktop.
A simple command line script to check your password against the HIBP database.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!env php | |
| <?php | |
| /** | |
| * Generates a SHA1 hash of the password to be tested. Sends the first 5 | |
| * characters of said hash to HIBP. | |
| * | |
| * HIBP returns the remaining characters of any hashes in their database that | |
| * matched ours. | |
| * | |
| * All we need to do iterate the list and find any matches. | |
| * | |
| * https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange | |
| * | |
| * @param string $password | |
| * | |
| * @return int | |
| */ | |
| function checkPassword(string $password): int | |
| { | |
| // create hash and split it | |
| $sha1 = strtoupper(sha1($password)); | |
| $key = substr($sha1, 0, 5); | |
| $rest = substr($sha1, 5); | |
| // call the API | |
| $result = file_get_contents('https://api.pwnedpasswords.com/range/' . $key); | |
| // split the big string into an array. | |
| $responses = explode("\n", $result); | |
| // search through the array | |
| foreach ($responses as $response) { | |
| // at this point we have an array with each element looking like this: | |
| // (string) "0018A45C4D1DEF81644B54AB7F969B88D65:1" | |
| // split the target hash from the usage count (see API Docs) | |
| $hashData = explode(':', $response); | |
| $hash = $hashData[0]; | |
| $count = $hashData[1]; | |
| if ($hash == $rest) { // if the hash matches the rest of our hash, we're done. | |
| return (int)$count; | |
| } | |
| } | |
| // else we didn't find anything. | |
| return 0; | |
| } | |
| if ($argc !== 2) { // if we didn't receive two inputs, print a small help guide. | |
| echo "Usage: " . $argv[0] . ' passwordToCheck'; | |
| } else { // try to find the password. | |
| $count = checkPassword($argv[1]); | |
| // prettify the response | |
| $plural = $count == 1 ? '' : 's'; | |
| $verb = $count > 0 ? 'has' : 'has NOT'; | |
| $used = $count > 0 ? " It has been used ${count} time{$plural}." : ''; | |
| echo "Your password ${verb} been found online.${used}"; | |
| } | |
| echo PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment