hash password with secret in python

To hash a password with a secret in python, you can use the hashlib library and the secrets module.

Here's an example code block:

main.py
import hashlib
import secrets

# Example password
password = "MyStrongPassword123"

# Generate a random secret key
secret = secrets.token_urlsafe(16)

# Create a hash object using SHA-256 algorithm
hash_object = hashlib.sha256()

# Update the hash object with the password and the secret
hash_object.update(str(password + secret).encode('utf-8'))

# Get the hashed password as a string
hashed_password = hash_object.hexdigest()

# Print the original password, secret key, and hashed password
print("Password  : " + password)
print("Secret key: " + secret)
print("Hashed    : " + hashed_password)
596 chars
23 lines

In this example, we generate a random secret key using the secrets module, and then we use the hashlib library to create a hash object using the SHA-256 algorithm. We update the hash object with the password and secret, and then we get the hashed password as a string using the hexdigest() method. Finally, we print the original password, secret key, and hashed password for verification.

It's important to note that hashing passwords with a secret key is just one step in a larger process of storing and managing passwords securely. Depending on your specific use case, you may need to take additional steps such as salting the password, using a key derivation function, or storing the hashed passwords securely.

gistlibby LogSnag