
®Aj­§  ã            =   @   s	  d  Z  d d l m Z d d l m Z m Z m Z d d l m	 Z	 m
 Z
 y$ d d l m Z d d l m Z Wn2 e k
 r  d d l m Z d d l m Z Yn Xd d l m Z d d l m Z d d	 l Z d d	 l Z d d	 l Z e j e ƒ Z d d	 l Z d d	 l Z d d	 l Z d d	 l Z d d	 l Z e rjy d d	 l  Z  Wqve k
 rfd	 Z  d
 Z! YqvXn d d	 l  Z  d d	 l" Z" e  r”d d	 l# Z# y d d	 l$ Z$ Wn e k
 r¾d	 Z$ Yn Xd d	 l% Z% d d	 l& Z& d d l' m( Z( d d l) m* Z* m+ Z+ m, Z, m- Z- m. Z. m/ Z/ m0 Z0 m1 Z1 m2 Z2 m3 Z3 m4 Z4 m5 Z5 m6 Z6 d d l7 m8 Z8 m9 Z9 m: Z: m; Z; m< Z< d d l= m> Z> m? Z? d d l m@ Z@ mA ZA mB ZB mC ZC mD ZD mE ZE mF ZF mG ZG mH ZH mI ZI mJ ZJ mK ZK mL ZL mM ZM mN ZN mO ZO mP ZP d d d d d d d d d d d d d d d d d  d! d" d# d$ d% d& d' d( g ZQ eR e j eF rVe jS n e jT d) ƒ d* ƒ ZU d+ d, d- d. d/ d0 d1 g ZV d2 d3 g ZW d d4 l= mX ZX d5 ZY eG d6 ƒ ZZ eG d7 ƒ Z[ eR e j\ j] d8 ƒ pÙd9 ƒ Z^ Gd: d; „  d; e_ ƒ Z` eF r.e ja jb Zc ed ec e ja je g ƒ Zf d< d= „  Zg n d> d= „  Zg d	 d	 d? d	 d	 d? d@ dA „ Zh dB dC „  Zi dD d „  Zj ej Zk y d dE ll mm Zj Wn e k
 ržYn XdF dG dH „ Zn dI dJ d „ Zo e  d	 k rØdI dK d „ Zo dL d „  Zp eF rdM dN „  Zq dO dP „  Zr n. d dQ l ms Zs mt Zt dR dN „  Zq dS dP „  Zr e@ eq dT ƒ e@ er dU ƒ dV d „  Zu dW dX „  Zv dY dZ „  Zw d[ Zx eG d\ ƒ Zy d	 d] d^ „ Zz d_ d` „  Z{ da Z| e| j} db ƒ Z~ dc dd „  Z de d „  Z€ d¥ Z� eG dg ƒ Z‚ dh d „  Zƒ di dI d	 dj d „ Z„ di dI dk d „ Z… eF r+di dI dl d „ Z† n di dI dm d „ Z† e@ e† dn ƒ e8 do dp dq dr ƒ db ds dt „ ƒ Z‡ ed du jˆ ƒ  ƒ Z‰ ed dv jˆ ƒ  ƒ ZŠ ed d6 dw g ƒ Z‹ d	 dx dy dz „ ZŒ d{ d| „  Z� y d d} lŽ mŽ Z� Wn< e k
 rd	 Z� d? Z� d? Z‘ d? Z’ d	 Z“ d~ d „  Z” YnØ Xd Z� d\ Z• e$ raeP rad¦ e j– k oGd§ k n rae$ j— ƒ  Z“ d Z’ n d d‚ l m˜ Z˜ e˜ ƒ  Z“ d? Z’ eG dƒ ƒ Z™ eF rÚd Z‘ y e� d„ d… ƒ Wn eš k
 rÃd? Z‘ Yn Yn Xd† d „  Z” n d Z‘ d‡ d „  Z” e@ e” dˆ ƒ d‰ d „  Z› e% jœ Z� e� Zž dŠ d‹ „  ZŸ y e j  dŒ ƒ d Z¡ Wn e¢ k
 rQd? Z¡ Yn Xd	 d� dŽ „ Z£ e¡ rve j¤ ƒ  Z¥ n e j¦ e£ ƒ  ƒ Z¥ d� d" „  Z§ d� d# „  Z¨ d‘ Z© e8 do dr dq d’ d“ d” ƒ d• e© d– d$ „ ƒ Zª d¨ Z« d� d% „  Z¬ d© Z­ d¢ d& „  Z® d£ d' „  Z¯ d¤ d( „  Z° d	 S)ªz4passlib.utils -- helpers for writing password hashesé    )ÚJYTHON)Ú
b2a_base64Ú
a2b_base64ÚError)Ú	b64encodeÚ	b64decode)ÚSequence)ÚIterable)Úlookup)Úupdate_wrapperNznot present under Jython)Úwarn)ÚBASE64_CHARSÚ
AB64_CHARSÚHASH64_CHARSÚBCRYPT_CHARSÚBase64EngineÚLazyBase64EngineÚh64Úh64bigÚbcrypt64Úab64_encodeÚab64_decodeÚb64s_encodeÚb64s_decode)Údeprecated_functionÚdeprecated_methodÚmemoized_propertyÚclasspropertyÚhybrid_method)ÚExpectedStringErrorÚExpectedTypeError)Úadd_docÚ
join_bytesÚjoin_byte_valuesÚjoin_byte_elemsÚirangeÚimapÚPY3ÚuÚjoin_unicodeÚunicodeÚbyte_elem_valueÚ
nextgetterÚunicode_or_strÚunicode_or_bytes_typesÚget_method_functionÚsuppress_causeÚPYPYr   Úsys_bitsÚunix_crypt_schemesÚrounds_cost_valuesÚconsteqÚsaslprepÚ	xor_bytesÚrender_bytesÚis_same_codecÚis_ascii_safeÚto_bytesÚ
to_unicodeÚto_native_strÚ	has_cryptÚ
test_cryptÚ
safe_cryptÚtickÚrngÚgetrandbytesÚ
getrandstrÚgenerate_passwordÚis_crypt_handlerÚis_crypt_contextÚhas_rounds_infoÚhas_salt_infoé   g      ø?Zsha512_cryptZsha256_cryptZ
sha1_cryptZbcryptZ	md5_cryptZ
bsdi_cryptZ	des_cryptZlinearZlog2)ÚMissingBackendErroró    Ú ú ZPASSLIB_MAX_PASSWORD_SIZEi   c               @   sj   e  Z d  Z d Z d d „  Z d d „  Z d d „  Z d d	 „  Z d
 d „  Z d d „  Z	 d d „  Z
 d S)ÚSequenceMixinzƒ
    helper which lets result object act like a fixed-length sequence.
    subclass just needs to provide :meth:`_as_tuple()`.
    c             C   s   t  d ƒ ‚ d  S)Nzimplement in subclass)ÚNotImplementedError)Úself© rR   ú../../passlib/utils/__init__.pyÚ	_as_tuple—   s    zSequenceMixin._as_tuplec             C   s   t  |  j ƒ  ƒ S)N)ÚreprrT   )rQ   rR   rR   rS   Ú__repr__š   s    zSequenceMixin.__repr__c             C   s   |  j  ƒ  | S)N)rT   )rQ   ÚidxrR   rR   rS   Ú__getitem__�   s    zSequenceMixin.__getitem__c             C   s   t  |  j ƒ  ƒ S)N)ÚiterrT   )rQ   rR   rR   rS   Ú__iter__    s    zSequenceMixin.__iter__c             C   s   t  |  j ƒ  ƒ S)N)ÚlenrT   )rQ   rR   rR   rS   Ú__len__£   s    zSequenceMixin.__len__c             C   s   |  j  ƒ  | k S)N)rT   )rQ   ÚotherrR   rR   rS   Ú__eq__¦   s    zSequenceMixin.__eq__c             C   s   |  j  | ƒ S)N)r^   )rQ   r]   rR   rR   rS   Ú__ne__©   s    zSequenceMixin.__ne__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rT   rV   rX   rZ   r\   r^   r_   rR   rR   rR   rS   rO   ’   s   rO   c             C   se   t  j t |  ƒ ƒ j } | s" d S| j | ƒ } | rJ | j t k rJ d S| t | ƒ d j t k S)z*test if function accepts specified keywordFTé   éÿÿÿÿ)	ÚinspectZ	signaturer/   Z
parametersÚgetZkindÚ_VAR_ANY_SETÚlistÚ_VAR_KEYWORD)ÚfuncÚkeyZparamsÚargrR   rR   rS   Úaccepts_keyword³   s    rn   c             C   s1   t  j t |  ƒ ƒ } | | j k p0 | j d k	 S)z*test if function accepts specified keywordN)rf   Z
getargspecr/   ÚargsÚkeywords)rk   rl   ÚspecrR   rR   rS   rn   À   s    Fc                s°  t  | t ƒ r | g } t |  j ƒ } | r„ t  | t ƒ rE | g } x< | D]4 ‰  | rg ˆ  | k rg qL ˆ  | k rL | j ˆ  ƒ qL W| r—x
| D]‰  t ‡  f d d †  | Dƒ ƒ r¹ q‘ | rxÁ t | ƒ D]2 \ } }	 t ˆ  |	 ƒ rè P| rÌ t |	 | ƒ rÌ PqÌ Wt | ƒ } nr | r}xi t t	 | ƒ ƒ D]F \ }
 }	 t |	 | ƒ r*t | ƒ |
 } | | d |	 k sot
 ‚ Pq*Wd } n d } | j | ˆ  ƒ q‘ W| s¬t | ƒ |  _ d S)a  
    helper to update mixin classes installed in target class.

    :param target:
        target class whose bases will be modified.

    :param add:
        class / classes to install into target's base class list.

    :param remove:
        class / classes to remove from target's base class list.

    :param append:
        by default, prepends mixins to front of list.
        if True, appends to end of list instead.

    :param after:
        optionally make sure all mixins are inserted after
        this class / classes.

    :param before:
        optionally make sure all mixins are inserted before
        this class / classes.

    :param dryrun:
        optionally perform all calculations / raise errors,
        but don't actually modify the class.
    c             3   s   |  ] } t  | ˆ  ƒ Vq d  S)N)Ú
issubclass)Ú.0Úbase)ÚmixinrR   rS   ú	<genexpr>ö   s    z'update_mixin_classes.<locals>.<genexpr>rd   r   N)Ú
isinstanceÚtyperi   Ú	__bases__ÚremoveÚanyÚ	enumeraterr   r[   ÚreversedÚAssertionErrorÚinsertÚtuple)ÚtargetÚaddrz   ÚappendZbeforeÚafterZdryrunÚbasesrW   rt   Zend_idxrR   )ru   rS   Úupdate_mixin_classesÅ   sB    			r†   c             c   sï   | d k  r t  d ƒ ‚ t |  t ƒ rn t |  ƒ } d } x¯ | | k  rj | | } |  | | … V| } q< Wn} t |  t ƒ rß t |  ƒ } x_ t j | | ƒ } y t | ƒ } Wn t	 k
 rÃ PYn Xt j
 | f | ƒ VqŒ Wn t d ƒ ‚ d S)z8
    split iterable into chunks of <size> elements.
    rd   zsize must be positive integerr   zsource must be iterableN)Ú
ValueErrorrw   r   r[   r	   rY   Ú	itertoolsÚisliceÚnextÚStopIterationÚchainÚ	TypeError)ÚsourceÚsizeÚendÚiÚnZitrZ	chunk_itrÚfirstrR   rR   rS   Úbatch  s&    
r”   c             C   s)  t  |  t ƒ r3 t  | t ƒ s* t d ƒ ‚ d } n? t  |  t ƒ rf t  | t ƒ s] t d ƒ ‚ t } n t d ƒ ‚ t |  ƒ t | ƒ k } | rœ |  } d } | s® | } d } | rå xh t | | ƒ D] \ } } | | | AO} qÄ Wn: x7 t | | ƒ D]& \ } } | t | ƒ t | ƒ AO} qõ W| d k S)aç  Check two strings/bytes for equality.

    This function uses an approach designed to prevent
    timing analysis, making it appropriate for cryptography.
    a and b must both be of the same type: either str (ASCII only),
    or any type that supports the buffer protocol (e.g. bytes).

    Note: If a and b are of different lengths, or if an error occurs,
    a timing attack could theoretically reveal information about the
    types and lengths of a and b--but not their values.
    z)inputs must be both unicode or both bytesFr   rd   )rw   r*   r�   Úbytesr'   r[   ÚzipÚord)ÚleftÚrightZis_py3_bytesZ	same_sizeZtmpÚresultÚlÚrrR   rR   rS   r5   ;  s,    		)Úcompare_digestú,c             C   sO   |  j  ƒ  }  |  j | ƒ r+ |  d d … }  |  s5 g  Sd d „  |  j | ƒ Dƒ S)zRsplit comma-separated string into list of elements,
    stripping whitespace.
    Nrd   c             S   s   g  |  ] } | j  ƒ  ‘ q SrR   )Ústrip)rs   ÚelemrR   rR   rS   ú
<listcomp>�  s   	 zsplitcomma.<locals>.<listcomp>re   )rŸ   ÚendswithÚsplit)rŽ   ÚseprR   rR   rS   Ú
splitcomma†  s    r¥   Úvaluec                ss  t  |  t ƒ s( t d t |  ƒ f ƒ ‚ t j ‰ t j ‰  t ‡  ‡ f d d †  |  Dƒ ƒ } t j	 d | ƒ } | sx t
 St j } | | d ƒ r½ | | d ƒ s± t d | ƒ ‚ t j } n | } t j } t j } t j } t j } t j }	 t j }
 t j } t j } t j } xX| D]P} ˆ  | ƒ s:t d ƒ ‚ ˆ | ƒ sSt d	 ƒ ‚ | | ƒ rot d
 | ƒ ‚ | | ƒ r‹t d | ƒ ‚ | | ƒ r§t d | ƒ ‚ | | ƒ rÃt d | ƒ ‚ |	 | ƒ rßt d | ƒ ‚ |
 | ƒ rût d | ƒ ‚ | | ƒ rt d | ƒ ‚ | | ƒ r3t d | ƒ ‚ | | ƒ rOt d | ƒ ‚ | | ƒ rt d | ƒ ‚ qW| S)a  Normalizes unicode strings using SASLPrep stringprep profile.

    The SASLPrep profile is defined in :rfc:`4013`.
    It provides a uniform scheme for normalizing unicode usernames
    and passwords before performing byte-value sensitive operations
    such as hashing. Among other things, it normalizes diacritic
    representations, removes non-printing characters, and forbids
    invalid characters such as ``\n``. Properly internationalized
    applications should run user passwords through this function
    before hashing.

    :arg source:
        unicode string to normalize & validate

    :param param:
        Optional noun identifying source parameter in error messages
        (Defaults to the string ``"value"``). This is mainly useful to make the caller's error
        messages make more sense contextually.

    :raises ValueError:
        if any characters forbidden by the SASLPrep profile are encountered.

    :raises TypeError:
        if input is not :class:`!unicode`

    :returns:
        normalized unicode string

    .. note::

        This function is not available under Jython,
        as the Jython stdlib is missing the :mod:`!stringprep` module
        (`Jython issue 1758320 <http://bugs.jython.org/issue1758320>`_).

    .. versionadded:: 1.6
    z$input must be unicode string, not %sc             3   s3   |  ]) } ˆ  | ƒ s ˆ | ƒ r' t  n | Vq d  S)N)Ú_USPACE)rs   Úc)Úin_table_b1Úin_table_c12rR   rS   rv   Ç  s   zsaslprep.<locals>.<genexpr>ZNFKCr   rd   zmalformed bidi sequence in z$failed to strip B.1 in mapping stagez(failed to replace C.1.2 in mapping stagez$unassigned code points forbidden in z control characters forbidden in z$private use characters forbidden in z"non-char code points forbidden in zsurrogate codes forbidden in z!non-plaintext chars forbidden in z!non-canonical chars forbidden in z1display-modifying / deprecated chars forbidden inztagged characters forbidden in zforbidden bidi character in re   )rw   r*   r�   rx   Ú
stringpreprª   r©   r)   ÚunicodedataZ	normalizeÚ_UEMPTYZin_table_d1r‡   Zin_table_d2Úin_table_a1Úin_table_c21_c22Úin_table_c3Úin_table_c4Úin_table_c5Úin_table_c6Úin_table_c7Úin_table_c8Úin_table_c9r~   )rŽ   ÚparamÚdataZis_ral_charZis_forbidden_bidi_charr®   r¯   r°   r±   r²   r³   r´   rµ   r¶   r¨   rR   )r©   rª   rS   r6   ‘  sf    ,												
c             C   s   t  d t ƒ ‚ d S)zstub for saslprep()z>saslprep() support requires the 'stringprep' module, which is N)rP   Ú_stringprep_missing_reason)rŽ   r·   rR   rR   rS   r6     s    c             G   sH   t  |  t ƒ r |  j d ƒ }  |  t d d „  | Dƒ ƒ } | j d ƒ S)a   Peform ``%`` formating using bytes in a uniform manner across Python 2/3.

    This function is motivated by the fact that
    :class:`bytes` instances do not support ``%`` or ``{}`` formatting under Python 3.
    This function is an attempt to provide a replacement:
    it converts everything to unicode (decoding bytes instances as ``latin-1``),
    performs the required formatting, then encodes the result to ``latin-1``.

    Calling ``render_bytes(source, *args)`` should function roughly the same as
    ``source % args`` under Python 2.

    .. todo::
        python >= 3.5 added back limited support for bytes %,
        can revisit when 3.3/3.4 is dropped.
    zlatin-1c             s   s3   |  ]) } t  | t ƒ r' | j d  ƒ n | Vq d S)zlatin-1N)rw   r•   Údecode)rs   rm   rR   rR   rS   rv   ,  s   zrender_bytes.<locals>.<genexpr>)rw   r•   rº   r€   Úencode)rŽ   ro   rš   rR   rR   rS   r8     s
    c             C   s   t  j |  d ƒ S)NÚbig)ÚintÚ
from_bytes)r¦   rR   rR   rS   Úbytes_to_int2  s    r¿   c             C   s   |  j  | d ƒ S)Nr¼   )r;   )r¦   ÚcountrR   rR   rS   Úint_to_bytes4  s    rÁ   )ÚhexlifyÚ	unhexlifyc             C   s   t  t |  ƒ d ƒ S)Né   )r½   rÂ   )r¦   rR   rR   rS   r¿   9  s    c             C   s   t  d | d >|  ƒ S)Nz%%0%dxrd   )rÃ   )r¦   rÀ   rR   rR   rS   rÁ   ;  s    z/decode byte string as single big-endian integerz/encode integer as single big-endian byte stringc             C   s#   t  t |  ƒ t | ƒ At |  ƒ ƒ S)z;Perform bitwise-xor of two byte strings (must be same size))rÁ   r¿   r[   )r˜   r™   rR   rR   rS   r7   A  s    c             C   s*   d | d t  |  ƒ } |  | d | … S)zE
    repeat or truncate <source> string, so it has length <size>
    rd   N)r[   )rŽ   r�   ÚmultrR   rR   rS   Úrepeat_stringE  s    rÆ   c             C   s)   d | d t  |  ƒ } t |  | | ƒ S)zN
    variant of repeat_string() which truncates to nearest UTF8 boundary.
    rd   )r[   Úutf8_truncate)rŽ   r�   rÅ   rR   rR   rS   Úutf8_repeat_stringM  s    rÈ   s    ú c             C   sa   t  |  ƒ } | | k rO | d k r? t |  t ƒ r9 t n t } |  | | | S|  d | … Sd S)z>right-pad or truncate <source> string, so it has length <size>N)r[   rw   r*   Ú_UNULLÚ_BNULL)rŽ   r�   ZpadZcurrR   rR   rS   Úright_pad_stringX  s    rÌ   c                sñ   t  ˆ t ƒ s! t ˆ t d ƒ ‚ t ˆ ƒ } | d k  rL t d | | ƒ } | | k r\ ˆ St | d | ƒ } xG | | k  r¦ t ˆ | ƒ d @d k r™ P| d 7} qr W| | k s¹ t ‚ ˆ d | … ‰  ‡  ‡ f d d	 †  } | ƒ  sí t ‚ ˆ  S)
aÃ  
    helper to truncate UTF8 byte string to nearest character boundary ON OR AFTER <index>.
    returned prefix will always have length of at least <index>, and will stop on the
    first byte that's not a UTF8 continuation byte (128 - 191 inclusive).
    since utf8 should never take more than 4 bytes to encode known unicode values,
    we can stop after ``index+3`` is reached.

    :param bytes source:
    :param int index:
    :rtype: bytes
    rŽ   r   é   éÀ   é€   rd   Nc                 sN   y ˆ j  d ƒ }  Wn t k
 r+ d SYn X|  j ˆ  j  d ƒ ƒ sJ t ‚ d S)Nzutf-8T)rº   ÚUnicodeDecodeErrorÚ
startswithr~   )Útext)rš   rŽ   rR   rS   Úsanity_check–  s    	z#utf8_truncate.<locals>.sanity_check)rw   r•   r    r[   ÚmaxÚminr+   r~   )rŽ   Úindexr�   rÓ   rR   )rš   rŽ   rS   rÇ   c  s"    rÇ   s	    
 aA:#!Úasciic             C   s   t  j |  ƒ t k S)zRTest if codec is compatible with 7-bit ascii (e.g. latin-1, utf-8; but not utf-16))Ú_ASCII_TEST_UNICODEr»   Ú_ASCII_TEST_BYTES)ÚcodecrR   rR   rS   Úis_ascii_codec¬  s    rÛ   c             C   s<   |  | k r d S|  o | s  d St  |  ƒ j t  | ƒ j k S)z3Check if two codec names are aliases for same codecTF)Ú_lookup_codecÚname)r˜   r™   rR   rR   rS   r9   °  s
    s   €õ   Â€c                s8   t  |  t ƒ r t n t ‰  t ‡  f d d †  |  Dƒ ƒ S)z<Check if string (bytes or unicode) contains only 7-bit asciic             3   s   |  ] } | ˆ  k  Vq d  S)NrR   )rs   r¨   )rœ   rR   rS   rv   ½  s    z is_ascii_safe.<locals>.<genexpr>)rw   r•   Ú_B80Ú_U80Úall)rŽ   rR   )rœ   rS   r:   º  s    zutf-8c             C   s}   | s t  ‚ t |  t ƒ rN | rG t | | ƒ rG |  j | ƒ j | ƒ S|  Sn+ t |  t ƒ rj |  j | ƒ St |  | ƒ ‚ d S)a  Helper to normalize input to bytes.

    :arg source:
        Source bytes/unicode to process.

    :arg encoding:
        Target encoding (defaults to ``"utf-8"``).

    :param param:
        Optional name of variable/noun to reference when raising errors

    :param source_encoding:
        If this is specified, and the source is bytes,
        the source will be transcoded from *source_encoding* to *encoding*
        (via unicode).

    :raises TypeError: if source is not unicode or bytes.

    :returns:
        * unicode strings will be encoded using *encoding*, and returned.
        * if *source_encoding* is not specified, byte strings will be
          returned unchanged.
        * if *source_encoding* is specified, byte strings will be transcoded
          to *encoding*.
    N)r~   rw   r•   r9   rº   r»   r*   r   )rŽ   Úencodingr·   Zsource_encodingrR   rR   rS   r;   ¿  s    c             C   sN   | s t  ‚ t |  t ƒ r |  St |  t ƒ r; |  j | ƒ St |  | ƒ ‚ d S)a¼  Helper to normalize input to unicode.

    :arg source:
        source bytes/unicode to process.

    :arg encoding:
        encoding to use when decoding bytes instances.

    :param param:
        optional name of variable/noun to reference when raising errors.

    :raises TypeError: if source is not unicode or bytes.

    :returns:
        * returns unicode strings unchanged.
        * returns bytes strings decoded using *encoding*
    N)r~   rw   r*   r•   rº   r   )rŽ   râ   r·   rR   rR   rS   r<   ä  s    c             C   sB   t  |  t ƒ r |  j | ƒ St  |  t ƒ r/ |  St |  | ƒ ‚ d  S)N)rw   r•   rº   r*   r   )rŽ   râ   r·   rR   rR   rS   r=   ÿ  s
    c             C   sB   t  |  t ƒ r |  St  |  t ƒ r/ |  j | ƒ St |  | ƒ ‚ d  S)N)rw   r•   r*   r»   r   )rŽ   râ   r·   rR   rR   rS   r=     s
    a>  Take in unicode or bytes, return native string.

    Python 2: encodes unicode using specified encoding, leaves bytes alone.
    Python 3: leaves unicode alone, decodes bytes using specified encoding.

    :raises TypeError: if source is not unicode or bytes.

    :arg source:
        source unicode or bytes string.

    :arg encoding:
        encoding to use when encoding unicode or decoding bytes.
        this defaults to ``"utf-8"``.

    :param param:
        optional name of variable/noun to reference when raising errors.

    :returns: :class:`str` instance
    Z
deprecatedz1.6Zremovedz1.7c             C   s   t  |  | d d ƒS)z'deprecated, use to_native_str() insteadr·   Úhash)r=   )rŽ   râ   rR   rR   rS   Úto_hash_str$  s    rä   z true t yes y on 1 enable enabledz#false f no n off 0 disable disabledÚnoneZbooleanc             C   s­   | d k s t  ‚ t |  t ƒ r| |  j ƒ  j ƒ  } | t k rC d S| t k rS d S| t k rc | St d | |  f ƒ ‚ n- t |  t	 ƒ r� |  S|  d k rŸ | St	 |  ƒ Sd S)z\
    helper to convert value to boolean.
    recognizes strings such as "true", "false"
    TFNzunrecognized %s value: %r)TFN)
r~   rw   r.   ÚlowerrŸ   Ú	_true_setÚ
_false_setÚ	_none_setr‡   Úbool)r¦   rå   r·   ZcleanrR   rR   rS   Úas_bool-  s    rë   c             C   sL   t  s t |  t ƒ r d Sy |  j d ƒ d SWn t k
 rG d SYn Xd S)zƒ
    UT helper --
    test if value is safe to pass to crypt.crypt();
    under PY3, can't pass non-UTF8 bytes to crypt.crypt.
    Tzutf-8FN)Úcrypt_accepts_bytesrw   r•   rº   rÐ   )r¦   rR   rR   rS   Úis_safe_crypt_inputG  s    rí   )Úcryptc             C   s   d  S)NrR   )Úsecretrã   rR   rR   rS   r@   ]  s    Té   rÍ   )Únullcontextz*:!s   îZxxc             C   sl  t  r] t |  t ƒ r$ |  j d ƒ }  t |  k r< t d ƒ ‚ t | t ƒ rõ | j d ƒ } n˜ t |  t ƒ r¿ |  } y |  j d ƒ }  Wn t k
 r� d  SYn X|  j d ƒ | k s¿ t	 d ƒ ‚ t
 |  k r× t d ƒ ‚ t | t ƒ rõ | j d ƒ } y! t � t |  | ƒ } Wd  QRXWn t k
 r.d  SYn Xt | t ƒ rM| j d ƒ } | sd| d t k rhd  S| S)Nzutf-8znull character in secretr×   z"utf-8 spec says this can't happen!r   )rì   rw   r*   r»   rË   r‡   r•   rº   rÐ   r~   Ú_NULLÚ_safe_crypt_lockÚ_cryptÚOSErrorÚ_invalid_prefixes)rï   rã   Zorigrš   rR   rR   rS   r@   ˆ  s:    			c          
   C   s¢   t  |  t ƒ r |  j d ƒ }  t |  k r6 t d ƒ ‚ t  | t ƒ rT | j d ƒ } t � t |  | ƒ } Wd  QRX| s{ d  S| j d ƒ } | d t k rž d  S| S)Nzutf-8znull character in secretr×   r   )	rw   r*   r»   rò   r‡   ró   rô   rº   rö   )rï   rã   rš   rR   rR   rS   r@   º  s    aì  Wrapper around stdlib's crypt.

    This is a wrapper around stdlib's :func:`!crypt.crypt`, which attempts
    to provide uniform behavior across Python 2 and 3.

    :arg secret:
        password, as bytes or unicode (unicode will be encoded as ``utf-8``).

    :arg hash:
        hash or config string, as ascii bytes or unicode.

    :returns:
        resulting hash as ascii unicode; or ``None`` if the password
        couldn't be hashed due to one of the issues:

        * :func:`crypt()` not available on platform.

        * Under Python 3, if *secret* is specified as bytes,
          it must be use ``utf-8`` or it can't be passed
          to :func:`crypt()`.

        * Some OSes will return ``None`` if they don't recognize
          the algorithm being used (though most will simply fall
          back to des-crypt).

        * Some OSes will return an error string if the input config
          is recognized but malformed; current code converts these to ``None``
          as well.
    c             C   sJ   t  | t ƒ s% t d t | ƒ ƒ ‚ | s7 t d ƒ ‚ t |  | ƒ | k S)z°check if :func:`crypt.crypt` supports specific hash
    :arg secret: password to test
    :arg hash: known hash of password to use as reference
    :returns: True or False
    z#hash must be unicode_or_str, got %szhash must be non-empty)rw   r-   r~   rx   r@   )rï   rã   rR   rR   rS   r?   è  s    
c             C   sE   t  j d |  ƒ } | rA t d d „  | j d ƒ j d ƒ Dƒ ƒ Sd S)zhelper to parse version stringz(\d+(?:\.\d+)+)c             s   s   |  ] } t  | ƒ Vq d  S)N)r½   )rs   r    rR   rR   rS   rv   ÿ  s    z parse_version.<locals>.<genexpr>rd   Ú.N)ÚreÚsearchr€   Úgroupr£   )rŽ   ÚmrR   rR   rS   Úparse_versionû  s    )rü   rd   c             C   sñ   d d l  m } t |  d ƒ rb t |  d ƒ rb y |  j ƒ  }  Wn! t k
 ra |  j d ƒ }  Yn Xt d ƒ |  t t d ƒ r‰ t j ƒ  n d	 t	 t
 ƒ  ƒ t j ƒ  t ƒ  t rÅ t j d
 ƒ j d ƒ n d f } t | | j d ƒ ƒ j ƒ  d ƒ S)z.generate prng seed value from system resourcesr   )Úsha512ÚgetstateÚgetrandbitsrd   é   z%s %s %s %.15f %.15f %sÚgetpidNé    zlatin-1zutf-8rÄ   i €  )Zhashlibrý   Úhasattrrþ   rP   rÿ   r(   Úosr  ÚidÚobjectÚtimerA   Úhas_urandomÚurandomrº   r½   r»   Z	hexdigest)r¦   rý   rÒ   rR   rR   rS   Úgenseed  s    		(r
  c                s,   ˆ  s
 t  S‡  ‡ f d d †  } t | ƒ  ƒ S)z]return byte-string containing *count* number of randomly generated bytes, using specified rngc              3   sM   ˆ j  ˆ  d >ƒ }  d } x- | ˆ  k  rH |  d @V|  d L}  | d 7} q Wd  S)NrÍ   r   éÿ   rd   )rÿ   )r¦   r‘   )rÀ   rB   rR   rS   ÚhelperM  s    	
zgetrandbytes.<locals>.helper)Ú_BEMPTYr#   )rB   rÀ   r  rR   )rÀ   rB   rS   rC   B  s    	c                s˜   ˆ d k  r t  d ƒ ‚ t ˆ  ƒ ‰ ˆ d k r< t  d ƒ ‚ ˆ d k rP ˆ  ˆ S‡  ‡ ‡ ‡ f d d †  } t ˆ  t ƒ r‡ t | ƒ  ƒ St | ƒ  ƒ Sd S)z|return string containing *count* number of chars/bytes, whose elements are drawn from specified charset, using specified rngr   zcount must be >= 0zalphabet must not be emptyrd   c              3   sT   ˆ j  d ˆ ˆ ƒ }  d } x1 | ˆ k  rO ˆ  |  ˆ V|  ˆ }  | d 7} q Wd  S)Nr   rd   )Z	randrange)r¦   r‘   )ÚcharsetrÀ   ÚlettersrB   rR   rS   r  f  s    
zgetrandstr.<locals>.helperN)r‡   r[   rw   r*   r)   r$   )rB   r  rÀ   r  rR   )r  rÀ   r  rB   rS   rD   W  s    	Z42346789ABCDEFGHJKMNPQRTUVWXYZabcdefghjkmnpqrstuvwxyzz2.0Zreplacementz/passlib.pwd.genword() / passlib.pwd.genphrase()é
   c             C   s   t  t | |  ƒ S)aw  generate random password using given length & charset

    :param size:
        size of password.

    :param charset:
        optional string specified set of characters to draw from.

        the default charset contains all normal alphanumeric characters,
        except for the characters ``1IiLl0OoS5``, which were omitted
        due to their visual similarity.

    :returns: :class:`!str` containing randomly generated password.

    .. note::

        Using the default character set, on a OS with :class:`!SystemRandom` support,
        this function should generate passwords with 5.7 bits of entropy per character.
    )rD   rB   )r�   r  rR   rR   rS   rE   v  s    rÝ   Úsetting_kwdsÚcontext_kwdsÚverifyrã   Úidentifyc                s   t  ‡  f d d †  t Dƒ ƒ S)z4check if object follows the :ref:`password-hash-api`c             3   s   |  ] } t  ˆ  | ƒ Vq d  S)N)r  )rs   rÝ   )ÚobjrR   rS   rv   š  s    z#is_crypt_handler.<locals>.<genexpr>)rá   Ú_handler_attrs)r  rR   )r  rS   rF   —  s    Úneeds_updateÚ	genconfigÚgenhashÚencryptc                s   t  ‡  f d d †  t Dƒ ƒ S)zOcheck if object appears to be a :class:`~passlib.context.CryptContext` instancec             3   s   |  ] } t  ˆ  | ƒ Vq d  S)N)r  )rs   rÝ   )r  rR   rS   rv   ¥  s    z#is_crypt_context.<locals>.<genexpr>)rá   Ú_context_attrs)r  rR   )r  rS   rG   ¢  s    c             C   s%   d |  j  k o$ t |  d d ƒ d k	 S)z_check if handler provides the optional :ref:`rounds information <rounds-attributes>` attributesÚroundsZ
min_roundsN)r  Úgetattr)ÚhandlerrR   rR   rS   rH   ¬  s    c             C   s%   d |  j  k o$ t |  d d ƒ d k	 S)z[check if handler provides the optional :ref:`salt information <salt-attributes>` attributesZsaltZmin_salt_sizeN)r  r  )r  rR   rR   rS   rI   ±  s    rÏ   )rð   rJ   r   )rð   rÍ   rÍ   )rÝ   r  r  r  rã   r  )r  r  r  r  r  r  )±rc   Úpasslib.utils.compatr   Zbinasciir   r   r   Z_BinAsciiErrorÚbase64r   r   Úcollections.abcr   r	   ÚImportErrorÚcollectionsÚcodecsr
   rÜ   Ú	functoolsr   rˆ   rf   ÚloggingÚ	getLoggerr`   ÚlogZmathr  ÚsysZrandomrø   r«   r¹   r  r¬   Ú	threadingZtimeitÚtypesÚwarningsr   Zpasslib.utils.binaryr   r   r   r   r   r   r   r   r   r   r   r   r   Zpasslib.utils.decorr   r   r   r   r   Zpasslib.excr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   Ú__all__r½   ÚmaxsizeZmaxintr2   r3   r4   rK   r  r­   r§   Úenvironrg   ZMAX_PASSWORD_SIZEr  rO   Z	ParameterZVAR_KEYWORDrj   ÚsetZVAR_POSITIONALrh   rn   r†   r”   r5   Zstr_consteqZhmacr�   r¥   r6   r8   r¿   rÁ   rÂ   rÃ   r7   rÆ   rÈ   rË   rÊ   rÌ   rÇ   rÙ   rº   rØ   rÛ   r9   rß   rà   r:   r;   r<   r=   rä   r£   rç   rè   ré   rë   rí   rî   rô   r>   rì   Zcrypt_needs_lockró   r@   rò   Zpypy_version_infoÚLockrñ   rö   r�   r?   Zdefault_timerZtimerrA   rü   r	  r  rP   r
  ZSystemRandomrB   ZRandomrC   rD   Z
_52charsetrE   r  rF   r  rG   rH   rI   rR   rR   rR   rS   Ú<module>   s‚   X(p	.	V>€F%+		
/	
!    
