How to Check Password Strength with Python

Learn how to check password strength in Python using the zxcvbn library. This guide walks you through installing zxcvbn, importing necessary libraries, and creating functions to test single and multiple passwords. You'll securely input passwords and receive feedback on their strength.
  · 5 min read · Updated jun 2024 · Ethical Hacking

Before we get started, have you tried our new Python Code Assistant? It's like having an expert coder at your fingertips. Check it out!

In this quick guide, you'll learn how to check password strength with Python. This is a very crucial program for our day-to-day online activities. Even though it's being preached every single day, a lot of people do not actually know what a strong password is. The program we'll build today will help us with that.

To achieve this, we'll be using zxcvbn. zxcvbn in Python is a password strength estimator library that evaluates the security of passwords based on patterns and common usage, providing a score and feedback on password strength.

You can install it by running:

$ pip install zxcvbn

Open up a Python file, as always, name it meaningfully like check_password_strength.py and follow along. 

We'll start by importing the necessary libraries:

from zxcvbn import zxcvbn
import pprint, getpass, sys

The imports bring in zxcvbn for password strength estimation, pprint for pretty-printing data structures, getpass for secure password input (just like the Linux terminal), and sys for system-specific parameters and functions (in our case command-line arguments).

We will make our program flexible so we can either check the strength of one password or pass a file containing passwords and check all to save time. 

First, we create a function to check the strength of just one password:

def test_single_password():
    password = getpass.getpass("[?] Enter your password: ")
    result = zxcvbn(password)
    print(f"Value: {result['password']}")
    print(f"Password Score: {result['score']}/4")
    print(f"Crack Time: {result['crack_times_display']['offline_slow_hashing_1e4_per_second']}")
    print(f"Feedback: {result['feedback']['suggestions']}")
    #pprint.pp(result)

In this test_single_pasword(), we start by accepting the input password using getpass. We're using getpass so that if a user has to use this program in public, they wouldn't worry about someone seeing their password on their screen. They just have to be smart with typing.

After getting the password, we're passing it to the zxcvbn function for password analysis. We're storing the results of the analysis in a variable called result

Next, we display some important parameters from the result variable like the password entered (which is represented as "value" and not "password"), and the score of the password (which is usually over 4. So we have 0 being the weakest and 4 being the strongest), estimated time to crack the given password and helpful feedback. 

Of course, you can print the entire result. For that, I'll advise using the pprint library as the regular print function is very ugly for that. You can uncomment the line above and see for yourself.

Next, we create a function for handling multiple passwords by accepting them through a file:

def test_multiple_passwords(password_file):
    try:
        with open(password_file, 'r') as passwords:
            for password in passwords:
                result = zxcvbn(password.strip('\n'))
                print('\n[+] ######################')# for readability
                print(f"Value: {result['password']}")
                print(f"Password Score: {result['score']}/4")
                print(f"Crack Time: {result['crack_times_display']['offline_slow_hashing_1e4_per_second']}")
                print(f"Feedback: {result['feedback']['suggestions']}")
                #pprint.pp(result)
           
    except Exception:
        print('[!] Please make sure to specify an accessible file containing passwords.')

This function is essentially the same as the previous one. The main difference is that we allow a user to pass a file. We then open the file and check the strength of every password in the given file.

Finally, we handle the program execution - through CLI, of course:

if len(sys.argv) == 2:
    test_multiple_passwords(sys.argv[1])
elif len(sys.argv) == 1:
    test_single_password()
else:
    print('Usage: python test_password_strength.py <file> (for a file containing passwords) or \
        \npython test_password_strength.py (for a single password.)')

Essentially, we're checking the user's arguments. If the user's arguments are 2 (starting from index 0), e.g python[0] check_password_strength.py[1] passwords.txt[2], we take index 2 to be a file containing the password.

If the user's argument is/are 1 (starting from index 0), e.g python[0] check_password_strength.py[1], we take it that the user wants to check the strength of one password.

That's it! Let's run our code!

Checking the strength of one password:

$ python check_password_strenth.py

Result:

That's a result of two different passwords.

Checking the strengths of multiple passwords:

$ python check_password_strength [file containing passwords]

Result:

Please note that the file containing the passwords doesn't necessarily have to be text (.txt) file. It just has to be accessible by the program. I recommend text files, though.

In this tutorial, we learned how to write a very simple but helpful program that can check the strength of our passwords. I hope you enjoyed this one and found it helpful. You can get the complete code on this page.

If you're ever in a situation where you don't have access to running this program immediately, you can use this password strength checker tool to check the strength of your password quickly. I built the tool. You don't have to worry about privacy or data collection.

Here are similar tutorials you may find interesting:

Till next time, Happy coding ♥

Why juggle between languages when you can convert? Check out our Code Converter. Try it out today!

View Full Code Assist My Coding
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!