Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ Hashing User Passwords Using bcrypt in Python

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š Hashing User Passwords Using bcrypt in Python


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Web-based services and websites store hashed versions of your passwords, which means your actual password isn't visible or stored in their database instead a string of fixed-length characters is stored.

Hashing is a security technique used to secure your passwords or texts stored in databases. A hash function is used to generate a string of unique fixed-length characters from the provided password by the user.

Let's see how the hashing is done. In this article, you'll use the bcrypt library to hash the user's password and then compare that hashed password to the actual password in Python. You'll also learn more about the bcrypt library.

Installing bcrypt

Open your terminal window and run the following command to install the bcrypt library using pip.

pip install bcrypt

Now that the bcrypt is installed in your system, the next step is to use it for hashing the user's password.

Hash Password using bcrypt

In this section, you'll see the functions provided by the bcrypt library that will help you generate salt and hash values.

import bcrypt

# Password to Hash
my_password = b'Sachinfromgeekpython'

# Generating Salt
salt = bcrypt.gensalt()

# Hashing Password
hash_password = bcrypt.hashpw(
    password=my_password,
    salt=salt
)

print(f"Actual Password: {my_password.decode('utf-8')}")
# Print Hashed Password
print(f"Hashed Password: {hash_password.decode('utf-8')}")

The above code imports the bcrypt library for hashing the password. A test password is provided in bytes and is stored inside the my_password variable.

The code uses the gensalt() function from the bcrypt library to generate the salt, a string of characters to enhance security.

The salt is a random and unique string of characters combined with the password before hashing to provide additional security, it will always be unique, if two users have the same password, their hashed passwords will be different.

Then the actual password (my_password) and salt (salt) are passed to the hashpw() function from the bcrypt library to produce the hash value of the actual password.

Finally, the actual and hashed passwords are decoded and printed.

Actual Password: Sachinfromgeekpython
Hashed Password: $2b$12$RF6JLXecIE4qujuPgTwkC.GN2BsOmGf8Ji10LyquoBaHkHWUWgiAm

Check Password using bcrypt

Now that you've hashed the password, the next step is to verify the actual password's hash value against the user-provided password.

import bcrypt

# Password to Hash
my_password = b'Sachinfromgeekpython'

# Generating Salt
salt = bcrypt.gensalt()

# Hashing Password
hash_password = bcrypt.hashpw(
    password=my_password,
    salt=salt
)

# User-provided Password
user_password = b'Sachinfromgeekpython'

# Checking Password
check = bcrypt.checkpw(
    password=user_password,
    hashed_password=hash_password
)

# This will print True or False
print(check)

# Verifying the Password
if check:
    print("Welcome to GeekPython.")
else:
    print("Invalid Credential.")

The above code uses the checkpw() function from the bcrypt library to check the user-provided password against the hashed password. The hashed password (hash_password) and user-provided password (user_password) are passed inside the function and the result is stored inside the check variable.

Then the code prints the check variable to obtain the result. In the end, an if-else statement is used to verify the password.

True
Welcome to GeekPython.

True in the output above indicates that the hashed password matches the user-provided password, making the first condition true.

Hash Password Using KDF (Key Derivation Function)

KDF (Key Derivation Function) is used to add additional security in password hashing. KDFs are used to derive keys from passwords for authentication purposes while including salt and the number of rounds.

import bcrypt

password = b'Sachinfromgeekpython'
salt = bcrypt.gensalt()

# Using KDF from bcrypt Lib
key = bcrypt.kdf(
    password=password,
    salt=salt,
    desired_key_bytes=32,
    rounds=200
)

# Print Generated Key
print(f"Key: {key}")

The above code uses the kdf() function from the bcrypt library to derive a key from the password. The function is passed with four parameters:

  • password: This parameter is set to the password variable which contains a byte string.

  • salt: This parameter is set to the salt variable that contains a unique and fixed-length salt.

  • desired_key_bytes: This parameter is set to 32 which is the desired length of the derived key we want. You can set it to your own desired length.

  • rounds: This parameter is set to 200 which is the number of iterations to make the derivation of the key more computationally intense to increase security. The higher the rounds more the security but the more it uses resources and time.

Finally, the result stored in the key variable is printed.

Key: b'\xc4#VW\x9a\x16\xdbG?\x11\xa9\xf7\xbd\x88"7+zxo\xfe@\xce\xab\x89\xc3g\x1c\xec~\xbe\xf7'

Verifying the Password with KDF

import bcrypt

password = b'Sachinfromgeekpython'
salt = bcrypt.gensalt()

# Using KDF from bcrypt Lib
key = bcrypt.kdf(
    password=password,
    salt=salt,
    desired_key_bytes=32,
    rounds=200
)

# User-provided Password
user_password = b'Sachinfromgeekpython'

# Deriving Key from User-provided Password
user_key = bcrypt.kdf(
    password=user_password,
    salt=salt,
    desired_key_bytes=32,
    rounds=200
)

# Verifying the Password
if user_key == key:
    print("Welcome to GeekPython.")
else:
    print("Invalid Credential.")

The code derives the key from the user-provided password (user_password) and stores it inside the user_key variable.

Then the code verifies the derived keys from the user-provided password (user_key) and the actual password (password).

Welcome to GeekPython.

The output indicates that the key derived from the user-provided password matches the key derived from the actual password.

Customizing Salt

The gensalt() function accepts two parameters: rounds and prefix, which allow you to customize the number of rounds of hashing to apply to the salt and prefix of the salt.

import bcrypt

# Customize Salt
salt = bcrypt.gensalt(
    rounds=30,
    prefix=b'2a'
)

# Print Generated Salt
print(salt.decode('utf-8'))

The above code customizes the salt generation by passing the rounds parameter which is set to 30 and the prefix parameter which is set to b'2a' to the gensalt() function.

$2a$30$5uKaXaXVceqCjmKkPf2mnu

You can notice that in the beginning after $, above provided 2a is prefixed, and just after that 30 indicates the number of rounds.

Conclusion

Password hashing prevents exposing the user's actual password to the attackers. The hash function, which is simply a mathematical function is used to produce the hash value of the password.

In this article, you've learned to hash the user's password using the bcrypt library in Python and then check the produced hash value against the user-provided password. Additionally, you've seen the KDF (Key Derivation Function) that adds additional security for hashing.

๐Ÿ†Other articles you might be interested in if you liked this one

โœ…Different methods to convert bytes into a string in Python.

โœ…Create a WebSocket server and client in Python.

โœ…Create multi-threaded Python programs using a threading module.

โœ…Comparing the accuracies of 4 different pre-trained deep learning models?

โœ…Upload and display images on the frontend using Flask.

โœ…How does the learning rate affect the ML and DL models?

That's all for now

Keep CodingโœŒโœŒ

...



๐Ÿ“Œ Hashing User Passwords Using bcrypt in Python


๐Ÿ“ˆ 72.91 Punkte

๐Ÿ“Œ Password hashing using Bcrypt in Python


๐Ÿ“ˆ 58.3 Punkte

๐Ÿ“Œ Password Hashing Developer Guide - Part 3 Python Bcrypt Implementation


๐Ÿ“ˆ 52.94 Punkte

๐Ÿ“Œ Do you use bcrypt or other 3rd-party npm packages when hashing user password?


๐Ÿ“ˆ 52.12 Punkte

๐Ÿ“Œ Hashing a file vs hashing its content


๐Ÿ“ˆ 37.69 Punkte

๐Ÿ“Œ bcrypt or argon2 for storing passwords?


๐Ÿ“ˆ 35.92 Punkte

๐Ÿ“Œ [CVE-2014-9016] DoS by hashing large passwords


๐Ÿ“ˆ 27.47 Punkte

๐Ÿ“Œ Apocalypse Meow <= 21.2.7 - BCrypt Authentication Bypass


๐Ÿ“ˆ 27.29 Punkte

๐Ÿ“Œ Kelektiv node.bcrypt.js inadequate encryption [CVE-2020-7689]


๐Ÿ“ˆ 27.29 Punkte

๐Ÿ“Œ Windows Credential Guard BCrypt Context Use-After-Free Privilege Escalation


๐Ÿ“ˆ 27.29 Punkte

๐Ÿ“Œ Wine Staging 2.3 Implements ECB Mode in Bcrypt, Adds Minor CSMT Improvements


๐Ÿ“ˆ 27.29 Punkte

๐Ÿ“Œ ELI5 difference between bcrypt and sha password with salt


๐Ÿ“ˆ 27.29 Punkte

๐Ÿ“Œ Have I missed something about SHA-512 v. BCRYPT?


๐Ÿ“ˆ 27.29 Punkte

๐Ÿ“Œ [$] Python and hashing None


๐Ÿ“ˆ 25.65 Punkte

๐Ÿ“Œ Python Secure Password Management: Hashing and Encryption #๏ธโƒฃ๐Ÿ”โœจ


๐Ÿ“ˆ 25.65 Punkte

๐Ÿ“Œ Longest Palindromic Substring using hashing in O(nlogn)


๐Ÿ“ˆ 24.2 Punkte

๐Ÿ“Œ Lil-Pwny - Auditing Active Directory Passwords Using Multiprocessing In Python


๐Ÿ“ˆ 20.79 Punkte

๐Ÿ“Œ Any books similar to Black Hat Python, or Violent Python that use Python v3?


๐Ÿ“ˆ 20.42 Punkte

๐Ÿ“Œ What Makes Python Python? (aka Everything About Pythonโ€™s Grammar)


๐Ÿ“ˆ 20.42 Punkte

๐Ÿ“Œ Switching Geany to execute Python files as Python 3, not Python 2


๐Ÿ“ˆ 20.42 Punkte

๐Ÿ“Œ Python for Beginners [1 of 44] Programming with Python | Python for Beginners


๐Ÿ“ˆ 20.42 Punkte

๐Ÿ“Œ Introducing More Python for Beginners | More Python for Beginners [1 of 20] | More Python for Beginners


๐Ÿ“ˆ 20.42 Punkte

๐Ÿ“Œ Master Ethical Hacking with Python Tutorial - Password Cracker Using Python


๐Ÿ“ˆ 18.97 Punkte

๐Ÿ“Œ Pyshark - Python Wrapper For Tshark, Allowing Python Packet Parsing Using Wireshark Dissectors


๐Ÿ“ˆ 18.97 Punkte

๐Ÿ“Œ RHEL 8 install Python 3 or Python 2 using yum


๐Ÿ“ˆ 18.97 Punkte

๐Ÿ“Œ Massive Python Survey Reveals Popularity of Linux and PyCharm, Just 10% Still Using Python 2


๐Ÿ“ˆ 18.97 Punkte

๐Ÿ“Œ Master Python Documentation - Part1: Using the Python Interpreter.


๐Ÿ“ˆ 18.97 Punkte

๐Ÿ“Œ Open Real Estate 1.15.1 XSS / SQL Injection / Weak Hashing


๐Ÿ“ˆ 18.85 Punkte

๐Ÿ“Œ MyBB 1.8.6 Cross Site Request Forgery / Weak Hashing


๐Ÿ“ˆ 18.85 Punkte

๐Ÿ“Œ Password Hashing, Salts, Peppers | Explained!


๐Ÿ“ˆ 18.85 Punkte

๐Ÿ“Œ Open Real Estate 1.15.1 XSS / SQL Injection / Weak Hashing


๐Ÿ“ˆ 18.85 Punkte











matomo