Secure Password Hashing For Python

December 2, 2017
Use Passlib.

Passlib is a password hashing library for Python 2 & 3, which provides cross-platform implementations of over 30 password hashing algorithms, as well as a framework for managing existing password hashes. It’s designed to be useful for a wide range of tasks, from verifying a hash found in /etc/shadow, to providing full-strength password hashing for multi-user applications.

Basically, Passlib implements the best practices of password hashing (salt, recommended algo, rounds, auto hex, etc.) and very simple to use.

Install Passlib.

pip install passlib

Hash password.

from passlib.hash import pbkdf2_sha256

hash = pbkdf2_sha256.hash("mypassword")
# output: $pbkdf2-sha256$29000$7x3D2DvnHGOMMWZszfk/pw$SLe.amRGTBhG.v0EtUpD.RvzVBS7EXoUZuGdlmtZJi4

Verify password.

from passlib.hash import pbkdf2_sha256

pbkdf2_sha256.verify("mypassword", hash)

As for November 2017, 4 hash algos are recommended by Passlib.

  • argon2
  • bcrypt
  • pbkdf2_sha256 / pbkdf2_sha512
  • sha256_crypt / sha512_crypt

Note: argon2 and bcrypt need to install additional packages.

For more advance usage, you can use CryptContext which can support multiple hash algos, especially when you need to support legacy hashes. The following code is copied from Passlib.

from passlib.context import CryptContext
pwd_context = CryptContext(
    # Replace this list with the hash(es) you wish to support.
    # this example sets pbkdf2_sha256 as the default,
    # with additional support for reading legacy des_crypt hashes.
    schemes=["pbkdf2_sha256", "des_crypt"],

    # Automatically mark all but first hasher in list as deprecated.
    # (this will be the default in Passlib 2.0)
    deprecated="auto",
    )

hash = pwd_context.hash("mypassword")
pwd_context.verify("mypassword", hash)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.