For more complex deployment scenarios than the frontend functions described in Quick Start, the CryptContext class exists...
Helper for encrypting passwords using different algorithms.
Different storage contexts (eg: linux shadow files vs openbsd shadow files) may use different sets and subsets of the available algorithms. This class encapsulates such distinctions: it represents an ordered list of algorithms, each with a unique name. It contains methods to verify against existing algorithms in the context, and still encrypt using new algorithms as they are added.
Because of all of this, it’s basically just a list object. However, it contains some dictionary-like features such as looking up algorithms by name, and it’s restriction that no two algorithms in a list share the same name causes it to act more like an “ordered set” than a list.
In general use, none of this matters. The typical use case is as follows:
>>> from passlib import hash
>>> #create a new context that only understands Md5Crypt & BCrypt
>>> myctx = hash.CryptContext([ hash.Md5Crypt, hash.BCrypt ])
>>> #the last one in the list will be used as the default for encrypting...
>>> hash1 = myctx.encrypt("too many secrets")
>>> hash1
'$2a$11$RvViwGZL./LkWfdGKTrgeO4khL/PDXKe0TayeVObQdoew7TFwhNFy'
>>> #choose algorithm explicitly
>>> hash2 = myctx.encrypt("too many secrets", alg="md5-crypt")
>>> hash2
'$1$E1g0/BY.$gS9XZ4W2Ea.U7jMueBRVA.'
>>> #verification will autodetect the right hash
>>> myctx.verify("too many secrets", hash1)
True
>>> myctx.verify("too many secrets", hash2)
True
>>> myctx.verify("too many socks", hash2)
False
>>> #you can also have it identify the algorithm in use
>>> myctx.identify(hash1)
'bcrypt'
>>> #or just return the CryptAlgorithm instance directly
>>> myctx.identify(hash1, resolve=True)
<passlib.hash.BCrypt object, name="bcrypt">
>>> #you can get a list of algs...
>>> myctx.keys()
[ 'md5-crypt', 'bcrypt' ]
>>> #and get the CryptAlgorithm object by name
>>> bc = myctx['bcrypt']
>>> bc
<passlib.hash.BCrypt object, name="bcrypt">
The following context objects are predefined by BPS:
This context object contains all the algorithms supported by BPS, listed (mostly) in order of strength. identify(), verify(), and encrypt() are all merely wrappers for this object’s methods of the same name.
This context object contains only the algorithms in use on modern linux systems (namely: unix-crypt, md5-crypt, sha512-crypt).
This context object contains only the algorithms in use on modern BSD systems (namely: unix-crypt, md5-crypt, bcrypt).