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:
How to Hide Password in HTML ?
Next article icon

How To Hash Passwords In Python

Last Updated : 28 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 unique password for every text, even if the plaintext password is the same.

Why do we need to Hash a Password?

Hashing is used mainly to protect a password from hackers. Suppose, if a website is hacked, cybercriminals don’t get access to your password. Instead, they just get access to the encrypted “hash” created by the method of hashing.

What is salt in hashing?

In cryptography, a salt is random data used as an additional input to a one-way function that hashes data, such as a password. Salts are used to keep passwords safe while they are being stored. Historically, only the password’s cryptographic hash function was maintained on a system, but over time, additional precautions were developed to prevent the identification of duplicate or common passwords. One such prevention is salting.

 

Encryption: Encryption is the process of encoding plain text or any information in such a way that only authorized people can read it with a corresponding key so that confidential data can be protected from unauthorized persons. 

Hashing: Hashing converts any amount of data into a fixed-length hash that cannot be reversed. It is widely used in cryptography. The hash allows us to validate if the input has changed even slightly, if it is changed the resulting hash will be different. In this article, we are going to learn the  Salted Password Hashing technique. It includes converting an algorithm to map data of any size to a fixed length.

What is BCrypt?

The BCrypt Algorithm is used to hash and salt passwords in a secure way. BCrypt enables the creation of a password protection layer that can develop local hardware innovation in order to protect against long-term hazards or threats, such as attackers having the computational capacity to guess passwords twice as efficiently.

Install bcrypt using pip:

 pip install bcrypt

Example: In this Program, we will be hashing the password using bcrypt.

Here we are using “GeekPassword” as an input to be converted to a hash.

Python

import bcrypt
 
# Declaring our password
password = b'GeekPassword'
 
# Adding the salt to password
salt = bcrypt.gensalt()
# Hashing the password
hashed = bcrypt.hashpw(password, salt)
 
# printing the salt
print("Salt :")
print(salt)
 
# printing the hashed
print("Hashed")
print(hashed)
                      
                       

Output:

 

What is Hashlib?

The Python hashlib module is an interface for easily hashing messages. This contains many methods that will handle hashing any raw message into an encrypted format. The main purpose of this module is to use a hash function on a string and encrypt it so that it is very difficult to decrypt it. hash library: It is used to create a hash table. The hash table is a data structure that is designed for searching through a set of entries, each of which is identified by a unique key.

Install hashlib using pip:

pip install hashlib

Example 2: In this Program, we will be hashing the password using hashlib.

Here we are using “GeekPassword” as an input to be converted to a hash.

Python

import hashlib
 
# Declaring Password
password = 'GeeksPassword'
# adding 5gz as password
salt = "5gz"
 
# Adding salt at the last of the password
dataBase_password = password+salt
# Encoding the password
hashed = hashlib.md5(dataBase_password.encode())
 
# Printing the Hash
print(hashed.hexdigest())
                      
                       

Output:

 

 Using the Argon2 algorithm:

One approach that is not mentioned in the provided article is using the Argon2 algorithm to hash passwords in Python. Argon2 is a password-hashing function that was selected as the winner of the Password Hashing Competition (PHC) in 2015. It is designed to be resistant to attacks such as dictionary attacks, brute-force attacks, and precomputation attacks.

To use Argon2 to hash passwords in Python, you can use the argon2-cffi library. Install using pip install argon2-cffi .Here is an example of how to use the argon2-cffi library to hash a password:

Python3

import argon2
 
# Declare the password as a bytes object
password = b'MySecurePassword'
 
# Hash the password using Argon2
hashed_password = argon2.hash_password(password)
 
# Print the hashed password
print(hashed_password)
                      
                       

Output:

b’$argon2i$v=19$m=65536,t=3,p=4$FHzFXaVPKR0Ryz2oymZ8Gw$3PMIBGgUPGq2CrzPTB+3BnsfX4l7p5At67Bg+Wi68Bw’
 



Next Article
How to Hide Password in HTML ?

A

ayushcoding100
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • How to Parse Hash in Ruby?
    Parsing a hash in Ruby entails gaining access to its keys and values, iterating over them, and carrying out any necessary actions. The article focuses on discussing the ways to parse a hash in Ruby. Table of Content Iterating through a HashAccessing Hash ElementsSorting a HashIterating through a Has
    2 min read
  • Hashing Passwords in Python with BCrypt
    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 anothe
    4 min read
  • How to secure database passwords in PHP?
    Most of the websites are providing sing up and login facility to the user. User has to create a password and use it for login to the website. But it is very important to secure the password of the user. password_hash() function provides the facility to securely store the password of the user to the
    1 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
  • How to Hide Password in HTML ?
    Hiding the password is commonly known as Password Masking. It hides the password characters when entered by the users by the use of bullets (•), an asterisk (*), or some other characters. It is always a good practice to use password masking to ensure security and avoid misuse. Generally, password ma
    2 min read
  • MD5 hash in Python
    MD5 is a cryptographic hash function that produces a 128-bit hash value, usually shown as a 32-character hexadecimal string. While it was commonly used for tasks like data integrity checks, MD5 is now considered insecure due to collision vulnerabilities. Despite this, it remains useful for non-sensi
    5 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
  • Hash Map in Python
    Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. Think of a hash map as a cabinet having drawers with label
    6 min read
  • Hash Set in Python
    Hash Set is a data structure that stores unique elements in an unordered manner and provides highly efficient operations for searching, inserting, and deleting elements. Python Set data type is a built-in implementation of a hash set. Python sets are implemented using hash tables, where each element
    2 min read
  • How to Store Username and Password in Flask
    This article covers storing usernames and passwords in a Flask web app using MySQL. After logging in, users see a welcome message with their username. InstallationTo make our project we first create a virtual environment, to learn how to create and activate a virtual environment, refer to - Python v
    6 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