Here at Twilio we’re fans of using a second factor to protect user accounts, but that doesn’t mean we’ve forgotten the first factor. Encouraging users to pick strong passwords is still the first line of defence for their accounts.

After spending years collecting lists of passwords from publicly available data breaches at HaveIBeenPwned, Troy Hunt has made available an API to check whether a password has been used before. This post will show you how to encourage your users to use stronger passwords by checking against the pwned passwords API.

The Pwned Passwords API

In 2017 NIST (National Institute of Standards and Technology) as part of their digital identity guidelines recommended that user passwords are checked against existing public breaches of data. The idea is that if a password has appeared in a data breach before then it is deemed compromised and should not be used. Of course, the recommendations include the use of two factor authentication to protect user accounts too.

The Pwned Passwords API allows you to check whether a potential password has been exposed as part of a number of data breaches across the web. There is an online version of the API where you can enter a password and see if it’s been used before. If it has, it’ll also show how many times it appeared. The data has more than 500,000,000 unique passwords that have been used before.

While you’re at it, check the main haveibeenpwned service with your email address to see if your credentials have been in any of those data breaches. Spoiler alert, it probably has!

The API

The Pwned Passwords API allows us to check a password against the database of passwords. With the results, we can advise users to choose better passwords when they sign up for a service, when they log in or when they change their password.

Your security senses might be tingling at the prospect of sending all your users’ passwords to a third-party. Thankfully you needn’t worry.

Instead of sending the whole password, you only need to hash the password using SHA-1 and send the first 5 characters of the result. This returns all the hashes that are in the data set beginning with those 5 characters and if the remained of the hash is present, the password was in the list. You can read more about this technique, the dump of passwords and the API in this article.

Let’s take a look at how to use this in a Ruby application using a couple of gems that abstract that process away for you.

Pwned Passwords in Ruby

If you want to use the Pwned Passwords API in any Ruby application then do I have the gem for you. It’s called pwned and it makes checking passwords against the API really easy.

You can check out all the documentation for pwned on GitHub, but here’s how you get started.

Install the gem: