DEV Community

Cover image for How to hash passwords with Python
YoungWonks
YoungWonks

Posted on

How to hash passwords with Python

If you are a web developer working on creating a website, you will need to look into the safe storage of passwords for the site. How can one go about doing this? The answer lies in hashing and verification of passwords.

In this blog, we shall look at how one can hash passwords with Python. But before that, let us take a quick look at what is hashing. Hashing refers to the process of converting a given key into another value. A hash function is used to generate the new value as per a mathematical algorithm. The result of a hash function is known as a hash value or simply, a hash.

In Python, hashing can be carried out using Passlib. It is a password hashing library for Python 2 & 3, which offers cross-platform implementations of over 30 password hashing algorithms, and a framework for managing existing password hashes.

Now let us look at the steps involved in hashing passwords in Python.

Step 1: Install and import
We install Passlib first by typing pip3 install passlib in the terminal.

Alt Text

After this, we import a hashing algorithm by typing the code as shown below.

Alt Text

Step 2: Syntax
In this stage, we generate a new hash from the string and verify the password as shown below.

Alt Text

Now let us look at how this can be done in an example. First, the user would need to create an account. We would then ask the user for their email and password. After this, we hash the password and store it (maybe in a database).

Alt Text

When the user needs to access the account later, we hash what we stored against the hash of the entered password. Upon successful verification, the user can access the account.

Alt Text

Now you have successfully hashed and verified a password in Python.
However, there are other algorithms one can use in addition to the one we have shared above. You can see them below.

Alt Text

This article has been written by Suchin Ravi. Suchin is an experienced educator and technologist. Suchin teaches computer science at YoungWonks https://www.youngwonks.com and works as a lead software developer on many projects at Wonksknow https://www.wonksknow.com/.

Top comments (0)