Validate passwords with python

In this article we can see how to validate our password and also check the strength of our password. We can set the parameters for validation like the number of special characters required, number of upper case or small case letters required, etc.

All these validations are possible with the help of a python package called “password-strength”.

Installation

The package can be installed using pip as

pip install password-strength

Basic example

A basic example for creating a validation would look like this.

Once we have created a policy, we can use it to validate our passwords.

The from_names method from the PasswordPolicy will take the following arguments.

  1. length – The length of a valid password.
  2. uppercase – Minimum number of upper case characters that should be present in a valid password.
  3. numbers – Numeric digits required.
  4. special – Number of special characters required.
  5. nonletters – This is the combination of both numbers and special characters.

We can now validate our password like this.

policy.test('ABcd12!')
# -> [Length(8), Special(2)]

This tells us that 2 tests have failed: password is not long enough, and it does not have enough special characters. You can use this information to tell the user what precisely is wrong with their password.

policy.test('[email protected]')
# -> []

Empty list tells us that this password is alright.

This test, however, enabled uses to use passwords that have a lot of repetition.

Test password strength

Complexity is a number in the range of 0.00..0.99. Good, strong passwords start at 0.66.

Let’s first see how different passwords score:

from password_strength import PasswordStats

stats = PasswordStats('qwerty123')
print(stats.strength())  #-> Its strength is 0.316

stats = PasswordStats('G00dPassw0rd?!')
print(stats.strength())  #-> Its strength is 0.585

stats = PasswordStats('V3ryG00dPassw0rd?!')
print(stats.strength())  #-> Its strength is 0.767

So, 0.66 will be a very good indication of a good password. 

We can also add the strength attribute to the PasswordPolicy class like this, just like the other params like length, numbers etc.

We can also generate passwords using python instead of just validating the strength of our password.

Create password

Although, password generation is not complex using python, we will be using an external library here for simplicity.

Install the library via pip as

pip install readable_password

These are some of the examples to generate the password with various parameters based on requirements. I am not explaining each example in detail as they are self-explanatory.

The password generated by the above code is,

[email protected]
Lihu604!
Hejuros?
Jegibeni
mutemoxo

Hope this article is useful. Thanks for reading.

Happy coding!