To hash passwords in Python, you can use a hashing function from the
hashlib module. Hashing a password is a one-way process that converts the password to a fixed-length sequence of characters, called a digest, that cannot be converted back to the original password.
Here is an example of how to hash a password using SHA-256 algorithm in Python:
import hashlib password = 'my_password' salt = b'salt' # This should be randomly generated for each user # Concatenate the password and salt together password_with_salt = password.encode() + salt # Hash the password with salt using SHA-256 algorithm hash_object = hashlib.sha256(password_with_salt) hex_dig = hash_object.hexdigest() # Print the hexadecimal digest value print(hex_dig)
In this example, we first define a password and a salt value. The salt is a random value that is added to the password to make the hash more secure. We then concatenate the password and salt together.
Next, we create a
hashlib.sha256() object and pass it the concatenated password and salt. We then call the
hexdigest() method to get the hexadecimal digest value of the hash. Finally, we print the hexadecimal digest value to the console.
You can use other hash functions provided by the
hashlib module such as SHA-1, SHA-512, etc. to hash passwords.