
    TfD                        d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
mZmZ ddlmZ ddlmZ d	Z ej        e Zd
ZdZej        dk    rd Znd Zej        dk     rd Znd Zd Zd+dZ G d d          Zd Zd Zd ZefdZefdZ d Z!d Z"d Z#d Z$d Z%d  Z&d! Z'd" Z(d# Z)d$ Z*d% Z+ G d& d'e,          Z-d( Z.d) Z/d* Z0dS ),a  
This module includes some utility functions.

The methods most typically used are the sigencode and sigdecode functions
to be used with :func:`~ecdsa.keys.SigningKey.sign` and
:func:`~ecdsa.keys.VerifyingKey.verify`
respectively. See the :func:`sigencode_strings`, :func:`sigdecode_string`,
:func:`sigencode_der`, :func:`sigencode_strings_canonize`,
:func:`sigencode_string_canonize`, :func:`sigencode_der_canonize`,
:func:`sigdecode_strings`, :func:`sigdecode_string`, and
:func:`sigdecode_der` functions.
    )divisionN)sha256)PY2int2bytenext   )der)normalise_bytes)r      iH  i='  r   r   )r         r      )r   r   r   r      )r   c                     t          t                              | d                    dd                             t	          |           dz            S )-Convert a bytestring to string of 0's and 1'sbigr   N   )binint
from_byteszfilllenent_256s    </var/www/html/env/lib/python3.11/site-packages/ecdsa/util.pyentropy_to_bitsr   4   s@    3>>'511221226<<S\\A=MNNN    c                 @    d                     d | D                       S )r    c              3      K   | ];}t          t          |                    d d                             d          V  <dS )r   Nr   )r   ordr   ).0xs     r   	<genexpr>z"entropy_to_bits.<locals>.<genexpr><   sD      AAAs3q66{{122,,Q//AAAAAAr   )joinr   s    r   r   r   :   s#    wwAAAAAAAAr   )r      c                 @    t          t          |                     dz
  S )Nr   )r   r   r#   s    r   
bit_lengthr)   A   s    3q66{{Qr   c                 .    |                                  pdS Nr   )r)   r(   s    r   r)   r)   F   s    ||~~""r   c                 2    dt          d| z            z   dz  S )Nr   z%xr   )r   )orders    r   orderlenr.   J   s    D5L!!!a''r   c                     | dk    sJ |t           j        }t          | dz
            }|dz  dz   }	  ||          }t          |          }t	          |d|         d          dz   }d|cxk     r| k     rn n|S I)a  Return a random integer k such that 1 <= k < order, uniformly
    distributed across that range. Worst case should be a mean of 2 loops at
    (2**k)+2.

    Note that this function is not declared to be forwards-compatible: we may
    change the behavior in future releases. The entropy= argument (which
    should get a callable that behaves like os.urandom) can be used to
    achieve stability within a given release (for repeatable unit tests), but
    should not be used as a long-term-compatible key generation algorithm.
    r   Nr   r   T)baser   )osurandomr)   r   r   )r-   entropyupper_2	upper_256r   ent_2rand_nums          r   	randranger8   N   s     19999*##G1q I')$$((uXgXQ///!3x%Or   c                        e Zd Zd Zd Zd ZdS )PRNGc                 :    |                      |          | _        d S N)block_generator	generator)selfseeds     r   __init__zPRNG.__init__l   s    --d33r   c                       fdt          |          D             }t          rd                    |          S t          |          S )Nc                 8    g | ]}t          j                  S  )r   r>   )r"   ir?   s     r   
<listcomp>z!PRNG.__call__.<locals>.<listcomp>p   s#    ;;;aT$.!!;;;r   r   )ranger   r%   bytes)r?   numbytesas   `  r   __call__zPRNG.__call__o   sE    ;;;;5??;;; 	771::88Or   c              #      K   d}	 t          d||fz                                                                            D ]}|V  |dz  }E)Nr   Tz
prng-%d-%sr   )r   encodedigest)r?   r@   counterbytes       r   r=   zPRNG.block_generatorw   se      	$/7799 fhh  



qLG	r   N)__name__
__module____qualname__rA   rK   r=   rD   r   r   r:   r:   f   sA        4 4 4      r   r:   c                      t          |           dt          |          z            }t          t          j        |          d          |dz
  z  dz   }d|cxk    r|k     sn J d||f            |S )Nr      r   )r:   r.   r   binasciihexlify)r@   r-   r0   numbers       r   %randrange_from_seed__overshoot_modulorY      s     4::a(5//)**D("4(("--;q@FFE 2Mr   c                     d| z  dz
  S r+   rD   )numbitss    r   lsb_of_onesr\      s    LAr   c                 p    t          t          j        | dz
  d          dz             }|dz  }|dz  }|||fS )Nr   r   r   )r   mathlog)r-   bitsrH   	extrabitss       r   bits_and_bytesrb      sC    tx	1%%)**DAIEqI	!!r   c                     t          |          \  }}}|r|dz  } ||                                           d |         }d|t          |          z
  z  |z   }dt          t	          j        |          d          z   }d|cxk    r|k     sn J |S )Nr    rU   )rb   rN   r   r   rV   rW   )r@   r-   hashmodr`   _bytesra   r0   rX   s           r   #randrange_from_seed__truncate_bytesrg      s     -U33D&) !74==!!'6'*DVc$ii'(4/DX%d++R000FMr   c                    t          t          j        |dz
  d          dz             }|dz   dz  } ||                                           d |         }d|t	          |          z
  z  |z   }d|z  |z
  }|r=t          t          |d                   t          |          z            |dd          z   }dt          t          j	        |          d          z   }d|cxk    r|k     sn J |S )Nr   r   r&   r   rd   r   rU   )
r   r^   r_   rN   r   r   r!   r\   rV   rW   )r@   r-   re   r`   maxbytesr0   topbitsrX   s           r   "randrange_from_seed__truncate_bitsrk      s     tx	1%%)**DqQH74==!!)8),DXD		)*T1D(lT!G HDG{7';';;<<tABBxGX%d++R000FMr   c                 ,   |dk    sJ t          |          \  }}}t          |           }	 d}|r5t          t           |d                    t	          |          z            }t          | ||          z             dz   }d|cxk    r|k     rn n|S j)Nr   Tr   )rb   r:   r   r!   r\   string_to_number)r@   r-   r`   rH   ra   generate	extrabyteguesss           r    randrange_from_seed__trytryagainrq      s     19999+E22D%DzzH	 	L XXa[[!1!1K	4J4J!JKKI XXe__!<==ALr   c                     t          |          }dt          d|z            z   dz   }t          j        || z                                            }t          |          |k    sJ t          |          |f            |S Nz%0r   r#   )r.   strrV   	unhexlifyrM   r   numr-   lfmt_strstrings        r   number_to_stringr{      su    ASQZZ#%G3 6 6 8 899Fv;;!c&kk1-Mr   c                     t          |          }dt          d|z            z   dz   }t          j        || z                                            }|d |         S rs   )r.   rt   rV   ru   rM   rv   s        r   number_to_string_cropr}      sT    ASQZZ#%G3 6 6 8 899F"1":r   c                 F    t          t          j        |           d          S NrU   )r   rV   rW   )rz   s    r   rm   rm      s    x'',,,r   c                     t          |          }t          |           |k    sJ t          |           |f            t          t          j        |           d          S r   )r.   r   r   rV   rW   )rz   r-   rx   s      r   string_to_number_fixedlenr      sR    Av;;!c&kk1-x'',,,r   c                 J    t          | |          }t          ||          }||fS )aZ  
    Encode the signature to a pair of strings in a tuple

    Encodes signature into raw encoding (:term:`raw encoding`) with the
    ``r`` and ``s`` parts of the signature encoded separately.

    It's expected that this function will be used as a ``sigencode=`` parameter
    in :func:`ecdsa.keys.SigningKey.sign` method.

    :param int r: first parameter of the signature
    :param int s: second parameter of the signature
    :param int order: the order of the curve over which the signature was
        computed

    :return: raw encoding of ECDSA signature
    :rtype: tuple(bytes, bytes)
    )r{   rsr-   r_strs_strs        r   sigencode_stringsr      s,    $ Q&&EQ&&E5>r   c                 4    t          | ||          \  }}||z   S )a  
    Encode the signature to raw format (:term:`raw encoding`)

    It's expected that this function will be used as a ``sigencode=`` parameter
    in :func:`ecdsa.keys.SigningKey.sign` method.

    :param int r: first parameter of the signature
    :param int s: second parameter of the signature
    :param int order: the order of the curve over which the signature was
        computed

    :return: raw encoding of ECDSA signature
    :rtype: bytes
    r   r   s        r   sigencode_stringr     s#    " %Q511LE55=r   c                 t    t          j        t          j        |           t          j        |                    S )a  
    Encode the signature into the ECDSA-Sig-Value structure using :term:`DER`.

    Encodes the signature to the following :term:`ASN.1` structure::

        Ecdsa-Sig-Value ::= SEQUENCE {
            r       INTEGER,
            s       INTEGER
        }

    It's expected that this function will be used as a ``sigencode=`` parameter
    in :func:`ecdsa.keys.SigningKey.sign` method.

    :param int r: first parameter of the signature
    :param int s: second parameter of the signature
    :param int order: the order of the curve over which the signature was
        computed

    :return: DER encoding of ECDSA signature
    :rtype: bytes
    )r	   encode_sequenceencode_integerr   r   r-   s      r   sigencode_derr     s-    , s1!44c6H6K6KLLLr   c                 @    ||dz  k    r||z
  }t          | ||          S )a  
    Encode the signature to a pair of strings in a tuple

    Encodes signature into raw encoding (:term:`raw encoding`) with the
    ``r`` and ``s`` parts of the signature encoded separately.

    Makes sure that the signature is encoded in the canonical format, where
    the ``s`` parameter is always smaller than ``order / 2``.
    Most commonly used in bitcoin.

    It's expected that this function will be used as a ``sigencode=`` parameter
    in :func:`ecdsa.keys.SigningKey.sign` method.

    :param int r: first parameter of the signature
    :param int s: second parameter of the signature
    :param int order: the order of the curve over which the signature was
        computed

    :return: raw encoding of ECDSA signature
    :rtype: tuple(bytes, bytes)
    r   r   r   s      r   sigencode_strings_canonizer   3  s,    , 	519}}AIQ5)))r   c                 @    ||dz  k    r||z
  }t          | ||          S )aw  
    Encode the signature to raw format (:term:`raw encoding`)

    Makes sure that the signature is encoded in the canonical format, where
    the ``s`` parameter is always smaller than ``order / 2``.
    Most commonly used in bitcoin.

    It's expected that this function will be used as a ``sigencode=`` parameter
    in :func:`ecdsa.keys.SigningKey.sign` method.

    :param int r: first parameter of the signature
    :param int s: second parameter of the signature
    :param int order: the order of the curve over which the signature was
        computed

    :return: raw encoding of ECDSA signature
    :rtype: bytes
    r   )r   r   s      r   sigencode_string_canonizer   N  s,    & 	519}}AIAq%(((r   c                 @    ||dz  k    r||z
  }t          | ||          S )a9  
    Encode the signature into the ECDSA-Sig-Value structure using :term:`DER`.

    Makes sure that the signature is encoded in the canonical format, where
    the ``s`` parameter is always smaller than ``order / 2``.
    Most commonly used in bitcoin.

    Encodes the signature to the following :term:`ASN.1` structure::

        Ecdsa-Sig-Value ::= SEQUENCE {
            r       INTEGER,
            s       INTEGER
        }

    It's expected that this function will be used as a ``sigencode=`` parameter
    in :func:`ecdsa.keys.SigningKey.sign` method.

    :param int r: first parameter of the signature
    :param int s: second parameter of the signature
    :param int order: the order of the curve over which the signature was
        computed

    :return: DER encoding of ECDSA signature
    :rtype: bytes
    r   )r   r   s      r   sigencode_der_canonizer   f  s,    4 	519}}AIAu%%%r   c                       e Zd ZdZdS )MalformedSignatureaB  
    Raised by decoding functions when the signature is malformed.

    Malformed in this context means that the relevant strings or integers
    do not match what a signature over provided curve would create. Either
    because the byte strings have incorrect lengths or because the encoded
    values are too large.
    N)rQ   rR   rS   __doc__rD   r   r   r   r     s          	Dr   r   c                 8   t          |           } t          |          }t          |           d|z  k    s3t          d                    d|z  t          |                               t          | d|         |          }t          | |d         |          }||fS )a  
    Decoder for :term:`raw encoding`  of ECDSA signatures.

    raw encoding is a simple concatenation of the two integers that comprise
    the signature, with each encoded using the same amount of bytes depending
    on curve size/order.

    It's expected that this function will be used as the ``sigdecode=``
    parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method.

    :param signature: encoded signature
    :type signature: bytes like object
    :param order: order of the curve over which the signature was computed
    :type order: int

    :raises MalformedSignature: when the encoding of the signature is invalid

    :return: tuple with decoded ``r`` and ``s`` values of signature
    :rtype: tuple of ints
    r   zWInvalid length of signature, expected {0} bytes long, provided string is {1} bytes longN)r
   r.   r   r   formatr   )	signaturer-   rx   r   r   s        r   sigdecode_stringr     s    *  	**IAy>>QU"" 006q1uc)nn0M0M
 
 	
 	")BQB-77A!)ABB-77Aa4Kr   c                 >   t          |           dk    s/t          d                    t          |                               | \  }}t          |          }t          |          }t	          |          }t          |          |k    s0t          d                    |t          |                              t          |          |k    s0t          d                    |t          |                              t          ||          }t          ||          }||fS )a  
    Decode the signature from two strings.

    First string needs to be a big endian encoding of ``r``, second needs to
    be a big endian encoding of the ``s`` parameter of an ECDSA signature.

    It's expected that this function will be used as the ``sigdecode=``
    parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method.

    :param list rs_strings: list of two bytes-like objects, each encoding one
        parameter of signature
    :param int order: order of the curve over which the signature was computed

    :raises MalformedSignature: when the encoding of the signature is invalid

    :return: tuple with decoded ``r`` and ``s`` values of signature
    :rtype: tuple of ints
    r   z3Invalid number of strings provided: {0}, expected 2zjInvalid length of first string ('r' parameter), expected {0} bytes long, provided string is {1} bytes longzkInvalid length of second string ('s' parameter), expected {0} bytes long, provided string is {1} bytes long)r   r   r   r
   r.   r   )
rs_stringsr-   r   r   rx   r   r   s          r   sigdecode_stringsr     s   & z??a AHHJ 
 
 	

  NUEE""EE""EAu::?? 3u::..
 
 	

 u::?? 3u::..
 
 	

 	"%//A!%//Aa4Kr   c                 n   t          |           } t          j        |           \  }}|dk    r)t          j        dt	          j        |          z            t          j        |          \  }}t          j        |          \  }}|dk    r)t          j        dt	          j        |          z            ||fS )a  
    Decoder for DER format of ECDSA signatures.

    DER format of signature is one that uses the :term:`ASN.1` :term:`DER`
    rules to encode it as a sequence of two integers::

        Ecdsa-Sig-Value ::= SEQUENCE {
            r       INTEGER,
            s       INTEGER
        }

    It's expected that this function will be used as as the ``sigdecode=``
    parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method.

    :param sig_der: encoded signature
    :type sig_der: bytes like object
    :param order: order of the curve over which the signature was computed
    :type order: int

    :raises UnexpectedDER: when the encoding of signature is invalid

    :return: tuple with decoded ``r`` and ``s`` values of signature
    :rtype: tuple of ints
    r   ztrailing junk after DER sig: %sz#trailing junk after DER numbers: %s)r
   r	   remove_sequenceUnexpectedDERrV   rW   remove_integer)sig_derr-   r   emptyr   restr   s          r   sigdecode_derr     s    2 g&&G+G44J||-0@0G0GG
 
 	
  ,,GAt!$''HAu||1H4DU4K4KK
 
 	
 a4Kr   r<   )1r   
__future__r   r1   r^   rV   syshashlibr   sixr   r   r   r   r	   _compatr
   oid_ecPublicKey
encode_oidencoded_oid_ecPublicKeyoid_ecDH	oid_ecMQVversion_infor   r)   r.   r8   r:   rY   r\   rb   rg   rk   rq   r{   r}   rm   r   r   r   r   r   r   r   	Exceptionr   r   r   r   rD   r   r   <module>r      s           				   



       # # # # # # # # # #       $ $ $ $ $ $ +(#./:   	tO O O OB B B
 f   
# # #( ( (   0       6
 
 
  " " "& >D     =C      &    - - -- - -  .  *M M M2* * *6) ) )0& & &>
	 
	 
	 
	 
	 
	 
	 
	  B+ + +\& & & & &r   