passlib.hash.bcrypt - BCrypt¶
BCrypt was developed to replace md5_crypt for BSD systems.
It uses a modified version of the Blowfish stream cipher. Featuring
a large salt and variable number of rounds, it's currently the default
password hash for many systems (notably BSD), and has no known weaknesses.
It is one of the four hashes Passlib recommends for new applications. This class can be used directly as follows:
from passlib.hash import bcrypt
# generate new salt, hash password
h = bcrypt.hash("password")
print(h)
# > '$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy'
# the same, but with an explicit number of rounds
print(bcrypt.using(rounds=13).hash("password"))
# > '$2b$13$HMQTprwhaUwmir.g.ZYoXuRJhtsbra4uj.qJPHrKsX5nGlhpts0jm'
# verify password
print(bcrypt.verify("password", h))
# > True
print(bcrypt.verify("wrong", h))
# > False
Note
It is strongly recommended that you install bcrypt when using this hash.
Tip
the generic PasswordHash usage examples.
Interface¶
bcrypt
¶
bcrypt(ident=None, **kwds)
This class implements the BCrypt password hash, and follows the :ref:password-hash-api.
It supports a fixed-length salt, and a variable number of rounds.
The :meth:~passlib.ifc.PasswordHash.using method accepts the following optional keywords:
Parameters:
-
salt(str) –Optional salt string. If not specified, one will be autogenerated (this is recommended). If specified, it must be 22 characters, drawn from the regexp range
[./0-9A-Za-z]. -
rounds(int) –Optional number of rounds to use. Defaults to 12, must be between 4 and 31, inclusive. This value is logarithmic, the actual number of iterations used will be :samp:
2**{rounds}-- increasing the rounds by +1 will double the amount of time taken. -
ident(str, default:None) –Specifies which version of the BCrypt algorithm will be used when creating a new hash. Typically this option is not needed, as the default (
"2b") is usually the correct choice. If specified, it must be one of the following:"2"- the first revision of BCrypt, which suffers from a minor security flaw and is generally not used anymore."2a"- some implementations suffered from rare security flaws, replaced by 2b."2y"- format specific to the crypt_blowfish BCrypt implementation, identical to"2b"in all but name."2b"- latest revision of the official BCrypt algorithm, current default.
-
truncate_error(bool) –By default, BCrypt will silently truncate passwords larger than 72 bytes. Setting
truncate_error=Truewill cause :meth:~passlib.ifc.PasswordHash.hashto raise a :exc:~passlib.exc.PasswordTruncateErrorinstead... versionadded:: 1.7
-
relaxed(bool) –By default, providing an invalid value for one of the other keywords will result in a :exc:
ValueError. Ifrelaxed=True, and the error can be corrected, a :exc:~passlib.exc.PasslibHashWarningwill be issued instead. Correctable errors includeroundsthat are too small or too large, andsaltstrings that are too long... versionadded:: 1.6.. versionchanged:: 1.6 This class now supports
"2y"hashes, and recognizes (but does not support) the broken"2x"hashes. (see the :ref:crypt_blowfish bug <crypt-blowfish-bug>for details)... versionchanged:: 1.6 Added a pure-python backend.
.. versionchanged:: 1.6.3
Added support for ``"2b"`` variant... versionchanged:: 1.7
Now defaults to ``"2b"`` variant.
encrypt
classmethod
¶
encrypt(*args, **kwds)
Legacy alias for :meth:hash.
.. deprecated:: 1.7
This method was renamed to :meth:!hash in version 1.7.
This alias will be removed in version 2.0, and should only
be used for compatibility with Passlib 1.3 - 1.6.
parsehash
classmethod
¶
parsehash(hash, checksum=True, sanitize=False)
[experimental method] parse hash into dictionary of settings.
this essentially acts as the inverse of :meth:hash: for most
cases, if hash = cls.hash(secret, **opts), then
cls.parsehash(hash) will return a dict matching the original options
(with the extra keyword checksum).
this method may not work correctly for all hashes, and may not be available on some few. its interface may change in future releases, if it's kept around at all.
Parameters:
-
hash–hash to parse
-
checksum–include checksum keyword? (defaults to True)
-
sanitize–mask data for sensitive fields? (defaults to False)
bitsize
classmethod
¶
bitsize(rounds=None, vary_rounds=0.1, **kwds)
[experimental method] return info about bitsizes of hash
default_salt_chars
¶
default_salt_chars()
charset used to generate new salt strings (defaults to salt_chars)
get_backend
classmethod
¶
get_backend()
Return name of currently active backend. if no backend has been loaded, loads and returns name of default backend.
Returns:
-
–
name of active backend
Raises:
-
passlib.exc.MissingBackendError–if no backends are available.
has_backend
classmethod
¶
has_backend(name='any')
Check if support is currently available for specified backend.
Parameters:
-
name–name of backend to check for. can be any string accepted by :meth:
set_backend.
Returns:
-
–
Trueif backend is available.Falseif it's available / can't be loaded.Noneif it's present, but won't load due to a security issue.
Raises:
-
ValueError–if backend name is unknown
set_backend
classmethod
¶
set_backend(name='any', dryrun=False)
Load specified backend.
Parameters:
-
name–name of backend to load, can be any of the following:
-
"any"-- use current backend if one is loaded, otherwise load the first available backend. -
"default"-- use the first available backend. -
any string in :attr:
backends, loads specified backend.
-
-
dryrun–If True, this perform all setup actions except switching over to the new backend. (this flag is used to implement :meth:
has_backend)... versionadded:: 1.7
Raises:
-
ValueError–If backend name is unknown.
-
passlib.exc.MissingBackendError–If specific backend is missing; or in the case of
"any"/"default", if no backends are available. -
passlib.exc.PasslibSecurityError–If
"any"or"default"was specified, but the only backend available has a PasslibSecurityError.
Bcrypt Backends¶
This class will use the first available of five possible backends:
- bcrypt, if installed.
- stdlib's
crypt.crypt(), if the host OS supports BCrypt (primarily BSD-derived systems). - A pure-python implementation of BCrypt, built into Passlib.
If no backends are available, hash() and verify()
will throw MissingBackendError when they are invoked.
You can check which backend is in use by calling bcrypt.get_backend().
As of Passlib 1.6.3, a one-time check is peformed when the backend is first loaded, to detect the backend's capabilities & bugs. If this check detects a fatal bug, a `PasslibSecurityError