Skip to content

Instantly share code, notes, and snippets.

@JimWestergren
Last active December 22, 2023 23:06
Show Gist options
  • Save JimWestergren/a4baf4716bfad6da989417a10e1ccc5f to your computer and use it in GitHub Desktop.
Save JimWestergren/a4baf4716bfad6da989417a10e1ccc5f to your computer and use it in GitHub Desktop.
Simple method to check the Pwned Passwords API using PHP
<?php
/**
* Simple method to use the API from https://www.troyhunt.com/ive-just-launched-pwned-passwords-version-2/
* Written by Jim Westergren and released to public domain
* @return int count
*/
function checkPawnedPasswords(string $password) : int
{
$sha1 = strtoupper(sha1($password));
$data = file_get_contents('https://api.pwnedpasswords.com/range/'.substr($sha1, 0, 5));
if (FALSE !== strpos($data, substr($sha1, 5))) {
$data = explode(substr($sha1, 5).':', $data);
$count = (int) $data[1];
}
return $count ?? 0;
}
@designviacode
Copy link

Thanks @JimWestergren 😉 😄

@nmxcgeo
Copy link

nmxcgeo commented Feb 25, 2018

What are the differences between this and https://github.com/ron-maxweb/pwned-passwords ?
I mean, I see that one is neatly wrapped into a class and returns true or false for the some $maxUsage but the essential function should be the same.

Especially I would like to know, why $count = (int) $data[1]; works and if there are any advantages of file_get_contents() over curl.
What is about connection error resilience?

Thanks.
Nmxcgeo

@JimWestergren
Copy link
Author

@nmxcgeo His code was written later than mine and I think mine is better. His code is looping all the lines and doing stuff there even if the hash is not even mentioned on the list. The API is hosted on a CDN and there should be no major difference with file_get_contents() over curl. He is overly complicating things.

@aselvan
Copy link

aselvan commented Feb 26, 2018

@JimWestergren -- I agree, the function snippet you wrote is simple and does the job well. I am using it and it works great. Thank you.

@hazzlewis
Copy link

What if the given password's hash matches the first returned from the api? Wouldn't strpos() would return 0 ?

I'd change line 11 to
if (FALSE !== strpos($data, substr($sha1, 5))) {

@JimWestergren
Copy link
Author

@hazzlewis Good catch. I have updated the code.

@MedeirosGuilherme
Copy link

Does it need the whole installation of the library first or this code alone will do the trick?

@JimWestergren
Copy link
Author

Does it need the whole installation of the library first or this code alone will do the trick?
@MedeirosGuilherme Those lines is all that is needed.

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