How to Secure Passwords in Python with passlib

Recently I needed a secure way to protect a service with a passphrase. I settled on the solution of using passlib verify that password, and learned along the way the important lesson of never trying to roll your own cryptographic code.

With passlib, we can generate hashes for a password, and then verify that password later. Simply create a hash in an interactive session, and then verify user provided passwords in your code using the hash you created interactively. For example, suppose our password is “zanzibar”. We’ll open a terminal and create two hashes

from passlib.hash import sha256_crypt
password = "zanzibar"
hash1 = sha256_crypt.encrypt( password )
hash2 = sha256_crypt.encrypt( password )
print hash1
print hash2

Note that we can use either of these hashes to verify our password later.


Next, in our code we can verify a password in the following manner,

import getpass
from passlib.hash import sha256_crypt
hash = "$5$rounds=110000$9RA0tPppiXaVQvN7$I79L17glplJGgc1.cm2I.NqTBLZbChN.dfFsSSWeNaA"
pass = getpass.getpass("Please enter the secret password: ")
if sha256_crypt.verify( pass, hash ):
    print("Everything worked!")
    print("Try again :(")

This way you can distribute your code and your passwords separately without anyone using grep and/or hexdump to sniff out sensitive information in your code.