hash password in python

To hash a password in Python, it is recommended to use a reputable library such as bcrypt or argon2. Here is an example using bcrypt:

main.py
import bcrypt

# Generate a hashed version of the password
password = b"password123"
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password, salt)

# Verify a password against a hashed version
password_attempt = b"password123"
if bcrypt.checkpw(password_attempt, hashed_password):
    print("Password is valid!")
else:
    print("Invalid password.")
360 chars
14 lines

In the above example, we first generate a salt using gensalt() and then use it to hash the password using hashpw(). To verify a password, we simply attempt to hash the provided password using the same salt, and compare the result to the original hashed password using checkpw().

gistlibby LogSnag