Пример #1
0
def get_prf(name):
    """lookup pseudo-random family (prf) by name.

    :arg name:
        this must be the name of a recognized prf.
        currently this only recognizes names with the format
        :samp:`hmac-{digest}`, where :samp:`{digest}`
        is the name of a hash function such as
        ``md5``, ``sha256``, etc.

        this can also be a callable with the signature
        ``prf(secret, message) -> digest``,
        in which case it will be returned unchanged.

    :raises ValueError: if the name is not known
    :raises TypeError: if the name is not a callable or string

    :returns:
        a tuple of :samp:`({func}, {digest_size})`.

        * :samp:`{func}` is a function implementing
          the specified prf, and has the signature
          ``func(secret, message) -> digest``.

        * :samp:`{digest_size}` is an integer indicating
          the number of bytes the function returns.

    usage example::

        >>> from passlib.utils.pbkdf2 import get_prf
        >>> hmac_sha256, dsize = get_prf("hmac-sha256")
        >>> hmac_sha256
        <function hmac_sha256 at 0x1e37c80>
        >>> dsize
        32
        >>> digest = hmac_sha256('password', 'message')

    this function will attempt to return the fastest implementation
    it can find; if M2Crypto is present, and supports the specified prf,
    :func:`M2Crypto.EVP.hmac` will be used behind the scenes.
    """
    global _prf_cache
    if name in _prf_cache:
        return _prf_cache[name]
    if isinstance(name, str):
        if name.startswith("hmac-") or name.startswith("hmac_"):
            retval = _get_hmac_prf(name[5:])
        else:
            raise ValueError("unknown prf algorithm: %r" % (name,))
    elif callable(name):
        # assume it's a callable, use it directly
        digest_size = len(name(b('x'),b('y')))
        retval = (name, digest_size)
    else:
        raise ExpectedTypeError(name, "str or callable", "prf name")
    _prf_cache[name] = retval
    return retval
Пример #2
0
def get_prf(name):
    """lookup pseudo-random family (prf) by name.

    :arg name:
        this must be the name of a recognized prf.
        currently this only recognizes names with the format
        :samp:`hmac-{digest}`, where :samp:`{digest}`
        is the name of a hash function such as
        ``md5``, ``sha256``, etc.

        this can also be a callable with the signature
        ``prf(secret, message) -> digest``,
        in which case it will be returned unchanged.

    :raises ValueError: if the name is not known
    :raises TypeError: if the name is not a callable or string

    :returns:
        a tuple of :samp:`({func}, {digest_size})`.

        * :samp:`{func}` is a function implementing
          the specified prf, and has the signature
          ``func(secret, message) -> digest``.

        * :samp:`{digest_size}` is an integer indicating
          the number of bytes the function returns.

    usage example::

        >>> from passlib.utils.pbkdf2 import get_prf
        >>> hmac_sha256, dsize = get_prf("hmac-sha256")
        >>> hmac_sha256
        <function hmac_sha256 at 0x1e37c80>
        >>> dsize
        32
        >>> digest = hmac_sha256('password', 'message')

    this function will attempt to return the fastest implementation
    it can find; if M2Crypto is present, and supports the specified prf,
    :func:`M2Crypto.EVP.hmac` will be used behind the scenes.
    """
    global _prf_cache
    if name in _prf_cache:
        return _prf_cache[name]
    if isinstance(name, str):
        if name.startswith("hmac-") or name.startswith("hmac_"):
            retval = _get_hmac_prf(name[5:])
        else:
            raise ValueError("unknown prf algorithm: %r" % (name,))
    elif callable(name):
        # assume it's a callable, use it directly
        digest_size = len(name(b('x'),b('y')))
        retval = (name, digest_size)
    else:
        raise ExpectedTypeError(name, "str or callable", "prf name")
    _prf_cache[name] = retval
    return retval
Пример #3
0
def _load():
    global _get_category

    # TODO: would like to add support for inheriting config from a preset
    #       (or from existing hasher state) and letting PASSLIB_CONFIG
    #       be an update, not a replacement.

    # TODO: wrap and import any custom hashers as passlib handlers,
    #       so they could be used in the passlib config.

    # load config from settings
    _UNSET = object()
    config = getattr(settings, "PASSLIB_CONFIG", _UNSET)
    if config is _UNSET:
        # XXX: should probably deprecate this alias
        config = getattr(settings, "PASSLIB_CONTEXT", _UNSET)
    if config is _UNSET:
        config = "passlib-default"
    if config is None:
        warn(
            "setting PASSLIB_CONFIG=None is deprecated, "
            "and support will be removed in Passlib 1.8, "
            "use PASSLIB_CONFIG='disabled' instead.", DeprecationWarning)
        config = "disabled"
    elif not isinstance(config, (unicode, bytes, dict)):
        raise ExpectedTypeError(config, "str or dict", "PASSLIB_CONFIG")

    # load custom category func (if any)
    get_category = getattr(settings, "PASSLIB_GET_CATEGORY", None)
    if get_category and not callable(get_category):
        raise ExpectedTypeError(get_category, "callable",
                                "PASSLIB_GET_CATEGORY")

    # check if we've been disabled
    if config == "disabled":
        if _patched:  # pragma: no cover -- sanity check
            log.error("didn't expect monkeypatching would be applied!")
        _remove_patch()
        return

    # resolve any preset aliases
    if isinstance(config, str) and '\n' not in config:
        config = get_preset_config(config)

    # setup context
    _apply_patch()
    password_context.load(config)
    if get_category:
        # NOTE: _get_category is module global which is read by
        #       monkeypatched functions constructed by _apply_patch()
        _get_category = get_category
    log.debug("passlib.ext.django loaded")
Пример #4
0
def _load():
    global _get_category

    # TODO: would like to add support for inheriting config from a preset
    #       (or from existing hasher state) and letting PASSLIB_CONFIG
    #       be an update, not a replacement.

    # TODO: wrap and import any custom hashers as passlib handlers,
    #       so they could be used in the passlib config.

    # load config from settings
    _UNSET = object()
    config = getattr(settings, "PASSLIB_CONFIG", _UNSET)
    if config is _UNSET:
        # XXX: should probably deprecate this alias
        config = getattr(settings, "PASSLIB_CONTEXT", _UNSET)
    if config is _UNSET:
        config = "passlib-default"
    if config is None:
        warn("setting PASSLIB_CONFIG=None is deprecated, "
             "and support will be removed in Passlib 1.8, "
             "use PASSLIB_CONFIG='disabled' instead.",
             DeprecationWarning)
        config = "disabled"
    elif not isinstance(config, (unicode, bytes, dict)):
        raise ExpectedTypeError(config, "str or dict", "PASSLIB_CONFIG")

    # load custom category func (if any)
    get_category = getattr(settings, "PASSLIB_GET_CATEGORY", None)
    if get_category and not callable(get_category):
        raise ExpectedTypeError(get_category, "callable", "PASSLIB_GET_CATEGORY")

    # check if we've been disabled
    if config == "disabled":
        if _patched: # pragma: no cover -- sanity check
            log.error("didn't expect monkeypatching would be applied!")
        _remove_patch()
        return

    # resolve any preset aliases
    if isinstance(config, str) and '\n' not in config:
        config = get_preset_config(config)

    # setup context
    _apply_patch()
    password_context.load(config)
    if get_category:
        # NOTE: _get_category is module global which is read by
        #       monkeypatched functions constructed by _apply_patch()
        _get_category = get_category
    log.debug("passlib.ext.django loaded")