The Wayback Machine - https://web.archive.org/web/20241003050448/https://www.geeksforgeeks.org/hashing-passwords-in-python-with-bcrypt/
Open In App

Hashing Passwords in Python with BCrypt

Last Updated : 03 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

 



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 to hash passwords. It is a password-hashing functio
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 access to every individual. Hence, the zip file is pro
3 min read
How to Extract Chrome Passwords in Python?
In this article, we will discuss how to extract all passwords stored in the Chrome browser. Note: This article is for users who use Chrome on Windows. If you are a Mac or Linux user, you may need to make some changes to the given path, while the rest of the Python program will remain the same. Installation: Now, Let's install some important librari
4 min read
GUI to generate and store passwords in SQLite using Python
In this century there are many social media accounts, websites, or any online account that needs a secure password. Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We
8 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 can be encrypted. maskpass() maskpass() is a Pyth
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 malicious activity. Password hashing generates a uniq
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 access the system keyring service. Only authorized
2 min read
Implementation of Hashing with Chaining in Python
Hashing is a data structure that is used to store a large amount of data, which can be accessed in O(1) time by operations such as search, insert and delete. Various Applications of Hashing are: Indexing in database Cryptography Symbol Tables in Compiler/Interpreter Dictionaries, caches, etc. Concept of Hashing, Hash Table and Hash Function Hashing
3 min read
Compare two files using Hashing in Python
In this article, we would be creating a program that would determine, whether the two files provided to it are the same or not. By the same means that their contents are the same or not (excluding any metadata). We would be using Cryptographic Hashes for this purpose. A cryptographic hash function is a function that takes in input data and produces
3 min read
Full domain Hashing with variable Hash size in Python
A cryptographic hash function is a special class of hash function that has certain properties which make it suitable for use in cryptography. It is a mathematical algorithm that maps data of arbitrary size to a bit string of a fixed size (a hash function) which is designed to also be a one-way function, that is, a function which is infeasible to in
5 min read
Address Calculation Sort using Hashing
In this sorting algorithm, Hash Function f is used with the property of Order Preserving Function which states that if [Tex]x <= y, f(x) <= f(y) [/Tex]. Hash Function: f(x) = floor( (x/maximum) * SIZE )where maximum => maximum value in the array, SIZE => size of the address table (10 in our case), floor => floor functionThis algorith
14 min read
hmac - Keyed-Hashing for Message Authentication
HMAC is a mechanism for message authentication using cryptographic hash functions. HMAC can be used with any iterative cryptographic hash function, e.g., MD5, SHA-1, in combination with a secret shared key. This module implements the HMAC algorithm. The basic idea is to generate a cryptographic hash of the actual data combined with a shared secret
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Practice Tags :