Password Hashing with Bcrypt

Git Commit: add support for hashing
Storing raw passwords is super dangerous. In case our db is compromised for whatsoever reason. All our user's passwords will be available to the hacker without any effort. To tackle this scenario we make use of password hashing. In very simple words, It is a one-way algorithm to convert passwords to a string that looks like gibberish e.g. If your password is "HelloWorld" it would become $2y$12$kbQm9Vb96023efZFhSkZf.a4bAGyzDW6zKC/K1JDtKY0f.gKZxAHO with 12 cryptographic iterations. I would suggest playing with Bcrypt Generator to get a feel of hashing. The wonderful thing about hashing is that we do not de-hash but we compare hashes to see if the password entered is the same as that of the existing password.
There are many hashing algorithms like PBKDF2, SHA1, SHA256, and many more. In this post, we are going to use the BCrypt algorithm. We will be using a super library passlib, to handle hashing and comparison for us. So, let's install passlib along with Bcrypt. Update your requirements.txt file with passlib[bcrypt] and do a pip install -r requirements.txt.


#hashing              #new

Now, we are going to create a file in which we will be implementing the class to handle Hashing. Make a new file inside the core folder named   core > and paste the following lines.

from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

class Hasher():
    def verify_password(plain_password, hashed_password):
        return pwd_context.verify(plain_password, hashed_password)

    def get_password_hash(password):
        return pwd_context.hash(password)
(env) nofoobar@fastapi:~/Documents/$  python

>>> Hasher.get_password_hash("supersecret1234")
>>> Hasher.verify_password("supersecret1234","$2b$12$qFVOexqUL3/qhlHwy8W8eu0S80hxq2h382cTQrJyqyDJiJlCVRBhe")

Done, Now, I am going off-screen, There is a world outside which is also important <3 :D

Prev: Dependency Injection : … Next: Our First API …

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.



Refund Policy

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial