Search code examples
pythonhashpasswordssalt-cryptographypasslib

Why does this passlib hashing script create a new result every time I run the script?


I'm using the following script from the passlib docs to hash a password:

# import the hash algorithm                                                         
from passlib.hash import sha256_crypt                                               

# generate new salt, and hash a password
hash = sha256_crypt.encrypt("toomanysecrets")
print hash  # <== WHY IS THIS ALWAYS A DIFFERENT STRING?
# verifying the password
print sha256_crypt.verify("toomanysecrets", hash)  # Outputs "True"
print sha256_crypt.verify("joshua", hash)  # Outputs "False"

It seems odd that sha256_crypt.verify would be able to verify multiple different hashes as "toomanysecrets" - why isn't there just one hash for this password?


Solution

  • Hash result depends on the input and salt. Where the salt - it is randomly generated value which is included in the output string together with result of hashing. That is why for each call sha256_crypt.encrypt output string looks random, but password verification ability is preserved.