Secure Password Hashing For Python

Dec 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_sha256hash = pbkdf2_sha256.hash("mypassword")# output: $pbkdf2-sha256$29000$7x3D2DvnHGOMMWZszfk/pw$SLe.amRGTBhG.v0EtUpD.RvzVBS7EXoUZuGdlmtZJi4

Verify password.

from passlib.hash import pbkdf2_sha256pbkdf2_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 CryptContextpwd_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)

❀️ Is this article helpful?

Buy me a coffee β˜• or support my work via PayPal to keep this space πŸ–– and ad-free.

Do send some πŸ’– to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

πŸ‘Ά Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.