Python Crypt Module
The crypt module is an interface to the crypt(3) routine, which is a one-way hash function based on a modified DES algorithm; see the Unix man page for further details. Possible uses include storing hashed passwords so you can check passwords without storing the actual password.
Note: The crypt module is deprecated as of Python 3.11 and was removed in Python 3.13. It is recommended to use hashlib for general hashing, or libraries like bcrypt or passlib for password hashing.
Importing the Module
import crypt
Hashing a Password
To hash a password, use the crypt.crypt() function. It takes the password and a "salt".
import crypt
# In standard crypt, the salt is usually a two-character string
# chosen from the set [a-zA-Z0-9./].
hashed = crypt.crypt("password", "HX")
print(hashed)
If the salt is not provided, a random salt is generated (using the strongest method available).
import crypt
hashed = crypt.crypt("password")
print(hashed)
Verifying a Password
To verify a password, you hash the input password using the stored hash as the salt. If the result matches the stored hash, the password is correct.
import crypt
import hmac
def verify_password(stored_hash, input_password):
# crypt() takes the salt from the beginning of the stored hash
return hmac.compare_digest(crypt.crypt(input_password, stored_hash), stored_hash)
# Example usage
password = "secret_password"
stored_hash = crypt.crypt(password)
if verify_password(stored_hash, "secret_password"):
print("Password matches")
else:
print("Password does not match")
Generating Salts
The crypt.mksalt() function generates a salt of the specified method.
import crypt
# Generate a salt using SHA-512
salt = crypt.mksalt(crypt.METHOD_SHA512)
print(salt)