Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Storing passwords with Python keyring
Next article icon

Hashing Passwords in Python with BCrypt

Last Updated : 03 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to hash passwords in Python with BCrypt. Storing passwords in plain text is a bad practice as it is vulnerable to various hacking attempts. That’s why it is recommended to keep them in a hashed form. 

What is hashing?

It’s a process of converting one string to another using a hash function. There are various types of hash functions but there are some basic similarities that are satisfied by all of them is that hashing is an irreversible process. i.e. conversion should be only one way, the length of hash should be fixed, and an input string should uniquely correspond with a hash so that we can compare them later, this makes it ideal for passwords and authentication.

Hashing Passwords in Python with BCrypt

 

Hash a Password in Python Using Bcrypt

Bcrypt is a password hashing function designed by Nelis Provos and David Mazières. Bcrypt uses strong cryptography to hash and salts password based on the Blowfish cipher. To make encryption stronger we can increase the “cost factor” so it can be increased as computers become faster. It is also intended to be slow, to make the brute force attacks slower and harder.

To install Bcrypt use the command – 

pip install bcrypt

The functions in Bcrypt used –

  • bcrypt.gensalt() –  It is used to generate salt. Salt is a pseudorandom string that is added to the password. Since hashing always gives the same output for the same input so if someone has access to the database, hashing can be defeated. for that salt is added at end of the password before hashing. It doesn’t need any arguments and returns a pseudorandom string.
  • bcrypt.hashpw() – It is used to create the final hash which is stored in a database.
    • Arguments – We can pass Salt and Password in form of bytecode.
    • Return value – If hashing is successful, it returns a hash string.

Hashing passwords

To use bcrypt, you’ll need to import bcrypt module, After that the bcrypt.hashpw() function takes 2 arguments: A string (bytes) and Salt. Salt is random data used in the hashing function. Let’s hash a password and print it in the following examples.

Example 1:

Python3

import bcrypt
  
# example password
password = 'password123'
  
# converting password to array of bytes
bytes = password.encode('utf-8')
  
# generating the salt
salt = bcrypt.gensalt()
  
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
  
print(hash)
                      
                       

Output: 

 

Example 2:

Now let’s just change the input password a little bit to see the behavior of hashing.

Python3

import bcrypt
  
# example password
password = 'passwordabc'
  
# converting password to array of bytes
bytes = password.encode('utf-8')
  
# generating the salt
salt = bcrypt.gensalt()
  
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
  
print(hash)
                      
                       

Output:

 

Checking passwords

The following example checks a password against a hashed value.

Example 1:

Here we will check whether the user has entered the correct password or not, for that we can use bcrypt.checkpw(password, hash). At first, let’s assume the user entered the wrong password.

Python3

import bcrypt
  
# example password
password = 'passwordabc'
  
# converting password to array of bytes
bytes = password.encode('utf-8')
  
# generating the salt
salt = bcrypt.gensalt()
  
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
  
# Taking user entered password 
userPassword =  'password000'
  
# encoding user password
userBytes = userPassword.encode('utf-8')
  
# checking password
result = bcrypt.checkpw(userBytes, hash)
  
print(result)
                      
                       

Output:

 

Example 2:

Now let’s see what happens when passwords are matched:

Python3

import bcrypt
  
# example password
password = 'passwordabc'
  
# converting password to array of bytes
bytes = password.encode('utf-8')
  
# generating the salt
salt = bcrypt.gensalt()
  
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
  
# Taking user entered password 
userPassword =  'passwordabc'
  
# encoding user password
userBytes = userPassword.encode('utf-8')
  
# checking password
result = bcrypt.checkpw(userBytes, hash)
  
print(result)
                      
                       

Output:

 



Next Article
Storing passwords with Python keyring
author
chandramauliguptach
Improve
Article Tags :
  • Python
  • python-modules
  • python-utility
Practice Tags :
  • python

Similar Reads

  • Password Hashing with Bcrypt in Flask
    In this article, we will use Password Hashing with Bcrypt in Flask using Python. Password hashing is the process of converting a plaintext password into a hashed or encrypted format that cannot be easily reverse-engineered to reveal the original password. Bcrypt is a popular hashing algorithm used t
    2 min read
  • Hiding and encrypting passwords in Python?
    There are various Python modules that are used to hide the user’s inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it
    6 min read
  • How To Hash Passwords In Python
    In this article, we are going to know how to hash passwords in python. A strong password provides safety. Plain text passwords are extremely insecure, so we need to strengthen the passwords by hashing the password. Hashing passwords is a cheap and secure method that keeps the passwords safe from mal
    4 min read
  • Storing passwords with Python keyring
    In this article, we will see how to store and retrieve passwords securely using Python's keyring package. What is a keyring package? keyring package is a module specifically designed to securely store and retrieve passwords. It is like the keychain of MacOS, using this module and Python code we can
    2 min read
  • What is Salted Password Hashing?
    Salted password hashing can be used to improve password security by adding additional layers of randomness on top of the hashing process. Salt is a cryptographically secure random string that is added to a password before it's hashed, and the salt should be stored with the hash, making it difficult
    4 min read
  • getpass() and getuser() in Python (Password without echo)
    getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal. getpass module provides two functions :Using getpass() function to prompt user password Syntax: getpass.getpass(
    2 min read
  • How to Brute Force ZIP File Passwords in Python?
    In this article, we will see a Python program that will crack the zip file's password using the brute force method. The ZIP file format is a common archive and compression standard. It is used to compress files. Sometimes, compressed files are confidential and the owner doesn't want to give its acce
    3 min read
  • What is the most used method for hashing passwords in PHP ?
    Hashing password is a technique of converting a single password into another string called hashed password. The hashed password is generally one-way, i.e. we can't go to the original password from the hashed password. So the thing is why we needed to use hashing to do all this stuff, why going one m
    3 min read
  • Double Hashing in Python
    Double hashing is a collision resolution technique used in hash tables. It works by using two hash functions to compute two different hash values for a given key. The first hash function is used to compute the initial hash value, and the second hash function is used to compute the step size for the
    4 min read
  • Cuckoo Hashing in Python
    Cuckoo Hashing derived its name from the cuckoo bird, which lays its eggs in the nests of other birds, replacing their eggs with its own. Cuckoo Hashing works in a similar manner which involves moving the values to different location whenever there is a collision in the hash table. In this article,
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences