How to Hash Passwords in Python?


Securing user passwords is a critical aspect of application development. One of the best ways of safeguarding passwords is by utilizing hashing calculations. Hashing is a course of changing over plain text passwords into a fixed-length series of characters that can't be switched. In this article, we will investigate how to hash passwords in Python, talking about the language structure and calculations included. We will also provide two real executable code examples to demonstrate different approaches to password hashing.

Syntax

To hash passwords in Python, we will utilize the hashlib module, which gives different hashing algorithms. The fundamental sentence structure to hash a secret phrase utilizing hashlib is as per the following −

import hashlib
password = "my_password".encode('utf-8')  # Convert the password to bytes
hash_object = hashlib.sha256(password)   # Choose a hashing algorithm (e.g., SHA-256)
hex_dig = hash_object.hexdigest()        # Get the hexadecimal digest of the hashed password

Algorithm

The algorithm for password hashing can be summarized in the following steps −

  • Convert the plain text password to bytes using the encode() method.

  • Select a hashing algorithm from the hashlib module, such as SHA-256 or bcrypt.

  • Create a hash object using the chosen algorithm.

  • Pass the password bytes to the hash object using the update() method.

  • Retrieve the hashed password using the hexdigest() method.

Approach 1: Using SHA-256 Algorithm

One regularly utilized hashing calculation is SHA-256. We should see an illustration of how to hash passwords utilizing this calculation −

Example

import hashlib

def hash_password(password):
   password_bytes = password.encode('utf-8')
   hash_object = hashlib.sha256(password_bytes)
   return hash_object.hexdigest()

# Assumed password
password = "MySecretPassword"

hashed_password = hash_password(password)
print("Hashed password:", hashed_password)

Output

Hashed password: c152246c91ef62f553d2109b68698b19f7dd83328374abc489920bf2e2e23510

Explanation

Using SHA-256 Algorithm

The SHA-256 algorithm is a generally utilized cryptographic hash capability that has a place with the SHA-2 (Secure Hash Algorithm 2) family. It takes an information and produces a fixed-size 256-bit (32-byte) hash value. How about we plunge into the means associated with hashing passwords utilizing the SHA-256 algorithm.

  • Importing the hashlib Module −

    To begin, we need to import the hashlib module, which provides the necessary functionality for hashing data using various algorithms.

  • Converting the Password to Bytes −

    Before we can hash the secret word, we want to change it over completely to bytes utilizing the encode() strategy. This step is vital in light of the fact that the hashlib module works on byte-like articles.

  • Creating a Hash Object −

    Then, we make a hash object utilizing the hashlib.sha256() constructor, determining the SHA-256 calculation. This item will be answerable for playing out the genuine hashing.

  • Updating the Hash Object −

    To hash the secret word, we pass the secret word bytes to the hash object utilizing the update() technique. This strategy can be called on different occasions assuming that you really want to refresh the hash with extra information.

  • Retrieving the Hashed Password −

    At long last, we recover the hashed secret key by calling the hexdigest() technique on the hash object. This strategy returns the hexadecimal portrayal of the hashed secret word.

By following these means, we can safely hash passwords involving the SHA-256 calculation in Python. It's vital to take note of that while SHA-256 is major areas of strength for a capability, it is as yet prudent to consolidate extra safety efforts like salting and key extending to additionally safeguard against expected weaknesses.

Approach 2: Using bcrypt Algorithm

One more well known algorithm for password hashing is bcrypt, which is intended to be slow and resistant to brute-force attacks. This is an illustration of the way to utilize bcrypt to hash passwords −

Note − the output will change as you run the program because it is a hashcode.

Example

!pip install bcrypt

import bcrypt

def hash_password(password):
   password = "MySecretPassword" 
   password_bytes = password.encode('utf-8')
   hashed_bytes = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
   return hashed_bytes.decode('utf-8')

# Usage example
hashed_password = hash_password("MySecretPassword")
print("Hashed password:", hashed_password)

Output

Hashed password: $2b$12$PmX5lm35jt1SEvvVfqXuz.YUE/N0W/oqKFGAPQe9eqJKRh021jUzy

Explanation

The bcrypt algorithm is a broadly prescribed decision for secret password hashing because of its intrinsic security highlights. It is expected to be slow and computationally costly, making it resistant to brute-force attacks. How about we investigate the means associated with hashing passwords utilizing bcrypt.

  • Importing the bcrypt Module −

    To utilize the bcrypt algorithm, we need to import the bcrypt module, which provides the necessary functions and constants for working with bcrypt in Python.

  • Converting the Password to Bytes −

    Similar to the previous approach, we convert the plain text password to bytes using the encode() method. This step ensures compatibility with the bcrypt functions.

  • Generating a Salt −

    Before hashing the password, bcrypt requires the generation of a salt—a random value used to modify the password hash. We use the bcrypt.gensalt() function to generate a suitable salt.

  • Hashing the Password −

    To hash the secret password, we call the bcrypt.hashpw() capability, passing the secret phrase bytes and the created salt as contentions. This capability consolidates the secret phrase and salt, applies the bcrypt algorithm, and produces the hashed secret password.

  • Retrieving the Hashed Password −

    The consequence of the bcrypt.hashpw() capability is a hashed secret phrase addressed as a byte-like item. To get a comprehensible string, we interpret the byte-like item to UTF-8 utilizing the decode() technique.

By following these means, we can really hash passwords utilizing the bcrypt calculation in Python. Bcrypt's sluggish hashing interaction and capacity to create special salts for every secret phrase go with it a powerful decision for secret phrase security. Nonetheless, it's essential to guarantee that the bcrypt library is modern, as more seasoned renditions might have weaknesses. Also, consolidating other security practices, for example, salting and key extending can additionally improve the general security of hashed passwords.

Conclusion

In this article, we examined the significance of secret word hashing for secure application improvement. We investigated two distinct ways to deal with hash passwords in Python utilizing the hashlib and bcrypt modules. The principal approach exhibited the use of the SHA-256 calculation, while the second methodology displayed the bcrypt calculation, known for its protection from animal power assaults.

Keep in mind, while executing secret word hashing, it is essential to consider extra safety efforts, like involving a one of a kind salt for every secret word and utilizing proper key extending strategies. These practices further enhance the security of hashed passwords.

By utilizing the information provided in this article, you can ensure the protection of user passwords within your Python applications, bolstering the overall security of your systems.

Updated on: 27-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements