Skip to content

passlib.context - CryptContext Hash Manager

This page provides a complete reference of all the methods and options supported by the CryptContext class and helper utilities. The module provides the CryptContext class, for managing multiple password hash schemes.

Tip

context-tutorial -- overview of this class and walkthrough of how to use it.

The CryptContext Class

Helper for hashing passwords using different algorithms.

At its base, this is a proxy object that makes it easy to use multiple PasswordHash objects at the same time. Instances of this class can be created by calling the constructor with the appropriate keywords, or by using one of the alternate constructors, which can load directly from a string or a local file. Since this class has so many options and methods, they have been broken out into subsections:

CryptContext

CryptContext(schemes=None, _autoload=True, **kwds)

Helper for hashing & verifying passwords using multiple algorithms.

Instances of this class allow applications to choose a specific set of hash algorithms which they wish to support, set limits and defaults for the rounds and salt sizes those algorithms should use, flag which algorithms should be deprecated, and automatically handle migrating users to stronger hashes when they log in.

Basic usage::

>>> ctx = CryptContext(schemes=[...])

See the Passlib online documentation for details and full documentation.

context_kwds property

context_kwds

return :class:!set containing union of all :ref:contextual keywords <context-keywords> supported by the handlers in this context.

.. versionadded:: 1.6.6

from_string classmethod

from_string(
    source, section="passlib", encoding="utf-8"
)

create new CryptContext instance from an INI-formatted string.

Parameters:

  • source (str | bytes) –

    string containing INI-formatted content.

  • section (str, default: 'passlib' ) –

    option name of section to read from, defaults to "passlib".

  • encoding (str, default: 'utf-8' ) –

    optional encoding used when source is bytes, defaults to "utf-8".

Returns:

  • –

    new :class:CryptContext instance, configured based on the parameters in the source string.

    Usage example::

    >>> from passlib.context import CryptContext
    >>> context = CryptContext.from_string('''
    ... [passlib]
    ... schemes = sha256_crypt, des_crypt
    ... sha256_crypt__default_rounds = 30000
    ... ''')
    

    .. versionadded:: 1.6

    .. seealso:: :meth:to_string, the inverse of this constructor.

from_path classmethod

from_path(path, section='passlib', encoding='utf-8')

create new CryptContext instance from an INI-formatted file.

this functions exactly the same as :meth:from_string, except that it loads from a local file.

Parameters:

  • path (str) –

    path to local file containing INI-formatted config.

  • section (str, default: 'passlib' ) –

    option name of section to read from, defaults to "passlib".

  • encoding (str, default: 'utf-8' ) –

    encoding used to load file, defaults to "utf-8".

Returns:

  • –

    new CryptContext instance, configured based on the parameters stored in the file path.

    .. versionadded:: 1.6

    .. seealso:: :meth:from_string for an equivalent usage example.

copy

copy(**kwds)

Return copy of existing CryptContext instance.

This function returns a new CryptContext instance whose configuration is exactly the same as the original, with the exception that any keywords passed in will take precedence over the original settings. As an example::

>>> from passlib.context import CryptContext

>>> # given an existing context...
>>> ctx1 = CryptContext(["sha256_crypt", "md5_crypt"])

>>> # copy can be used to make a clone, and update
>>> # some of the settings at the same time...
>>> ctx2 = custom_app_context.copy(default="md5_crypt")

>>> # and the original will be unaffected by the change
>>> ctx1.default_scheme()
"sha256_crypt"
>>> ctx2.default_scheme()
"md5_crypt"

.. versionadded:: 1.6 This method was previously named :meth:!replace. That alias was removed in Passlib 1.8.

.. seealso:: :meth:update

using

using(**kwds)

alias for :meth:copy, to match PasswordHash.using()

load_path

load_path(
    path,
    update=False,
    section="passlib",
    encoding="utf-8",
)

Load new configuration into CryptContext from a local file.

This function is a wrapper for :meth:load which loads a configuration string from the local file path, instead of an in-memory source. Its behavior and options are otherwise identical to :meth:!load when provided with an INI-formatted string.

.. versionadded:: 1.6

load

load(
    source,
    update=False,
    section="passlib",
    encoding="utf-8",
)

Load new configuration into CryptContext, replacing existing config.

Parameters:

  • source –

    source of new configuration to load. this value can be a number of different types:

    • a :class:!dict object, or compatible Mapping

      the key/value pairs will be interpreted the same keywords for the :class:CryptContext class constructor.

    • a :class:!str or :class:!bytes string

      this will be interpreted as an INI-formatted file, and appropriate key/value pairs will be loaded from the specified section.

    • another :class:!CryptContext object.

      this will export a snapshot of its configuration using :meth:to_dict.

  • update (bool, default: False ) –

    By default, :meth:load will replace the existing configuration entirely. If update=True, it will preserve any existing configuration options that are not overridden by the new source, much like the :meth:update method.

  • section (str, default: 'passlib' ) –

    When parsing an INI-formatted string, :meth:load will look for a section named "passlib". This option allows an alternate section name to be used. Ignored when loading from a dictionary.

  • encoding (str, default: 'utf-8' ) –

    Encoding to use when source is bytes. Defaults to "utf-8". Ignored when loading from a dictionary.

    .. deprecated:: 1.8

    This keyword, and support for bytes input, will be dropped in Passlib 2.0
    

Raises:

  • TypeError –
    • If the source cannot be identified.
    • If an unknown / malformed keyword is encountered.
  • ValueError –

    If an invalid keyword value is encountered.

    .. note::

    If an error occurs during a :meth:`!load` call, the :class:`!CryptContext`
    instance will be restored to the configuration it was in before
    the :meth:`!load` call was made; this is to ensure it is
    *never* left in an inconsistent state due to a load error.
    

    .. versionadded:: 1.6

update

update(*args, **kwds)

Helper for quickly changing configuration.

This acts much like the :meth:!dict.update method: it updates the context's configuration, replacing the original value(s) for the specified keys, and preserving the rest. It accepts any :ref:keyword <context-options> accepted by the :class:!CryptContext constructor.

.. versionadded:: 1.6

.. seealso:: :meth:copy

schemes

schemes(
    resolve=False, category=None, unconfigured=False
)

return schemes loaded into this CryptContext instance.

Parameters:

  • resolve (bool, default: False ) –

    if True, will return a tuple of :class:~passlib.ifc.PasswordHash objects instead of their names.

Returns:

  • –

    returns tuple of the schemes configured for this context via the schemes option.

    .. versionadded:: 1.6 This was previously available as CryptContext().policy.schemes()

    .. seealso:: the :ref:schemes <context-schemes-option> option for usage example.

default_scheme

default_scheme(
    category=None, resolve=False, unconfigured=False
)

return name of scheme that :meth:hash will use by default.

Parameters:

  • resolve (bool, default: False ) –

    if True, will return a :class:~passlib.ifc.PasswordHash object instead of the name.

  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will return the catgory-specific default scheme instead.

Returns:

  • –

    name of the default scheme.

    .. seealso:: the :ref:default <context-default-option> option for usage example.

    .. versionadded:: 1.6

    .. versionchanged:: 1.7

    This now returns a hasher configured with any CryptContext-specific
    options (custom rounds settings, etc).  Previously this returned
    the base hasher from :mod:`passlib.hash`.
    

handler

handler(
    scheme=None, category=None, unconfigured=False
)

helper to resolve name of scheme -> :class:~passlib.ifc.PasswordHash object used by scheme.

Parameters:

  • scheme –

    This should identify the scheme to lookup. If omitted or set to None, this will return the handler for the default scheme.

  • category –

    If a user category is specified, and no scheme is provided, it will use the default for that category. Otherwise this parameter is ignored.

  • unconfigured –

    By default, this returns a handler object whose .hash() and .needs_update() methods will honor the configured provided by CryptContext. See unconfigured=True to get the underlying handler from before any context-specific configuration was applied.

Returns:

  • –

    :class:~passlib.ifc.PasswordHash object used to implement the named scheme within this context (this will usually be one of the objects from :mod:passlib.hash)

    .. versionadded:: 1.6 This was previously available as CryptContext().policy.get_handler()

    .. versionchanged:: 1.7

    This now returns a hasher configured with any CryptContext-specific
    options (custom rounds settings, etc).  Previously this returned
    the base hasher from :mod:`passlib.hash`.
    

Raises:

  • KeyError –

    If the scheme does not exist OR is not being used within this context.

to_dict

to_dict(resolve=False)

Return current configuration as a dictionary.

Parameters:

  • resolve (bool, default: False ) –

    if True, the schemes key will contain a list of a :class:~passlib.ifc.PasswordHash objects instead of just their names.

    This method dumps the current configuration of the CryptContext instance. The key/value pairs should be in the format accepted by the :class:!CryptContext class constructor, in fact CryptContext(**myctx.to_dict()) will create an exact copy of myctx. As an example::

    >>> # you can dump the configuration of any crypt context...
    >>> from passlib.apps import ldap_nocrypt_context
    >>> ldap_nocrypt_context.to_dict()
    {'schemes': ['ldap_salted_sha1',
    'ldap_salted_md5',
    'ldap_sha1',
    'ldap_md5',
    'ldap_plaintext']}
    

    .. versionadded:: 1.6 This was previously available as CryptContext().policy.to_dict()

    .. seealso:: the :ref:context-serialization-example example in the tutorial.

to_string

to_string(section='passlib') -> str

serialize to INI format and return as unicode string.

:meth:from_path, and :meth:load. As an example::

>>> # you can dump the configuration of any crypt context...
>>> from passlib.apps import ldap_nocrypt_context
>>> print ldap_nocrypt_context.to_string()
[passlib]
schemes = ldap_salted_sha1, ldap_salted_md5, ldap_sha1, ldap_md5, ldap_plaintext

.. versionadded:: 1.6 This was previously available as CryptContext().policy.to_string()

.. seealso:: the :ref:context-serialization-example example in the tutorial.

Parameters:

  • section –

    name of INI section to output, defaults to "passlib".

Returns:

  • str –

    CryptContext configuration, serialized to a INI unicode string.

    This function acts exactly like :meth:to_dict, except that it serializes all the contents into a single human-readable string, which can be hand edited, and/or stored in a file. The output of this method is accepted by :meth:from_string,

needs_update

needs_update(
    hash, scheme=None, category=None, secret=None
)

Check if hash needs to be replaced for some reason, in which case the secret should be re-hashed.

This function is the core of CryptContext's support for hash migration: This function takes in a hash string, and checks the scheme, number of rounds, and other properties against the current policy. It returns True if the hash is using a deprecated scheme, or is otherwise outside of the bounds specified by the policy (e.g. the number of rounds is lower than :ref:min_rounds <context-min-rounds-option> configuration for that algorithm). If so, the password should be re-hashed using :meth:hash Otherwise, it will return False.

Parameters:

  • hash (str | bytes) –

    The hash string to examine.

  • scheme (str | None, default: None ) –

    Optional scheme to use. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option). If no scheme is specified, it will be identified based on the value of hash.

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will cause any category-specific defaults to be used when determining if the hash needs to be updated (e.g. is below the minimum rounds).

  • secret (str, bytes, | None, default: None ) –

    Optional secret associated with the provided hash. This is not required, or even currently used for anything... it's for forward-compatibility with any future update checks that might need this information. If provided, Passlib assumes the secret has already been verified successfully against the hash.

    .. versionadded:: 1.6

Returns:

  • –

    True if hash should be replaced, otherwise False.

Raises:

  • ValueError –

    If the hash did not match any of the configured :meth:schemes.

    .. versionadded:: 1.6 This method was previously named :meth:hash_needs_update.

    .. seealso:: the :ref:context-migration-example example in the tutorial.

hash_needs_update

hash_needs_update(hash, scheme=None, category=None)

Legacy alias for :meth:needs_update.

.. deprecated:: 1.6 This method was renamed to :meth:!needs_update in version 1.6. This alias will be removed in version 2.0, and should only be used for compatibility with Passlib 1.3 - 1.5.

genconfig

genconfig(scheme=None, category=None, **settings)

Generate a config string for specified scheme.

.. deprecated:: 1.7

This method will be removed in version 2.0, and should only
be used for compatibility with Passlib 1.3 - 1.6.

genhash

genhash(
    secret, config, scheme=None, category=None, **kwds
)

Generate hash for the specified secret using another hash.

.. deprecated:: 1.7

This method will be removed in version 2.0, and should only
be used for compatibility with Passlib 1.3 - 1.6.

identify

identify(
    hash,
    category=None,
    resolve=False,
    required=False,
    unconfigured=False,
)

Attempt to identify which algorithm the hash belongs to.

Note that this will only consider the algorithms currently configured for this context (see the :ref:schemes <context-schemes-option> option). All registered algorithms will be checked, from first to last, and whichever one positively identifies the hash first will be returned.

Parameters:

  • hash (str | bytes) –

    The hash string to test.

  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. Ignored by this function, this parameter is provided for symmetry with the other methods.

  • resolve (bool, default: False ) –

    If True, returns the hash handler itself, instead of the name of the hash.

  • required (bool, default: False ) –

    If True, this will raise a ValueError if the hash cannot be identified, instead of returning None.

Returns:

  • –

    The handler which first identifies the hash, or None if none of the algorithms identify the hash.

hash

hash(secret, scheme=None, category=None, **kwds)

run secret through selected algorithm, returning resulting hash.

Parameters:

  • secret (str | bytes) –

    the password to hash.

  • scheme (str | None, default: None ) –

    Optional scheme to use. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option). If no scheme is specified, the configured default will be used.

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will cause any category-specific defaults to be used when hashing the password (e.g. different default scheme, different default rounds values, etc).

  • \*\*kwds –

    All other keyword options are passed to the selected algorithm's :meth:PasswordHash.hash() <passlib.ifc.PasswordHash.hash> method.

Returns:

  • –

    The secret as encoded by the specified algorithm and options. The return value will always be a :class:!str.

encrypt

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.

verify

verify(
    secret, hash, scheme=None, category=None, **kwds
)

verify secret against an existing hash.

If no scheme is specified, this will attempt to identify the scheme based on the contents of the provided hash (limited to the schemes configured for this context). It will then check whether the password verifies against the hash.

Parameters:

  • secret (str | bytes) –

    the secret to verify

  • hash (str | bytes) –

    hash string to compare to

    if None is passed in, this will be treated as "never verifying"

  • scheme (str, default: None ) –

    Optionally force context to use specific scheme. This is usually not needed, as most hashes can be unambiguously identified. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option).

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories> string. This is mainly used when generating new hashes, it has little effect when verifying; this keyword is mainly provided for symmetry.

  • \*\*kwds –

    All additional keywords are passed to the appropriate handler, and should match its :attr:~passlib.ifc.PasswordHash.context_kwds.

Returns:

  • –

    True if the password matched the hash, else False.

Raises:

  • ValueError –
    • if the hash did not match any of the configured :meth:schemes.

    • if any of the arguments have an invalid value (this includes any keywords passed to the underlying hash's :meth:PasswordHash.verify() <passlib.ifc.PasswordHash.verify> method).

  • TypeError –
    • if any of the arguments have an invalid type (this includes any keywords passed to the underlying hash's :meth:PasswordHash.verify() <passlib.ifc.PasswordHash.verify> method).

    .. seealso:: the :ref:context-basic-example example in the tutorial

verify_and_update

verify_and_update(
    secret, hash, scheme=None, category=None, **kwds
)

verify password and re-hash the password if needed, all in a single call.

This is a convenience method which takes care of all the following: first it verifies the password (:meth:~CryptContext.verify), if this is successfull it checks if the hash needs updating (:meth:~CryptContext.needs_update), and if so, re-hashes the password (:meth:~CryptContext.hash), returning the replacement hash. This series of steps is a very common task for applications which wish to update deprecated hashes, and this call takes care of all 3 steps efficiently.

Parameters:

  • secret (str | bytes) –

    the secret to verify

  • hash –

    hash string to compare to.

    if None is passed in, this will be treated as "never verifying"

  • scheme (str, default: None ) –

    Optionally force context to use specific scheme. This is usually not needed, as most hashes can be unambiguously identified. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option).

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will cause any category-specific defaults to be used if the password has to be re-hashed.

  • \*\*kwds –

    all additional keywords are passed to the appropriate handler, and should match that hash's :attr:PasswordHash.context_kwds <passlib.ifc.PasswordHash.context_kwds>.

Returns:

  • –

    This function returns a tuple containing two elements: (verified, replacement_hash). The first is a boolean flag indicating whether the password verified, and the second an optional replacement hash. The tuple will always match one of the following 3 cases:

    • (False, None) indicates the secret failed to verify.
    • (True, None) indicates the secret verified correctly, and the hash does not need updating.
    • (True, str) indicates the secret verified correctly, but the current hash needs to be updated. The :class:!str will be the freshly generated hash, to replace the old one.

dummy_verify

dummy_verify()

Helper that applications can call when user wasn't found, in order to simulate time it would take to hash a password.

Runs verify() against a dummy hash, to simulate verification of a real account password.

.. versionadded:: 1.7

is_enabled

is_enabled(hash)

test if hash represents a usuable password -- i.e. does not represent an unusuable password such as "!", which is recognized by the :class:~passlib.hash.unix_disabled hash.

Raises:

  • ValueError –

    if the hash is not recognized (typically solved by adding unix_disabled to the list of schemes).

disable

disable(hash=None)

return a string to disable logins for user, usually by returning a non-verifying string such as "!".

Parameters:

  • hash –

    Callers can optionally provide the account's existing hash. Some disabled handlers (such as :class:!unix_disabled) will encode this into the returned value, so that it can be recovered via :meth:enable.

Returns:

  • –

    hash string which will be recognized as valid by the context, but is guaranteed to not validate against any password.

Raises:

  • RuntimeError –

    if this function is called w/o a disabled hasher (such as :class:~passlib.hash.unix_disabled) included in the list of schemes.

enable

enable(hash)

inverse of :meth:disable -- attempts to recover original hash which was converted by a :meth:!disable call into a disabled hash -- thus restoring the user's original password.

Returns:

  • –

    the original hash.

Raises:

  • ValueError –

    if original hash not present, or if the disabled handler doesn't support encoding the original hash (e.g. django_disabled)

Constructor Keywords

The CryptContext class accepts the following keywords, all of which are optional. The keywords are divided into two categories: context options, which affect the CryptContext itself; and algorithm options, which place defaults and limits on the algorithms used by the CryptContext.

Context Options

Options which directly affect the behavior of the CryptContext instance:

schemes

List of algorithms which the instance should support.

The most important option in the constructor, it controls what hashes can be used by the hash() method, which will be recognized by verify() and identify(), and other effects throughout the instance. It should be a sequence of names, drawn from the hashes in passlib.hash. Listing an unknown name will cause a ValueError. You can use the schemes() method to get a list of the currently configured algorithms. As an example, the following creates a CryptContext instance which supports the sha256_crypt and des_crypt schemes:

from passlib.context import CryptContext

myctx = CryptContext(schemes=["sha256_crypt", "des_crypt"])
print(myctx.schemes())
# > ("sha256_crypt", "des_crypt")

Note

The order of the schemes is sometimes important, as identify() will run through the schemes from first to last until an algorithm "claims" the hash. So plaintext algorithms and the like should be listed at the end.

Tip

See the context-basic-example example in the tutorial.

default

Specifies the name of the default scheme.

This option controls which of the configured schemes will be used as the default when creating new hashes. This parameter is optional; if omitted, the first non-deprecated algorithm in schemes will be used. You can use the default_scheme() method to retrieve the name of the current default scheme. As an example, the following demonstrates the effect of this parameter on the hash() method:

from passlib.context import CryptContext

myctx = CryptContext(schemes=["sha256_crypt", "md5_crypt"])

# hash() uses the first scheme
print(myctx.default_scheme())
# > 'sha256_crypt'
hashed = myctx.hash("password")
print(hashed)
# > '$5$rounds=80000$R5ZIZRTNPgbdcWq5$fT/Oeqq/apMa/0fbx8YheYWS6Z3XLTxCzEtutsk2cJ1'

# but setting default causes the second scheme to be used.
myctx.update(default="md5_crypt")
print(myctx.default_scheme())
# > 'md5_crypt'
hashed = myctx.hash("password")
print(hashed)
# > '$1$Rr0C.KI8$Kvciy8pqfL9BQ2CJzEzfZ/'

Tip

See the context-basic-example example in the tutorial.

deprecated

List of algorithms which should be considered "deprecated".

This has the same format as schemes, and should be a subset of those algorithms. The main purpose of this method is to flag schemes which need to be rehashed when the user next logs in. This has no effect on the Primary Methods; but if the special Hash Migration methods are passed a hash belonging to a deprecated scheme, they will flag it as needed to be rehashed using the default scheme.

This may also contain a single special value, ["auto"], which will configure the CryptContext instance to deprecate all supported schemes except for the default scheme.

Tip

See the context-migration-example in the tutorial

truncate_error

By default, some algorithms will truncate large passwords (e.g. bcrypt truncates ones larger than 72 bytes). Such hashes accept a truncate_error=True option to make them raise a PasswordTruncateError instead.

This can also be set at the CryptContext level, and will passed to all hashes that support it.

Algorithm Options

All of the other options that can be passed to a CryptContext constructor affect individual hash algorithms. All of the following keys have the form {scheme}__{key}, where {scheme} is the name of one of the algorithms listed in schemes, and {option} one of the parameters below:

{scheme}__rounds

Set the number of rounds required for this scheme when generating new hashes (using hash()). Existing hashes which have a different number of rounds will be marked as deprecated.

This essentially sets default_rounds, min_rounds, and max_rounds all at once. If any of those options are also specified, they will override the value specified by rounds.

{scheme}__default_rounds

Sets the default number of rounds to use with this scheme when generating new hashes (using hash()).

If not set, this will fall back to the an algorithm-specific PasswordHash.default_rounds. For hashes which do not support a rounds parameter, this option is ignored. As an example:

from passlib.context import CryptContext

# no explicit default_rounds set, so hash() uses sha256_crypt's default (80000)
context = CryptContext(["sha256_crypt"])
hashed = context.hash("fooey")
print(hashed)
# > '$5$rounds=80000$60Y7mpmAhUv6RDvj$AdseAOq6bKUZRDRTr/2QK1t38qm3P6sYeXhXKnBAmg0'
#            ^^^^^

# but if a default is specified, it will be used instead.
context = CryptContext(["sha256_crypt"], sha256_crypt__default_rounds=77123)
hashed = context.hash("fooey")
print(hashed)
# > '$5$rounds=77123$60Y7mpmAhUv6RDvj$AdseAOq6bKUZRDRTr/2QK1t38qm3P6sYeXhXKnBAmg0'
#            ^^^^^

Tip

See the context-default-settings-example example in the tutorial.

{scheme}__vary_rounds

Warning

Changed in 1.7: This option has been deprecated as of Passlib 1.7, and will be removed in Passlib 2.0. The (very minimal) security benefit it provides was judged to not be worth code complexity it requires.

Instead of using a fixed rounds value (such as specified by default_rounds, above). This option will cause each call to hash() to vary the default rounds value by some amount.

This can be an integer value, in which case each call will use a rounds value within the range default_rounds +/- vary_rounds. It may also be a floating point value within the range 0.0 .. 1.0, in which case the range will be calculated as a proportion of the current default rounds (default_rounds +/- default_rounds*vary_rounds). A typical setting is 0.1 to 0.2.

As an example of how this parameter operates:

# without vary_rounds set, hash() uses the same amount each time:
from passlib.context import CryptContext

context = CryptContext(schemes=["sha256_crypt"], sha256_crypt__default_rounds=80000)
hashed = context.hash("fooey")
print(hashed)
# > '$5$rounds=80000$60Y7mpmAhUv6RDvj$AdseAOq6bKUZRDRTr/2QK1t38qm3P6sYeXhXKnBAmg0'
hashed = context.hash("fooey")
print(hashed)
# > '$5$rounds=80000$60Y7mpmAhUv6RDvj$AdseAOq6bKUZRDRTr/2QK1t38qm3P6sYeXhXKnBAmg0'
#            ^^^^^

# but if vary_rounds is set, each one will be randomized
# (in this case, within the range 72000 - 88000)
context = CryptContext(
    schemes=["sha256_crypt"],
    sha256_crypt__default_rounds=80000,
    sha256_crypt__vary_rounds=0.1,
)
hashed = context.hash("fooey")
print(hashed)
# > '$5$rounds=83966$bMpgQxN2hXo2kVr4$jL4Q3ov41UPgSbO7jYL0PdtsOg5koo4mCa.UEF3zan.'
hashed = context.hash("fooey")
print(hashed)
# > '$5$rounds=72109$43BBHC/hYPHzL69c$VYvVIdKn3Zdnvu0oJHVlo6rr0WjiMTGmlrZrrH.GxnA'
#           ^^^^^

Note

This is not a needed security measure, but it lets some of the less-significant digits of the rounds value act as extra salt bits; and helps foil any attacks targeted at a specific number of rounds of a hash.

{scheme}__min_rounds, {scheme}__max_rounds

These options place a limit on the number of rounds allowed for a particular scheme.

For one, they limit what values are allowed for default_rounds, and clip the effective range of the vary_rounds parameter. More importantly though, they proscribe a minimum strength for the hash, and any hashes which don't have sufficient rounds will be flagged as needing rehashing by the Hash Migration methods.

Note

These are configurable per-context limits. A warning will be issued if they exceed any hard limits set by the algorithm itself.

Tip

See the context-min-rounds-example example in the tutorial.

{scheme}__{other-option}

Finally, any other options are assumed to correspond to one of that algorithm's hash() settings, such as setting a salt_size.

Tip

See the context-default-settings-example example in the tutorial.

Global Algorithm Options

all__{option}

The special scheme all permits you to set an option, and have it act as a global default for all the algorithms in the context. For instance, all__vary_rounds=0.1 would set the vary_rounds option for all the schemes where it was not overridden with an explicit {scheme}__vary_rounds option.

Warning

Changed in 1.7: This special scheme is deprecated as of Passlib 1.7, and will be removed in Passlib 2.0. It's only legitimate use was for vary_rounds, which is also being removed in Passlib 2.0.

User Categories

{category}context}, {category{scheme}

Passing keys with this format to the CryptContext constructor allows you to specify conditional context and algorithm options, controlled by the category parameter supported by most CryptContext methods.

These options are conditional because they only take effect if the {category} prefix of the option matches the value of the category parameter of the CryptContext method being invoked. In that case, they override any options specified without a category prefix (e.g. admin__sha256_crypt__min_rounds would override sha256_crypt__min_rounds). The category prefix and the value passed into the category parameter can be any string the application wishes to use, the only constraint is that None indicates the default category.

Motivation: Policy limits such as default rounds values and deprecated schemes generally have to be set globally. However, it's frequently desirable to specify stronger options for certain accounts (such as admin accounts), choosing to sacrifice longer hashing time for a more secure password. The user categories system allows for this. For example, a CryptContext could be set up as follows:

# A context object can be set up as follows:
from passlib.context import CryptContext

context = CryptContext(
    schemes=["sha256_crypt"],
    sha256_crypt__default_rounds=77000,
    staff__sha256_crypt__default_rounds=88000,
)

# In this case, calling hash() with ``category=None`` would result
# in a hash that used 77000 sha256-crypt rounds:
hashed = context.hash("password", category=None)
print(hashed)
# > '$5$rounds=77000$sj3XI0AbKlEydAKt$BhFvyh4.IoxaUeNlW6rvQ.O0w8BtgLQMYorkCOMzf84'
#            ^^^^^

# But if the application passed in ``category="staff"`` when an administrative
# account set their password, 88000 rounds would be used:
hashed = context.hash("password", category="staff")
print(hashed)
# > '$5$rounds=88000$w7XIdKfTI9.YLwmA$MIzGvs6NU1QOQuuDHhICLmDsdW/t94Bbdfxdh/6NJl7'
#            ^^^^^

Primary Methods

The main interface to the CryptContext object deliberately mirrors the PasswordHash interface, since its central purpose is to act as a container for multiple password hashes. Most applications will only need to make use of a handful of methods in a CryptContext instance: hash(), encrypt(), verify(), identify(), and dummy_verify().

These are all covered by the CryptContext reference above.

"crypt"-style methods

Additionally, the main interface offers wrappers for the two Unix "crypt" style methods provided by all the PasswordHash objects: genhash() and genconfig().

Hash Migration

Applications which want to detect and regenerate deprecated hashes will want to use one of the following methods: verify_and_update(), needs_update(), and hash_needs_update().

Disabled Hash Management

Warning

Changed in 1.7: Added.

It's frequently useful to disable a user's ability to login by replacing their password hash with a standin that's guaranteed to never verify, against any password. CryptContext offers some convenience methods for this through the following API: disable(), enable(), and is_enabled().

Alternate Constructors

In addition to the main class constructor, which accepts a configuration as a set of keywords, there are the following alternate constructors: from_string(), from_path(), and copy().

Changing the Configuration

CryptContext objects can have their configuration replaced or updated on the fly, and from a variety of sources (keywords, strings, files). This is done through three methods: update(**kwds), load(), and load_path().

Examining the Configuration

The CryptContext object also supports basic inspection of its current configuration: schemes(), default_scheme(), handler(), and context_kwds.

Saving the Configuration

More detailed inspection can be done by exporting the configuration using one of the serialization methods: to_dict() and to_string().

Configuration Errors

The following errors may be raised when creating a CryptContext instance via any of its constructors, or when updating the configuration of an existing instance:

ValueError:

  • If a configuration option contains an invalid value (e.g. all__vary_rounds=-1).
  • If the configuration contains valid but incompatible options (e.g. listing a scheme as both default and deprecated).

KeyError:

  • If the configuration contains an unknown or forbidden option (e.g. {scheme}__salt).
  • If the schemes, default, or deprecated options reference an unknown hash scheme (e.g. schemes=['xxx'])

TypeError:

  • If a configuration value has the wrong type (e.g. schemes=123).

Note that this error shouldn't occur when loading configurations from a file/string (e.g. using from_string()).

Additionally, a PasslibConfigWarning may be issued if any invalid-but-correctable values are encountered (e.g. if sha256_crypt__min_rounds is set to less than sha256_crypt's minimum of 1000).

Warning

Changed in 1.6: Previous releases used Python's builtin UserWarning instead of the more specific PasslibConfigWarning.

Other Helpers

LazyCryptContext

LazyCryptContext(schemes=None, **kwds)

CryptContext subclass which doesn't load handlers until needed.

This is a subclass of CryptContext which takes in a set of arguments exactly like CryptContext, but won't import any handlers (or even parse its arguments) until the first time one of its methods is accessed.

Parameters:

  • schemes –

    The first positional argument can be a list of schemes, or omitted, just like CryptContext.

  • onload –

    If a callable is passed in via this keyword, it will be invoked at lazy-load time with the following signature: onload(**kwds) -> kwds; where kwds is all the additional kwds passed to LazyCryptContext. It should perform any additional deferred initialization, and return the final dict of options to be passed to CryptContext.

    .. versionadded:: 1.6

  • kwds –

    All additional keywords are passed to CryptContext; or to the onload function (if provided).

    This is mainly used internally by modules such as :mod:passlib.apps, which define a large number of contexts, but only a few of them will be needed at any one time. Use of this class saves the memory needed to import the specified handlers until the context instance is actually accessed. As well, it allows constructing a context at module-init time, but using :func:!onload() to provide dynamic configuration at application-run time.

    .. note:: This class is only useful if you're referencing handler objects by name, and don't want them imported until runtime. If you want to have the config validated before your application runs, or are passing in already-imported handler instances, you should use :class:CryptContext instead.

    .. versionadded:: 1.4

context_kwds property

context_kwds

return :class:!set containing union of all :ref:contextual keywords <context-keywords> supported by the handlers in this context.

.. versionadded:: 1.6.6

from_string classmethod

from_string(
    source, section="passlib", encoding="utf-8"
)

create new CryptContext instance from an INI-formatted string.

Parameters:

  • source (str | bytes) –

    string containing INI-formatted content.

  • section (str, default: 'passlib' ) –

    option name of section to read from, defaults to "passlib".

  • encoding (str, default: 'utf-8' ) –

    optional encoding used when source is bytes, defaults to "utf-8".

Returns:

  • –

    new :class:CryptContext instance, configured based on the parameters in the source string.

    Usage example::

    >>> from passlib.context import CryptContext
    >>> context = CryptContext.from_string('''
    ... [passlib]
    ... schemes = sha256_crypt, des_crypt
    ... sha256_crypt__default_rounds = 30000
    ... ''')
    

    .. versionadded:: 1.6

    .. seealso:: :meth:to_string, the inverse of this constructor.

from_path classmethod

from_path(path, section='passlib', encoding='utf-8')

create new CryptContext instance from an INI-formatted file.

this functions exactly the same as :meth:from_string, except that it loads from a local file.

Parameters:

  • path (str) –

    path to local file containing INI-formatted config.

  • section (str, default: 'passlib' ) –

    option name of section to read from, defaults to "passlib".

  • encoding (str, default: 'utf-8' ) –

    encoding used to load file, defaults to "utf-8".

Returns:

  • –

    new CryptContext instance, configured based on the parameters stored in the file path.

    .. versionadded:: 1.6

    .. seealso:: :meth:from_string for an equivalent usage example.

copy

copy(**kwds)

Return copy of existing CryptContext instance.

This function returns a new CryptContext instance whose configuration is exactly the same as the original, with the exception that any keywords passed in will take precedence over the original settings. As an example::

>>> from passlib.context import CryptContext

>>> # given an existing context...
>>> ctx1 = CryptContext(["sha256_crypt", "md5_crypt"])

>>> # copy can be used to make a clone, and update
>>> # some of the settings at the same time...
>>> ctx2 = custom_app_context.copy(default="md5_crypt")

>>> # and the original will be unaffected by the change
>>> ctx1.default_scheme()
"sha256_crypt"
>>> ctx2.default_scheme()
"md5_crypt"

.. versionadded:: 1.6 This method was previously named :meth:!replace. That alias was removed in Passlib 1.8.

.. seealso:: :meth:update

using

using(**kwds)

alias for :meth:copy, to match PasswordHash.using()

load_path

load_path(
    path,
    update=False,
    section="passlib",
    encoding="utf-8",
)

Load new configuration into CryptContext from a local file.

This function is a wrapper for :meth:load which loads a configuration string from the local file path, instead of an in-memory source. Its behavior and options are otherwise identical to :meth:!load when provided with an INI-formatted string.

.. versionadded:: 1.6

load

load(
    source,
    update=False,
    section="passlib",
    encoding="utf-8",
)

Load new configuration into CryptContext, replacing existing config.

Parameters:

  • source –

    source of new configuration to load. this value can be a number of different types:

    • a :class:!dict object, or compatible Mapping

      the key/value pairs will be interpreted the same keywords for the :class:CryptContext class constructor.

    • a :class:!str or :class:!bytes string

      this will be interpreted as an INI-formatted file, and appropriate key/value pairs will be loaded from the specified section.

    • another :class:!CryptContext object.

      this will export a snapshot of its configuration using :meth:to_dict.

  • update (bool, default: False ) –

    By default, :meth:load will replace the existing configuration entirely. If update=True, it will preserve any existing configuration options that are not overridden by the new source, much like the :meth:update method.

  • section (str, default: 'passlib' ) –

    When parsing an INI-formatted string, :meth:load will look for a section named "passlib". This option allows an alternate section name to be used. Ignored when loading from a dictionary.

  • encoding (str, default: 'utf-8' ) –

    Encoding to use when source is bytes. Defaults to "utf-8". Ignored when loading from a dictionary.

    .. deprecated:: 1.8

    This keyword, and support for bytes input, will be dropped in Passlib 2.0
    

Raises:

  • TypeError –
    • If the source cannot be identified.
    • If an unknown / malformed keyword is encountered.
  • ValueError –

    If an invalid keyword value is encountered.

    .. note::

    If an error occurs during a :meth:`!load` call, the :class:`!CryptContext`
    instance will be restored to the configuration it was in before
    the :meth:`!load` call was made; this is to ensure it is
    *never* left in an inconsistent state due to a load error.
    

    .. versionadded:: 1.6

update

update(*args, **kwds)

Helper for quickly changing configuration.

This acts much like the :meth:!dict.update method: it updates the context's configuration, replacing the original value(s) for the specified keys, and preserving the rest. It accepts any :ref:keyword <context-options> accepted by the :class:!CryptContext constructor.

.. versionadded:: 1.6

.. seealso:: :meth:copy

schemes

schemes(
    resolve=False, category=None, unconfigured=False
)

return schemes loaded into this CryptContext instance.

Parameters:

  • resolve (bool, default: False ) –

    if True, will return a tuple of :class:~passlib.ifc.PasswordHash objects instead of their names.

Returns:

  • –

    returns tuple of the schemes configured for this context via the schemes option.

    .. versionadded:: 1.6 This was previously available as CryptContext().policy.schemes()

    .. seealso:: the :ref:schemes <context-schemes-option> option for usage example.

default_scheme

default_scheme(
    category=None, resolve=False, unconfigured=False
)

return name of scheme that :meth:hash will use by default.

Parameters:

  • resolve (bool, default: False ) –

    if True, will return a :class:~passlib.ifc.PasswordHash object instead of the name.

  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will return the catgory-specific default scheme instead.

Returns:

  • –

    name of the default scheme.

    .. seealso:: the :ref:default <context-default-option> option for usage example.

    .. versionadded:: 1.6

    .. versionchanged:: 1.7

    This now returns a hasher configured with any CryptContext-specific
    options (custom rounds settings, etc).  Previously this returned
    the base hasher from :mod:`passlib.hash`.
    

handler

handler(
    scheme=None, category=None, unconfigured=False
)

helper to resolve name of scheme -> :class:~passlib.ifc.PasswordHash object used by scheme.

Parameters:

  • scheme –

    This should identify the scheme to lookup. If omitted or set to None, this will return the handler for the default scheme.

  • category –

    If a user category is specified, and no scheme is provided, it will use the default for that category. Otherwise this parameter is ignored.

  • unconfigured –

    By default, this returns a handler object whose .hash() and .needs_update() methods will honor the configured provided by CryptContext. See unconfigured=True to get the underlying handler from before any context-specific configuration was applied.

Returns:

  • –

    :class:~passlib.ifc.PasswordHash object used to implement the named scheme within this context (this will usually be one of the objects from :mod:passlib.hash)

    .. versionadded:: 1.6 This was previously available as CryptContext().policy.get_handler()

    .. versionchanged:: 1.7

    This now returns a hasher configured with any CryptContext-specific
    options (custom rounds settings, etc).  Previously this returned
    the base hasher from :mod:`passlib.hash`.
    

Raises:

  • KeyError –

    If the scheme does not exist OR is not being used within this context.

to_dict

to_dict(resolve=False)

Return current configuration as a dictionary.

Parameters:

  • resolve (bool, default: False ) –

    if True, the schemes key will contain a list of a :class:~passlib.ifc.PasswordHash objects instead of just their names.

    This method dumps the current configuration of the CryptContext instance. The key/value pairs should be in the format accepted by the :class:!CryptContext class constructor, in fact CryptContext(**myctx.to_dict()) will create an exact copy of myctx. As an example::

    >>> # you can dump the configuration of any crypt context...
    >>> from passlib.apps import ldap_nocrypt_context
    >>> ldap_nocrypt_context.to_dict()
    {'schemes': ['ldap_salted_sha1',
    'ldap_salted_md5',
    'ldap_sha1',
    'ldap_md5',
    'ldap_plaintext']}
    

    .. versionadded:: 1.6 This was previously available as CryptContext().policy.to_dict()

    .. seealso:: the :ref:context-serialization-example example in the tutorial.

to_string

to_string(section='passlib') -> str

serialize to INI format and return as unicode string.

:meth:from_path, and :meth:load. As an example::

>>> # you can dump the configuration of any crypt context...
>>> from passlib.apps import ldap_nocrypt_context
>>> print ldap_nocrypt_context.to_string()
[passlib]
schemes = ldap_salted_sha1, ldap_salted_md5, ldap_sha1, ldap_md5, ldap_plaintext

.. versionadded:: 1.6 This was previously available as CryptContext().policy.to_string()

.. seealso:: the :ref:context-serialization-example example in the tutorial.

Parameters:

  • section –

    name of INI section to output, defaults to "passlib".

Returns:

  • str –

    CryptContext configuration, serialized to a INI unicode string.

    This function acts exactly like :meth:to_dict, except that it serializes all the contents into a single human-readable string, which can be hand edited, and/or stored in a file. The output of this method is accepted by :meth:from_string,

needs_update

needs_update(
    hash, scheme=None, category=None, secret=None
)

Check if hash needs to be replaced for some reason, in which case the secret should be re-hashed.

This function is the core of CryptContext's support for hash migration: This function takes in a hash string, and checks the scheme, number of rounds, and other properties against the current policy. It returns True if the hash is using a deprecated scheme, or is otherwise outside of the bounds specified by the policy (e.g. the number of rounds is lower than :ref:min_rounds <context-min-rounds-option> configuration for that algorithm). If so, the password should be re-hashed using :meth:hash Otherwise, it will return False.

Parameters:

  • hash (str | bytes) –

    The hash string to examine.

  • scheme (str | None, default: None ) –

    Optional scheme to use. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option). If no scheme is specified, it will be identified based on the value of hash.

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will cause any category-specific defaults to be used when determining if the hash needs to be updated (e.g. is below the minimum rounds).

  • secret (str, bytes, | None, default: None ) –

    Optional secret associated with the provided hash. This is not required, or even currently used for anything... it's for forward-compatibility with any future update checks that might need this information. If provided, Passlib assumes the secret has already been verified successfully against the hash.

    .. versionadded:: 1.6

Returns:

  • –

    True if hash should be replaced, otherwise False.

Raises:

  • ValueError –

    If the hash did not match any of the configured :meth:schemes.

    .. versionadded:: 1.6 This method was previously named :meth:hash_needs_update.

    .. seealso:: the :ref:context-migration-example example in the tutorial.

hash_needs_update

hash_needs_update(hash, scheme=None, category=None)

Legacy alias for :meth:needs_update.

.. deprecated:: 1.6 This method was renamed to :meth:!needs_update in version 1.6. This alias will be removed in version 2.0, and should only be used for compatibility with Passlib 1.3 - 1.5.

genconfig

genconfig(scheme=None, category=None, **settings)

Generate a config string for specified scheme.

.. deprecated:: 1.7

This method will be removed in version 2.0, and should only
be used for compatibility with Passlib 1.3 - 1.6.

genhash

genhash(
    secret, config, scheme=None, category=None, **kwds
)

Generate hash for the specified secret using another hash.

.. deprecated:: 1.7

This method will be removed in version 2.0, and should only
be used for compatibility with Passlib 1.3 - 1.6.

identify

identify(
    hash,
    category=None,
    resolve=False,
    required=False,
    unconfigured=False,
)

Attempt to identify which algorithm the hash belongs to.

Note that this will only consider the algorithms currently configured for this context (see the :ref:schemes <context-schemes-option> option). All registered algorithms will be checked, from first to last, and whichever one positively identifies the hash first will be returned.

Parameters:

  • hash (str | bytes) –

    The hash string to test.

  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. Ignored by this function, this parameter is provided for symmetry with the other methods.

  • resolve (bool, default: False ) –

    If True, returns the hash handler itself, instead of the name of the hash.

  • required (bool, default: False ) –

    If True, this will raise a ValueError if the hash cannot be identified, instead of returning None.

Returns:

  • –

    The handler which first identifies the hash, or None if none of the algorithms identify the hash.

hash

hash(secret, scheme=None, category=None, **kwds)

run secret through selected algorithm, returning resulting hash.

Parameters:

  • secret (str | bytes) –

    the password to hash.

  • scheme (str | None, default: None ) –

    Optional scheme to use. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option). If no scheme is specified, the configured default will be used.

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will cause any category-specific defaults to be used when hashing the password (e.g. different default scheme, different default rounds values, etc).

  • \*\*kwds –

    All other keyword options are passed to the selected algorithm's :meth:PasswordHash.hash() <passlib.ifc.PasswordHash.hash> method.

Returns:

  • –

    The secret as encoded by the specified algorithm and options. The return value will always be a :class:!str.

encrypt

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.

verify

verify(
    secret, hash, scheme=None, category=None, **kwds
)

verify secret against an existing hash.

If no scheme is specified, this will attempt to identify the scheme based on the contents of the provided hash (limited to the schemes configured for this context). It will then check whether the password verifies against the hash.

Parameters:

  • secret (str | bytes) –

    the secret to verify

  • hash (str | bytes) –

    hash string to compare to

    if None is passed in, this will be treated as "never verifying"

  • scheme (str, default: None ) –

    Optionally force context to use specific scheme. This is usually not needed, as most hashes can be unambiguously identified. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option).

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories> string. This is mainly used when generating new hashes, it has little effect when verifying; this keyword is mainly provided for symmetry.

  • \*\*kwds –

    All additional keywords are passed to the appropriate handler, and should match its :attr:~passlib.ifc.PasswordHash.context_kwds.

Returns:

  • –

    True if the password matched the hash, else False.

Raises:

  • ValueError –
    • if the hash did not match any of the configured :meth:schemes.

    • if any of the arguments have an invalid value (this includes any keywords passed to the underlying hash's :meth:PasswordHash.verify() <passlib.ifc.PasswordHash.verify> method).

  • TypeError –
    • if any of the arguments have an invalid type (this includes any keywords passed to the underlying hash's :meth:PasswordHash.verify() <passlib.ifc.PasswordHash.verify> method).

    .. seealso:: the :ref:context-basic-example example in the tutorial

verify_and_update

verify_and_update(
    secret, hash, scheme=None, category=None, **kwds
)

verify password and re-hash the password if needed, all in a single call.

This is a convenience method which takes care of all the following: first it verifies the password (:meth:~CryptContext.verify), if this is successfull it checks if the hash needs updating (:meth:~CryptContext.needs_update), and if so, re-hashes the password (:meth:~CryptContext.hash), returning the replacement hash. This series of steps is a very common task for applications which wish to update deprecated hashes, and this call takes care of all 3 steps efficiently.

Parameters:

  • secret (str | bytes) –

    the secret to verify

  • hash –

    hash string to compare to.

    if None is passed in, this will be treated as "never verifying"

  • scheme (str, default: None ) –

    Optionally force context to use specific scheme. This is usually not needed, as most hashes can be unambiguously identified. Scheme must be one of the ones configured for this context (see the :ref:schemes <context-schemes-option> option).

    .. deprecated:: 1.7

    Support for this keyword is deprecated, and will be removed in Passlib 2.0.
    
  • category (str | None, default: None ) –

    Optional :ref:user category <user-categories>. If specified, this will cause any category-specific defaults to be used if the password has to be re-hashed.

  • \*\*kwds –

    all additional keywords are passed to the appropriate handler, and should match that hash's :attr:PasswordHash.context_kwds <passlib.ifc.PasswordHash.context_kwds>.

Returns:

  • –

    This function returns a tuple containing two elements: (verified, replacement_hash). The first is a boolean flag indicating whether the password verified, and the second an optional replacement hash. The tuple will always match one of the following 3 cases:

    • (False, None) indicates the secret failed to verify.
    • (True, None) indicates the secret verified correctly, and the hash does not need updating.
    • (True, str) indicates the secret verified correctly, but the current hash needs to be updated. The :class:!str will be the freshly generated hash, to replace the old one.

dummy_verify

dummy_verify()

Helper that applications can call when user wasn't found, in order to simulate time it would take to hash a password.

Runs verify() against a dummy hash, to simulate verification of a real account password.

.. versionadded:: 1.7

is_enabled

is_enabled(hash)

test if hash represents a usuable password -- i.e. does not represent an unusuable password such as "!", which is recognized by the :class:~passlib.hash.unix_disabled hash.

Raises:

  • ValueError –

    if the hash is not recognized (typically solved by adding unix_disabled to the list of schemes).

disable

disable(hash=None)

return a string to disable logins for user, usually by returning a non-verifying string such as "!".

Parameters:

  • hash –

    Callers can optionally provide the account's existing hash. Some disabled handlers (such as :class:!unix_disabled) will encode this into the returned value, so that it can be recovered via :meth:enable.

Returns:

  • –

    hash string which will be recognized as valid by the context, but is guaranteed to not validate against any password.

Raises:

  • RuntimeError –

    if this function is called w/o a disabled hasher (such as :class:~passlib.hash.unix_disabled) included in the list of schemes.

enable

enable(hash)

inverse of :meth:disable -- attempts to recover original hash which was converted by a :meth:!disable call into a disabled hash -- thus restoring the user's original password.

Returns:

  • –

    the original hash.

Raises:

  • ValueError –

    if original hash not present, or if the disabled handler doesn't support encoding the original hash (e.g. django_disabled)