Skip to content

Instantly share code, notes, and snippets.

@dhensby
Created July 10, 2018 14:55
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 dhensby/536d0a0d5c0606aa3909b5c89e907ae6 to your computer and use it in GitHub Desktop.
Save dhensby/536d0a0d5c0606aa3909b5c89e907ae6 to your computer and use it in GitHub Desktop.
Pwned Passwords API - PHP CLI script to test your passwords locally
#!/usr/bin/env php
<?php
/**
* Usage: pwned.php '<password>'
*/
// get the first argument as the password
$password = $argv[1];
// no password, give them some usage instructions
if (!$password) {
echo "Usage: {$argv[0]} '<password>'\n";
exit;
}
// turn the password into sha1 hash (uppercased)
$sha = strtoupper(sha1($password));
// split at 5th char
$shaStart = substr($sha, 0, 5);
$shaEnd = substr($sha, 5);
// make curl request to password api
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://api.pwnedpasswords.com/range/' . $shaStart,
CURLOPT_USERAGENT => 'ss/cli-password 1.0',
CURLOPT_HTTPHEADER => array(
'Accept: text/plain',
),
));
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
// put response into memory so we can loop over each line
$fp = fopen('php://memory', 'r+');
fputs($fp, $response);
rewind($fp);
// search for the hash
$hit = false;
while ($line = fgets($fp)) {
list($candidateEnd, $count) = explode(':', trim($line), 2);
if ($candidateEnd === $shaEnd) {
$hit = true;
break;
}
}
// if we hit, let them know
if ($hit) {
echo "HIT: $count hit";
if ($count !== 1) {
echo "s";
}
} else {
echo "MISS";
}
echo "\n";
// error exit if we hit
exit ($hit ? 1 : 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment