Current File : //usr/lib/python2.7/site-packages/passlib/crypto/digest.pyc
�
���Xc@ s�dZddlmZddlZddlZeje�Zy9ddlmZ	e	j
dkruejd�dZ	nWne
k
r�dZ	nXddlZddlZddlmZddlmZyddlmZWne
k
r�dZnXdd	lmZdd
lmZmZmZmZmZddlmZm Z m!Z!m"Z"ddl#m$Z$d
dddddgZ%dMZ&dOZ'dPdQdRdSdTdUdVdWdXdYdZgZ(iZ)d-�Z*d.�Z+e,d/�Z-e)j.e-_/dd0�Z0defd1��YZ1ed2�ed3�D��Z2ed4�ed3�D��Z3e,d5�Z4dd6�Z5ed7�j6Z7dd8�Zej8j9d9�p}d:Z:e"r�e:d[kr�dd<l;m<Z<d=�Z=d>�Z>d;Z?n�e:d\kr
ddlmZdd@lm@Z@e@dkZAiZBdA�Z=d?Z?nJe:d]kstC�ddClDmEZFddDlmGZGdE�Z=dF�Z>dBZ?e:e?krpdZZ	ngerdGnde	r�dHnddIe?gD]ZHeHr�eH^q�ZIdGeIkr�dJZJndHeIkr�dKZJndZJdS(^slpasslib.crypto.digest -- crytographic helpers used by the password hashes in passlib

.. versionadded:: 1.7
i����(tdivisionN(tpbkdf2_hmacthashlibs*ignoring pure-python hashlib.pbkdf2_hmac()(tStruct(twarn(texc(t
join_bytest
to_native_strtjoin_byte_valuestto_bytest
SequenceMixin(tiranget	int_typestunicode_or_bytes_typestPY3(tmemoized_propertytlookup_hashtHashInfotnorm_hash_nametcompile_hmactpbkdf1Rii i@tmd2tmd5tsha1ssha-1tsha224ssha-224ssha2-224tsha256ssha-256ssha2-256tsha384ssha-384ssha2-384tsha512ssha-512ssha2-512tmd4tshassha-0tsha0tripemdt	ripemd160s
ripemd-160c	C s�|}t|t�s*t|dd�}ntjdd|j�j��}|jd�r�|d}|jd�r�|d }q�nd	�}||�}|r�|Stj	d
|�}|rT|j
ddd
�\}}}|r�||7}n|}|r%|d|7}|r|d7}n||7}n||�}|r;|Stjd|||�n.|}|j
dd�}tjd|||�||fS(sA
    internal helper used by :func:`lookup_hash` --
    normalize arbitrary hash name to hashlib format.
    if name not recognized, returns dummy record and issues a warning.

    :arg name:
        unnormalized name

    :returns:
        tuple with 2+ elements: ``(hashlib_name, iana_name|None, ... 0+ aliases)``.
    sutf-8s	hash names[_ /]t-sscram-is-plusi����cS s%xtD]}||kr|SqWdS(N(t_known_hash_names(tnametrow((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pytcheck_tablevs
s8(?i)^(?P<name>[a-z]+)-?(?P<rev>\d)?-?(?P<size>\d{3,4})?$R#trevtsizet_s0normalizing unrecognized hash name %r => %r / %rs;normalizing unrecognized hash name and format %r => %r / %r(t
isinstancetstrRtretsubtstriptlowert
startswithtendswithtmatchtgrouptlogtinfotreplacetwarning(	R#torigR%tresulttmt	iana_nameR&R'thashlib_name((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyt_get_hash_aliases^sB!
	


		
c s��jd�rD�dkrDytt��SWqDtk
r@qDXntj�y��d�Wntk
rqn9Xd��fd�}�|_d|_d�|_|S�dkr�d	d
l	m
}|SdS(
s
    internal helper used by :func:`lookup_hash` --
    lookup hash constructor by name

    :arg name:
        name (normalized to hashlib format, e.g. ``"sha256"``)

    :returns:
        hash constructor, e.g. ``hashlib.sha256()``;
        or None if hash can't be located.
    R(tnewt
algorithmstc s
��|�S(N((tmsg(R#tnew_ssl_hash(s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pytconst�sRsMwrapper for hashlib.new(%r),
generated by passlib.crypto.digest.lookup_hash()Ri����(R(snewR>N(R/tgetattrRtAttributeErrorR=t
ValueErrort__name__t
__module__t__doc__tpasslib.crypto._md4RtNone(R#RBR((R#RAs9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyt_get_hash_const�s(

	
		
c	C s�t}y||SWnttfk
r+nXt}t|t�r�t|�}|d}|sct�||kr�t|d|�}|j	dkr�|s�t�|S|||<|St|�}|dkrw|r�td|�St
j|��qwn�t|t�r|St|�rb|}t|�j�}|d}t|�}|dkrJqw||krYqwt}nt
j|dd��t||�}|||<|r�xO|D]D}|r�|j|�d|gks�td|��|||<q�q�Wn|S(sG
    Returns a :class:`HashInfo` record containing information about a given hash function.
    Can be used to look up a hash constructor by name, normalize hash name representation, etc.

    :arg digest:
        This can be any of:

        * A string containing a :mod:`!hashlib` digest name (e.g. ``"sha256"``),
        * A string containing an IANA-assigned hash name,
        * A digest constructor function (e.g. ``hashlib.sha256``).

        Case is ignored, underscores are converted to hyphens,
        and various other cleanups are made.

    :param return_unknown:
        By default, this function will throw an :exc:`~passlib.exc.UnknownHashError` if no hash constructor
        can be found.  However, if this flag is False, it will instead return a dummy record
        without a constructor function.  This is mainly used by :func:`norm_hash_name`.

    :returns HashInfo:
        :class:`HashInfo` instance containing information about specified digest.

        Multiple calls resolving to the same hash should always
        return the same :class:`!HashInfo` instance.
    itreturn_unknownsdigest name or constructortdigests%r already in cacheN(t_hash_info_cachetKeyErrort	TypeErrortTrueR)R
R<tAssertionErrorRRBRJRKRRtUnknownHashErrortcallableR#tFalsetExpectedTypeErrortget(	RMRLtcachet
cache_by_namet	name_listR#R4RBtother_const((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR�sV



	

+cC srt|dt�}|js5td|ftj�n|dkrH|jS|dkr[|jStd|f��dS(s<Normalize hash function name (convenience wrapper for :func:`lookup_hash`).

    :arg name:
        Original hash function name.

        This name can be a Python :mod:`~hashlib` digest name,
        a SCRAM mechanism name, IANA assigned hash name, etc.
        Case is ignored, and underscores are converted to hyphens.

    :param format:
        Naming convention to normalize to.
        Possible values are:

        * ``"hashlib"`` (the default) - normalizes name to be compatible
          with Python's :mod:`!hashlib`.

        * ``"iana"`` - normalizes name to IANA-assigned hash function name.
          For hashes which IANA hasn't assigned a name for, this issues a warning,
          and then uses a heuristic to return a "best guess" name.

    :returns:
        Hash name, returned as native :class:`!str`.
    RLs"norm_hash_name(): unknown hash: %rRtianasunknown format: %rN(	RRQRBRRtPasslibRuntimeWarningR#R:RE(R#tformatR4((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR9s	cB skeZdZdZdZdZdZdZdZ	d�Z
d�Zd�Ze
d��Ze
d��ZRS(s�
    Record containing information about a given hash algorithm, as returned :func:`lookup_hash`.

    This class exposes the following attributes:

    .. autoattribute:: const
    .. autoattribute:: digest_size
    .. autoattribute:: block_size
    .. autoattribute:: name
    .. autoattribute:: iana_name
    .. autoattribute:: aliases

    This object can also be treated a 3-element sequence
    containing ``(const, digest_size, block_size)``.
    cC s�|d|_|d|_|d|_||_|dkr@dS|�}|j|_|j|_t|j��|jkr�t	d|j��n|j|jkr�t
d|j||jftj�ndS(s
        initialize new instance.
        :arg const:
            hash constructor
        :arg names:
            list of 2+ names. should be list of ``(name, iana_name, ... 0+ aliases)``.
            names must be lower-case. only iana name may be None.
        iiiNs"%r constructor failed sanity checksEinconsistent digest name: %r resolved to %r, which reports name as %r(
R#R:taliasesRBRJtdigest_sizet
block_sizetlenRMtRuntimeErrorRRR](tselfRBtnamesthash((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyt__init__�s	


		cC sd|j|j|jfS(Ns/<lookup_hash(%r): digest_size=%r block_size=%r)(R#R`Ra(Rd((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyt__repr__�scC s|j|j|jfS(N(RBR`Ra(Rd((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyt	_as_tuple�scC sAts
dSyt|jddd�tSWntk
r<tSXdS(s5helper to detect if hash is supported by fastpbkdf2()tptsiN(t_fast_pbkdf2_hmacRJR#RQRERU(Rd((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pytsupported_by_fastpbkdf2�s
cC sAts
dSyt|jddd�tSWntk
r<tSXdS(s>helper to detect if hash is supported by hashlib.pbkdf2_hmac()RjRkiN(t_stdlib_pbkdf2_hmacRJR#RQRERU(Rd((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pytsupported_by_hashlib_pbkdf2�s
N((RFRGRHRJR#R:R_RBR`RaRgRhRiRRmRo(((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR\s	!		cc s|]}|dAVqdS(i\N((t.0tx((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pys	<genexpr>�sicc s|]}|dAVqdS(i6N((RpRq((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pys	<genexpr>�sc	 st|�}|\}}}|dks3td��t|t�sWt|dd�}nt|�}||kr�||�j�}|}n||kr�|d||7}n||jt��j	�||jt
��j	�|r���fd�}n��fd�}||_|S(s�
    This function returns an efficient HMAC function, hardcoded with a specific digest & key.
    It can be used via ``hmac = compile_hmac(digest, key)``.

    :arg digest:
        digest name or constructor.

    :arg key:
        secret key as :class:`!bytes` or :class:`!unicode` (unicode will be encoded using utf-8).

    :param multipart:
        request a multipart constructor instead (see return description).

    :returns:
        By default, the returned function has the signature ``hmac(msg) -> digest output``.

        However, if ``multipart=True``, the returned function has the signature
        ``hmac() -> update, finalize``, where ``update(msg)`` may be called multiple times,
        and ``finalize() -> digest_output`` may be repeatedly called at any point to
        calculate the HMAC digest so far.

        The returned object will also have a ``digest_info`` attribute, containing
        a :class:`lookup_hash` instance for the specified digest.

    This function exists, and has the weird signature it does, in order to squeeze as
    provide as much efficiency as possible, by omitting much of the setup cost
    and features of the stdlib :mod:`hmac` module.
    isblock size too smalltparamtkeytc s(�����fd�}�j|fS(s)generated by compile_hmac(multipart=True)c s&��}|j�j��|j�S(N(tupdateRM(touter(t_outer_copytinner(s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pytfinalizes	(Ru(Ry(t_inner_copyRw(Rxs9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pythmacs	c s<��}|j|���}|j|j��|j�S(sgenerated by compile_hmac()(RuRM(R@RxRv(RzRw(s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR{s
	
	(RRRR)tbytesR	RbRMt	translatet	_TRANS_36tcopyt	_TRANS_5Ctdigest_info(	RMRst	multipartR�RBR`RatklenR{((RzRws9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR�s$ 			c
C s2t|�\}}}t|dd�}t|dd�}t|t�s`tj|dd��n|dkr{td��n|d
kr�|}ngt|t�s�tj|dd	��n@|d
kr�td��n%||kr�td||f��n||}x&t|�D]}	||�j	�}qW|| S(s;pkcs#5 password-based key derivation v1.5

    :arg digest:
        digest name or constructor.
        
    :arg secret:
        secret to use when generating the key.
        may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
        
    :arg salt:
        salt string to use when generating key.
        may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).

    :param rounds:
        number of rounds to use to generate key.

    :arg keylen:
        number of bytes to generate (if omitted / ``None``, uses digest's native size)

    :returns:
        raw :class:`bytes` of generated key

    .. note::

        This algorithm has been deprecated, new code should use PBKDF2.
        Among other limitations, ``keylen`` cannot be larger
        than the digest size of the specified hash.
    Rrtsecrettsalttinttroundsisrounds must be at least 1sint or Nonetkeyleniskeylen must be at least 0s'keylength too large for digest: %r > %rN(
RR	R)RRRVRERJRRM(
RMR�R�R�R�RBR`RatblockR(((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyRs(	
s>Lc s�t|dd�}t�dd��t|�}|j}t�t�s`tj�dd��n�dkr{td��n|d
kr�|}nBt|t�s�tj|dd	��n|dkr�td
��n||d|}|t	kr�t
d��n|jr!t|j
|��|�S|jrCt|j
|��|�St||��t|��t����fd�td|d�D��| S(spkcs#5 password-based key derivation v2.0 using HMAC + arbitrary digest.

    :arg digest:
        digest name or constructor.

    :arg secret:
        passphrase to use to generate key.
        may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).

    :arg salt:
        salt string to use when generating key.
        may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).

    :param rounds:
        number of rounds to use to generate key.

    :arg keylen:
        number of bytes to generate.
        if omitted / ``None``, will use digest's native output size.

    :returns:
        raw bytes of generated key

    .. versionchanged:: 1.7

        This function will use the first available of the following backends:

        * `fastpbk2 <https://pypi.python.org/pypi/fastpbkdf2>`_
        * :func:`hashlib.pbkdf2_hmac` (only available in py2 >= 2.7.8, and py3 >= 3.4)
        * builtin pure-python backend

        See :data:`passlib.crypto.digest.PBKDF2_BACKENDS` to determine
        which backend(s) are in use.
    RrR�R�R�R�isrounds must be at least 1sint or NoneR�skeylen must be at least 1skeylen too long for digestc3 s1|]'}����t|����VqdS(N(t_pack_uint32(Rpti(t
calc_blockt
keyed_hmacR�R�(s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pys	<genexpr>�sN(R	RR`R)RRRVRERJt
MAX_UINT32t
OverflowErrorRmRlR#RoRnRt_get_pbkdf2_looperRR(RMR�R�R�R�R�R`tblock_count((R�R�R�R�s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR_s6$				tPASSLIB_PBKDF2_BACKENDtanys
from-bytes(tpartialcC s
tt|�S(N(R�t_pbkdf2_looper(R`((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR��scC shtj}d}|||�}x7t|d�D]%}||�}||||�N}q/W|j||�S(sk
        py3-only implementation of pbkdf2 inner loop;
        uses 'int.from_bytes' + integer XOR
        tbigi(R�t
from_bytesRR	(R`R�RMR�R�tBIGtaccumR(((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR��s	tunpack(tsys_bitscC s�yt|SWntk
rnXtrH|d@rH|d?}d|}nX|d@s�try|d?}d|}|d7}q�|d?}d|}ntd|��t|�}td	|d
djd�t|�D��d
djd�t|�D���}dj|�}x(t|�D]}|d||f7}qW|dj|�7}t	|dd�}tdtd|�}t�}	t
|||	�|	d}
||
_|
t|<|
S(s)
        We want a helper function which performs equivalent of the following::

          def helper(keyed_hmac, digest, rounds):
              accum = digest
              for _ in irange(rounds - 1):
                  digest = keyed_hmac(digest)
                  accum ^= digest
              return accum

        However, no efficient way to implement "bytes ^ bytes" in python.
        Instead, using approach where we dynamically compile a helper function based
        on digest size.  Instead of a single `accum` var, this helper breaks the digest
        into a series of integers.

        It stores these in a series of`accum_<i>` vars, and performs `accum ^= digest`
        by unpacking digest and perform xor for each "accum_<i> ^= digest_<i>".
        this keeps everything in locals, avoiding excessive list creation, encoding or decoding,
        etc.

        :param digest_size:
            digest size to compile for, in bytes. (must be multiple of 4).

        :return:
            helper function with call signature outlined above.
        iis=%dQs=%dQIiis=%dIsunsupported digest size: %dR`t
accum_varss, cs s|]}d|VqdS(sacc_%dN((RpR�((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pys	<genexpr>&stdigest_varscs s|]}d|VqdS(sdig_%dN((RpR�((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pys	<genexpr>'ss def helper(keyed_hmac, digest, rounds):
    '''pbkdf2 loop helper for digest_size={digest_size}'''
    unpack_digest = struct.unpack
    {accum_vars} = unpack_digest(digest)
    for _ in irange(1, rounds):
        digest = keyed_hmac(digest)
        {digest_vars} = unpack_digest(digest)
s        acc_%d ^= dig_%d
s%    return struct.pack({accum_vars})
s9<generated by passlib.crypto.digest._get_pbkdf2_looper()>texecRtstructthelper(t
_looper_cacheROt_have_64_bittNotImplementedErrorRtdicttjoinRR^tcompiletevalt
__source__(R`tcounttfmtR�ttdicttsourceR�tcodetgdicttldictR�((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR��sB








"		
	
thexlify(R�(tint_to_bytescC stS(N(R�(R`((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR�XscC snt}t||�d�}x=t|d�D]+}||�}|t||�d�N}q,Wt|t|��S(Nii(t_hexlifyR�RR�Rb(R�RMR�R�R�R(((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyR�[st
fastpbkdf2shashlib-sslsbuiltin-igffffff�?II����ll����(RR(RR(Rssha-1(Rssha-224ssha2-224(Rssha-256ssha2-256(Rssha-384ssha2-384(Rssha-512ssha2-512(smd4smd4(Rssha-0R(RR(R s
ripemd-160(sanys
from-bytes(sanysunpacks
from-bytes(sanyshexlify(KRHt
__future__RRtloggingt	getLoggerRFR3RRnRGtdebugRJtImportErrorR+tosR�RtwarningsRR�RltpasslibRt
passlib.utilsRRRR	R
tpasslib.utils.compatRRR
Rtpasslib.utils.decorRt__all__R�t
MAX_UINT64R"RNR<RKRURtcleartclear_cacheRRR�R~RRtpackR�tenvironRWt_force_backendt	functoolsR�R�R�t_builtin_backendR�R�R�RRtbinasciiR�R�R�tbtPBKDF2_BACKENDStPBKDF2_SPEED_FACTOR(((s9/usr/lib/python2.7/site-packages/passlib/crypto/digest.pyt<module>s�





("			@	/i#oP?h		
		f