Skip to content

passlib.utils.handlers - Framework for writing password hashes

Framework for writing password hashes.

Warning

This module is primarily used as an internal support module. Its interface has not been finalized yet, and may be changed somewhat between major releases of Passlib, as the internal code is cleaned up and simplified.

Note

TODO: This module, and the instructions on how to write a custom handler, definitely need to be rewritten for clarity. They are not yet organized, and may leave out some important details.

Implementing Custom Handlers

All that is required in order to write a custom handler that will work with Passlib is to create an object (be it module, class, or object) that exposes the functions and attributes required by the PasswordHash API. For classes, Passlib does not make any requirements about what a class instance should look like (if the implementation even uses them).

That said, most of the handlers built into Passlib are based around the GenericHandler class, and its associated mixin classes. While deriving from this class is not required, doing so will greatly reduce the amount of additional code that is needed for all but the most convoluted password hash schemes.

Once a handler has been written, it may be used explicitly, passed into a CryptContext constructor, or registered globally with Passlib via the passlib.registry module.

Tip

See Testing Hash Handlers for details about how to test custom handlers against Passlib's unittest suite.

The GenericHandler Class

Design

Most of the handlers built into Passlib are based around the GenericHandler class. This class is designed under the assumption that the common workflow for hashes is some combination of the following:

  1. parse hash into constituent parts - performed by from_string().
  2. validate constituent parts - performed by GenericHandler's constructor, and the normalization functions such as _norm_checksum() and HasSalt._norm_salt() which are provided by its related mixin classes.
  3. calculate the raw checksum for a specific password - performed by _calc_checksum().
  4. assemble hash, including new checksum, into a new string - performed by to_string().

With this in mind, GenericHandler provides implementations of most of the PasswordHash API methods, eliminating the need for almost all the boilerplate associated with writing a password hash.

In order to minimize the amount of unneeded features that must be loaded in, the GenericHandler class itself contains only the parts which are needed by almost all handlers: parsing, rendering, and checksum validation. Validation of all other parameters (such as salt, rounds, etc) is split out into separate mixin classes which enhance GenericHandler with additional features.

Usage

In order to use GenericHandler, just subclass it, and then do the following:

  • fill out the name attribute with the name of your hash.
  • fill out the PasswordHash.setting_kwds attribute with a tuple listing all the settings your hash accepts.
  • provide an implementation of the from_string() classmethod.

    This method should take in a potential hash string, parse it into components, and return an instance of the class which contains the parsed components. It should throw a ValueError if no hash, or an invalid hash, is provided.

  • provide an implementation of the to_string() instance method.

    This method should render an instance of your handler class (such as returned by from_string()), returning a hash string.

  • provide an implementation of the _calc_checksum() instance method.

    This is the heart of the hash; this method should take in the password as the first argument, then generate and return the digest portion of the hash, according to the settings (such as salt, etc) stored in the parsed instance this method was called from.

    Note that it should not return the full hash with identifiers, etc; that job should be performed by to_string().

Some additional notes:

  • In addition to simply subclassing GenericHandler, most handlers will also benefit from adding in some of the mixin classes that are designed to add features to GenericHandler. See mixin classes for more details.
  • Most implementations will want to alter/override the default identify() method. By default, it returns True for all hashes that from_string() can parse without raising a ValueError; which is reliable, but somewhat slow. For faster identification purposes, subclasses may fill in the ident attribute with the hash's identifying prefix, which identify() will then test for instead of calling from_string(). For more complex situations, a custom implementation should be used; the HasManyIdents mixin may also be helpful.
  • This class does not support context kwds of any type, since that is a rare enough requirement inside passlib.

Interface

GenericHandler

GenericHandler(
    checksum=None, use_defaults=False, **kwds
)

helper class for implementing hash handlers.

GenericHandler-derived classes will have (at least) the following constructor options, though others may be added by mixins and by the class itself:

Parameters:

  • checksum –

    this should contain the digest portion of a parsed hash (mainly provided when the constructor is called by :meth:from_string()). defaults to None.

  • use_defaults –

    If False (the default), a :exc:TypeError should be thrown if any settings required by the handler were not explicitly provided.

    If True, the handler should attempt to provide a default for any missing values. This means generate missing salts, fill in default cost parameters, etc.

    This is typically only set to True when the constructor is called by :meth:hash, allowing user-provided values to be handled in a more permissive manner.

  • relaxed –

    If False (the default), a :exc:ValueError should be thrown if any settings are out of bounds or otherwise invalid.

    If ``True``, they should be corrected if possible, and a warning
    issue. If not possible, only then should an error be raised.
    (e.g. under ``relaxed=True``, rounds values will be clamped
    to min/max rounds).
    
    This is mainly used when parsing the config strings of certain
    hashes, whose specifications implementations to be tolerant
    of incorrect values in salt strings.
    

    Class Attributes

    .. attribute:: ident

    [optional]
    If this attribute is filled in, the default :meth:`identify` method will use
    it as a identifying prefix that can be used to recognize instances of this handler's
    hash. Filling this out is recommended for speed.
    
    This should be a unicode str.
    

    .. attribute:: _hash_regex

    [optional]
    If this attribute is filled in, the default :meth:`identify` method
    will use it to recognize instances of the hash. If :attr:`ident`
    is specified, this will be ignored.
    
    This should be a unique regex object.
    

    .. attribute:: checksum_size

    [optional]
    Specifies the number of characters that should be expected in the checksum string.
    If omitted, no check will be performed.
    

    .. attribute:: checksum_chars

    [optional]
    A string listing all the characters allowed in the checksum string.
    If omitted, no check will be performed.
    
    This should be a unicode str.
    

    .. attribute:: _stub_checksum

    Placeholder checksum that will be used by genconfig()
    in lieu of actually generating a hash for the empty string.
    This should be a string of the same datatype as :attr:`checksum`.
    

    Instance Attributes

    .. attribute:: checksum

    The checksum string provided to the constructor (after passing it
    through :meth:`_norm_checksum`).
    

    Required Subclass Methods

    The following methods must be provided by handler subclass:

    .. automethod:: from_string .. automethod:: to_string .. automethod:: _calc_checksum

    Default Methods

    The following methods have default implementations that should work for most cases, though they may be overridden if the hash subclass needs to:

    .. automethod:: _norm_checksum

    .. automethod:: genconfig .. automethod:: genhash .. automethod:: identify .. automethod:: hash .. automethod:: verify

from_string classmethod

from_string(hash, **context)

return parsed instance from hash/configuration string

Parameters:

  • \\*\\*context –

    context keywords to pass to constructor (if applicable).

Returns:

  • –

    hash parsed into components, for formatting / calculating checksum.

Raises:

  • ValueError –

    if hash is incorrectly formatted

to_string

to_string()

render instance to hash or configuration string

Returns:

  • –

    hash string with salt & digest included.

    should return native str.

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(**kwds)

[experimental method] return info about bitsizes of hash

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.

GenericHandler Mixins

HasSalt

HasSalt(salt=None, **kwds)

mixin for validating salts.

This :class:GenericHandler mixin adds a salt keyword to the class constuctor; any value provided is passed through the :meth:_norm_salt method, which takes care of validating salt length and content, as well as generating new salts if one it not provided.

Parameters:

  • salt –

    optional salt string

  • salt_size –

    optional size of salt (only used if no salt provided); defaults to :attr:default_salt_size.

    Class Attributes

    In order for :meth:!_norm_salt to do its job, the following attributes should be provided by the handler subclass:

    .. attribute:: min_salt_size

    The minimum number of characters allowed in a salt string.
    An :exc:`ValueError` will be throw if the provided salt is too small.
    Defaults to ``0``.
    

    .. attribute:: max_salt_size

    The maximum number of characters allowed in a salt string.
    By default an :exc:`ValueError` will be throw if the provided salt is
    too large; but if ``relaxed=True``, it will be clipped and a warning
    issued instead. Defaults to ``None``, for no maximum.
    

    .. attribute:: default_salt_size

    [required]
    If no salt is provided, this should specify the size of the salt
    that will be generated by :meth:`_generate_salt`. By default
    this will fall back to :attr:`max_salt_size`.
    

    .. attribute:: salt_chars

    A string containing all the characters which are allowed in the salt
    string. An :exc:`ValueError` will be throw if any other characters
    are encountered. May be set to ``None`` to skip this check (but see
    in :attr:`default_salt_chars`).
    

    .. attribute:: default_salt_chars

    [required]
    This attribute controls the set of characters use to generate
    *new* salt strings. By default, it mirrors :attr:`salt_chars`.
    If :attr:`!salt_chars` is ``None``, this attribute must be specified
    in order to generate new salts. Aside from that purpose,
    the main use of this attribute is for hashes which wish to generate
    salts from a restricted subset of :attr:`!salt_chars`; such as
    accepting all characters, but only using a-z.
    

    Instance Attributes

    .. attribute:: salt

    This instance attribute will be filled in with the salt provided
    to the constructor (as adapted by :meth:`_norm_salt`)
    

    Subclassable Methods

    .. automethod:: _norm_salt .. automethod:: _generate_salt

default_salt_size

default_salt_size()

default salt size (defaults to max_salt_size)

default_salt_chars

default_salt_chars()

charset used to generate new salt strings (defaults to salt_chars)

bitsize classmethod

bitsize(salt_size=None, **kwds)

[experimental method] return info about bitsizes of hash

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.

from_string classmethod

from_string(hash, **context)

return parsed instance from hash/configuration string

Parameters:

  • \\*\\*context –

    context keywords to pass to constructor (if applicable).

Returns:

  • –

    hash parsed into components, for formatting / calculating checksum.

Raises:

  • ValueError –

    if hash is incorrectly formatted

to_string

to_string()

render instance to hash or configuration string

Returns:

  • –

    hash string with salt & digest included.

    should return native str.

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)

HasRounds

HasRounds(rounds=None, **kwds)

mixin for validating rounds parameter

This :class:GenericHandler mixin adds a rounds keyword to the class constuctor; any value provided is passed through the :meth:_norm_rounds method, which takes care of validating the number of rounds.

Parameters:

  • rounds –

    optional number of rounds hash should use

    Class Attributes

    In order for :meth:!_norm_rounds to do its job, the following attributes must be provided by the handler subclass:

    .. attribute:: min_rounds

    The minimum number of rounds allowed. A :exc:`ValueError` will be
    thrown if the rounds value is too small. Defaults to ``0``.
    

    .. attribute:: max_rounds

    The maximum number of rounds allowed. A :exc:`ValueError` will be
    thrown if the rounds value is larger than this. Defaults to ``None``
    which indicates no limit to the rounds value.
    

    .. attribute:: default_rounds

    If no rounds value is provided to constructor, this value will be used.
    If this is not specified, a rounds value *must* be specified by the
    application.
    

    .. attribute:: rounds_cost

    [required]
    The ``rounds`` parameter typically encodes a cpu-time cost
    for calculating a hash. This should be set to ``"linear"``
    (the default) or ``"log2"``, depending on how the rounds value relates
    to the actual amount of time that will be required.
    

    Class Methods

    .. todo:: document using() and needs_update() options

    Instance Attributes

    .. attribute:: rounds

    This instance attribute will be filled in with the rounds value provided
    to the constructor (as adapted by :meth:`_norm_rounds`)
    

    Subclassable Methods

    .. automethod:: _norm_rounds

bitsize classmethod

bitsize(rounds=None, vary_rounds=0.1, **kwds)

[experimental method] return info about bitsizes of hash

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.

from_string classmethod

from_string(hash, **context)

return parsed instance from hash/configuration string

Parameters:

  • \\*\\*context –

    context keywords to pass to constructor (if applicable).

Returns:

  • –

    hash parsed into components, for formatting / calculating checksum.

Raises:

  • ValueError –

    if hash is incorrectly formatted

to_string

to_string()

render instance to hash or configuration string

Returns:

  • –

    hash string with salt & digest included.

    should return native str.

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)

HasManyIdents

HasManyIdents(ident=None, **kwds)

mixin for hashes which use multiple prefix identifiers

For the hashes which may use multiple identifier prefixes, this mixin adds an ident keyword to constructor. Any value provided is passed through the :meth:norm_idents method, which takes care of validating the identifier, as well as allowing aliases for easier specification of the identifiers by the user.

.. todo::

document this class's usage

Class Methods

.. todo:: document using() and needs_update() options

using classmethod

using(default_ident=None, ident=None, **kwds)

This mixin adds support for the following :meth:~passlib.ifc.PasswordHash.using keywords:

Parameters:

  • default_ident –

    default identifier that will be used by resulting customized hasher.

  • ident –

    supported as alternate alias for default_ident.

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.

from_string classmethod

from_string(hash, **context)

return parsed instance from hash/configuration string

Parameters:

  • \\*\\*context –

    context keywords to pass to constructor (if applicable).

Returns:

  • –

    hash parsed into components, for formatting / calculating checksum.

Raises:

  • ValueError –

    if hash is incorrectly formatted

to_string

to_string()

render instance to hash or configuration string

Returns:

  • –

    hash string with salt & digest included.

    should return native str.

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(**kwds)

[experimental method] return info about bitsizes of hash

HasManyBackends

HasManyBackends(
    checksum=None, use_defaults=False, **kwds
)

GenericHandler mixin which provides selecting from multiple backends.

.. todo::

finish documenting this class's usage

For hashes which need to select from multiple backends, depending on the host environment, this class offers a way to specify alternate :meth:_calc_checksum methods, and will dynamically chose the best one at runtime.

.. versionchanged:: 1.7

This class now derives from :class:`BackendMixin`, which abstracts
out a more generic framework for supporting multiple backends.
The public api (:meth:`!get_backend`, :meth:`!has_backend`, :meth:`!set_backend`)
is roughly the same.

Private API (Subclass Hooks)

As of version 1.7, classes should implement :meth:!_load_backend_{name}, per :class:BackendMixin. This hook should invoke :meth:!_set_calc_checksum_backcend to install it's backend method.

.. deprecated:: 1.7

The following api is deprecated, and will be removed in Passlib 2.0:

.. attribute:: has_backend

private class attribute checked by :meth:`has_backend` to see if a
specific backend is available, it should be either ``True``
or ``False``. One of these should be provided by
the subclass for each backend listed in :attr:`backends`.

.. classmethod:: calc_checksum

private class method that should implement :meth:`_calc_checksum`
for a given backend. it will only be called if the backend has
been selected by :meth:`set_backend`. One of these should be provided
by the subclass for each backend listed in :attr:`backends`.

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.

from_string classmethod

from_string(hash, **context)

return parsed instance from hash/configuration string

Parameters:

  • \\*\\*context –

    context keywords to pass to constructor (if applicable).

Returns:

  • –

    hash parsed into components, for formatting / calculating checksum.

Raises:

  • ValueError –

    if hash is incorrectly formatted

to_string

to_string()

render instance to hash or configuration string

Returns:

  • –

    hash string with salt & digest included.

    should return native str.

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(**kwds)

[experimental method] return info about bitsizes of hash

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:

  • –
    • True if backend is available.
    • False if it's available / can't be loaded.
    • None if 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.

HasRawSalt

HasRawSalt(salt=None, **kwds)

mixin for classes which use decoded salt parameter

A variant of :class:!HasSalt which takes in decoded bytes instead of an encoded string.

.. todo::

document this class's usage

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.

from_string classmethod

from_string(hash, **context)

return parsed instance from hash/configuration string

Parameters:

  • \\*\\*context –

    context keywords to pass to constructor (if applicable).

Returns:

  • –

    hash parsed into components, for formatting / calculating checksum.

Raises:

  • ValueError –

    if hash is incorrectly formatted

to_string

to_string()

render instance to hash or configuration string

Returns:

  • –

    hash string with salt & digest included.

    should return native str.

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(salt_size=None, **kwds)

[experimental method] return info about bitsizes of hash

default_salt_size

default_salt_size()

default salt size (defaults to max_salt_size)

default_salt_chars

default_salt_chars()

charset used to generate new salt strings (defaults to salt_chars)

HasRawChecksum

HasRawChecksum(
    checksum=None, use_defaults=False, **kwds
)

mixin for classes which work with decoded checksum bytes

.. todo::

document this class's usage

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.

from_string classmethod

from_string(hash, **context)

return parsed instance from hash/configuration string

Parameters:

  • \\*\\*context –

    context keywords to pass to constructor (if applicable).

Returns:

  • –

    hash parsed into components, for formatting / calculating checksum.

Raises:

  • ValueError –

    if hash is incorrectly formatted

to_string

to_string()

render instance to hash or configuration string

Returns:

  • –

    hash string with salt & digest included.

    should return native str.

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(**kwds)

[experimental method] return info about bitsizes of hash

Examples

Note

TODO: Show some walk-through examples of how to use GenericHandler and its mixins.

The StaticHandler class

StaticHandler

StaticHandler(
    checksum=None, use_defaults=False, **kwds
)

GenericHandler mixin for classes which have no settings.

This mixin assumes the entirety of the hash ise stored in the :attr:checksum attribute; that the hash has no rounds, salt, etc. This class provides the following:

  • a default :meth:genconfig that always returns None.
  • a default :meth:from_string and :meth:to_string that store the entire hash within :attr:checksum, after optionally stripping a constant prefix.

All that is required by subclasses is an implementation of the :meth:_calc_checksum method.

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(**kwds)

[experimental method] return info about bitsizes of hash

Note

TODO: Show some examples of how to use StaticHandler.

Other Constructors

PrefixWrapper

PrefixWrapper(
    name,
    wrapped,
    prefix="",
    orig_prefix="",
    lazy=False,
    doc=None,
    ident=None,
)

wraps another handler, adding a constant prefix.

instances of this class wrap another password hash handler, altering the constant prefix that's prepended to the wrapped handlers' hashes.

this is used mainly by the :doc:ldap crypt <passlib.hash.ldap_crypt> handlers; such as :class:~passlib.hash.ldap_md5_crypt which wraps :class:~passlib.hash.md5_crypt and adds a {CRYPT} prefix.

usage::

myhandler = PrefixWrapper("myhandler", "md5_crypt", prefix="$mh$", orig_prefix="$1$")

Parameters:

  • name –

    name to assign to handler

  • wrapped –

    handler object or name of registered handler

  • prefix –

    identifying prefix to prepend to all hashes

  • orig_prefix –

    prefix to strip (defaults to '').

  • lazy –

    if True and wrapped handler is specified by name, don't look it up until needed.

__getattr__

__getattr__(attr)

proxy most attributes from wrapped class (e.g. rounds, salt size, etc)

Testing Hash Handlers

Within its unittests, Passlib provides the passlib.tests.utils.HandlerCase class, which can be subclassed to provide a unittest-compatible test class capable of checking if a handler adheres to the PasswordHash API.

Usage

As an example of how to use HandlerCase, the following is an annotated version of the unittest for passlib.hash.des_crypt:

from passlib.hash import des_crypt
from passlib.tests.utils import HandlerCase


# create a subclass for the handler...
class DesCryptTest(HandlerCase):
    "test des-crypt algorithm"

    # [required] - store the handler object itself in the handler attribute
    handler = des_crypt

    # [required] - this should be a list of (password, hash) pairs,
    #              which should all verify correctly using your handler.
    #              it is recommend include pairs which test all of the following:
    #
    #              * empty string & short strings for passwords
    #              * passwords with 2 byte unicode characters
    #              * hashes with varying salts, rounds, and other options
    known_correct_hashes = (
        # format: (password, hash)
        ("", "OgAwTx2l6NADI"),
        (" ", "/Hk.VPuwQTXbc"),
        ("test", "N1tQbOFcM5fpg"),
        ("Compl3X AlphaNu3meric", "um.Wguz3eVCx2"),
        ("4lpHa N|_|M3r1K W/ Cur5Es: #$%(*)(*%#", "sNYqfOyauIyic"),
        ("AlOtBsOl", "cEpWz5IUCShqM"),
        ("hell\u00d6", "saykDgk3BPZ9E"),
    )

    # [optional] - if there are hashes which are similar in format
    #              to your handler, and you want to make sure `identify()`
    #              does not return ``True`` for such hashes,
    #              list them here. otherwise this can be omitted.
    #
    known_unidentified_hashes = [
        # bad char in otherwise correctly formatted hash
        "!gAwTx2l6NADI",
    ]

HandlerCase is part of Passlib's test suite (not the public API); see passlib/tests/utils.py for its full interface.