Habilelabs-Logo
Blog

Steps to Protect Your User Password using Pwned Password API

May 12th, 2021 . 4 minutes read
Blog featured image

Most of the time users don’t even know that their password is compromised in a data leak and they keep using it while registering at new sites. This is a very common reason which can lead to your user account getting compromised.

To protect against it, we can use Pwned Password API to check for user password leak during registration. Pwned Password API uses a k-Anonymity model to check for leaks without having to send actual user passwords to their server.

Step 1

Create a SHA-1 hash of the password you want to test, and split the generated hash into 2 parts. The first one contains the first 5 letters and the other remaining.

Step 2

Now we need to hit the Pwned Password API with the first 5 letters of the hash.

Syntax:

GET https://api.pwnedpasswords.com/range/{first 5 hash chars}

Example:

GET https://api.pwnedpasswords.com/range/23D42

If there is any match, API will respond with a 200 containing suffix of all matched prefixes, followed by a count of how many times it appears in the data set.

Example Response:

Step 3

We can now process the response and search for the suffix and see how many times it appeared in the dataset.

In our case for password admin@123 we can see its suffix F5F3F66498B2C8FF4C20B8C5AC826E47146 appeared 3423 times which is bad.

We can then remind the user to choose a different password depending on our application stack.

Tip-

It’s always good to add **Add-Padding: true** in the request Header as it further enhances privacy by returning 800-1000 results regardless of the number of hash suffixes returned by the service.

Implementation

We can either implement it manually by following the above steps or use a package. This can be either in the frontend or backend as we wish.

Laravel, a very popular PHP framework recently added inbuild support for it.

PHP (Laravel)

In Laravel 8.39 and above, we can now just use the Password Rule Object to check for compromised passwords.

Example:

Under the hood, Laravel will call the Pwned password API and handle the checking for you. Here is the part of the code that is responsible in case you want to use this in older Laravel versions.

In JavaScript, this can either be implemented on the frontend or on the backend (NodeJS) as per requirement, here is a well-maintained library for this task.

https://github.com/wKovacs64/hibp

We hope you liked this blog and expect that it will help you with better password protection.

Author: Zishan Ansari
Share: