U
    ʹhVF                     @   s  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rdd Zndd Zejdk rdd Zndd Zdd ZdDddZG dd dZdd Zdd Zdd Zefd d!Zefd"d#Z d$d% Z!d&d' Z"d(d) Z#d*d+ Z$d,d- Z%d.d/ Z&d0d1 Z'd2d3 Z(d4d5 Z)d6d7 Z*d8d9 Z+d:d; Z,G d<d= d=e-Z.d>d? Z/d@dA Z0dBdC Z1dS )Ea  
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                 C   s&   t t| ddd t| d S )-Convert a bytestring to string of 0's and 1'sZbigr
   N   )binint
from_byteszfilllenent_256 r   0./venv/lib/python3.8/site-packages/ecdsa/util.pyentropy_to_bits4   s    r   c                 C   s   d dd | D S )r    c                 s   s(   | ] }t t|d d dV  qdS )r
   Nr   )r   ordr   ).0xr   r   r   	<genexpr><   s     z"entropy_to_bits.<locals>.<genexpr>)joinr   r   r   r   r   :   s    )r
      c                 C   s   t t| d S )Nr
   )r   r   r   r   r   r   
bit_lengthA   s    r#   c                 C   s   |   p
dS Nr   )r#   r"   r   r   r   r#   F   s    c                 C   s   dt d|   d S )Nr   z%xr
   )r   )orderr   r   r   orderlenJ   s    r&   c                 C   s|   | dkst |dkrtj}t| d }|d d }||}t|}t|d| ddd }d|  k rn| k r2n q2|S q2dS )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   )baser   )AssertionErrorosurandomr#   r   r   )r%   ZentropyZupper_2Z	upper_256r   Zent_2Zrand_numr   r   r   	randrangeN   s    r+   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )PRNGc                 C   s   |  || _d S )N)block_generator	generator)selfseedr   r   r   __init__l   s    zPRNG.__init__c                    s0    fddt |D }tr$d|S t|S d S )Nc                    s   g | ]}t  jqS r   )r   r.   )r   ir/   r   r   
<listcomp>p   s     z!PRNG.__call__.<locals>.<listcomp>r   )ranger   r    bytes)r/   Znumbytesar   r3   r   __call__o   s    
zPRNG.__call__c                 c   s6   d}t d||f   D ]
}|V  q|d7 }qd S )Nr   z
prng-%d-%sr   )r   encodedigest)r/   r0   ZcounterZbyter   r   r   r-   w   s    zPRNG.block_generatorN)__name__
__module____qualname__r1   r8   r-   r   r   r   r   r,   f   s   r,   c                 C   sX   t | dt| }tt|d|d  d }d|  krD|k sTn td||f|S )Nr
      r   )r,   r&   r   binasciihexlifyr(   )r0   r%   r'   numberr   r   r   %randrange_from_seed__overshoot_modulo   s    $rB   c                 C   s   d| > d S r$   r   )Znumbitsr   r   r   lsb_of_ones   s    rC   c                 C   s2   t t| d dd }|d }|d }|||fS )Nr   r
   r   )r   mathlog)r%   bitsr6   	extrabitsr   r   r   bits_and_bytes   s    rH   c                 C   st   t |\}}}|r|d7 }||  d | }d|t|  | }dtt|d }d|  krj|k spn t|S )Nr    r>   )rH   r:   r   r   r?   r@   r(   )r0   r%   hashmodrF   Z_bytesrG   r'   rA   r   r   r   #randrange_from_seed__truncate_bytes   s    rK   c                 C   s   t t|d dd }|d d }||  d | }d|t|  | }d| | }|rtt|d t|@ |dd   }dt t	|d }d|  kr|k sn t
|S )Nr   r
   r!   r   rI   r   r>   )r   rD   rE   r:   r   r   r   rC   r?   r@   r(   )r0   r%   rJ   rF   Zmaxbytesr'   ZtopbitsrA   r   r   r   "randrange_from_seed__truncate_bits   s    $rL   c                 C   sx   |dkst t|\}}}t| }d}|rBtt|dt|@ }t||| d }d|  krj|k r"n q"|S q"d S )Nr       )r(   rH   r,   r   r   rC   string_to_number)r0   r%   rF   r6   rG   ZgenerateZ	extrabyteZguessr   r   r    randrange_from_seed__trytryagain   s    rO   c                 C   sN   t |}dtd|  d }t||   }t||ksJtt||f|S Nz%0r
   r   )r&   strr?   	unhexlifyr9   r   r(   Znumr%   lZfmt_strstringr   r   r   number_to_string   s
    rV   c                 C   s:   t |}dtd|  d }t||   }|d | S rP   )r&   rQ   r?   rR   r9   rS   r   r   r   number_to_string_crop   s    rW   c                 C   s   t t| dS Nr>   )r   r?   r@   )rU   r   r   r   rN      s    rN   c                 C   s4   t |}t| |ks$tt| |ftt| dS rX   )r&   r   r(   r   r?   r@   )rU   r%   rT   r   r   r   string_to_number_fixedlen   s    rY   c                 C   s   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)
    )rV   rsr%   r_strs_strr   r   r   sigencode_strings   s    

r_   c                 C   s   t | ||\}}|| 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_   rZ   r   r   r   sigencode_string  s    r`   c                 C   s   t t | t |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   Zencode_sequenceZencode_integerr[   r\   r%   r   r   r   sigencode_der  s    rb   c                 C   s   | |d kr||  } | S )a8  
    Internal function for ensuring that the ``s`` value of a signature is in
    the "canonical" format.

    :param int s: the second parameter of ECDSA signature
    :param int order: the order of the curve over which the signatures was
        computed

    :return: canonical value of s
    :rtype: int
    r
   r   )r\   r%   r   r   r   	_canonize3  s    rc   c                 C   s   t ||}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)
    )rc   r_   ra   r   r   r   sigencode_strings_canonizeD  s    
rd   c                 C   s   t ||}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
    )rc   r`   ra   r   r   r   sigencode_string_canonize^  s    
re   c                 C   s   t ||}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
    )rc   rb   ra   r   r   r   sigencode_der_canonizeu  s    
rf   c                   @   s   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)r;   r<   r=   __doc__r   r   r   r   rg     s   	rg   c                 C   sd   t | } t|}t| d| ks8tdd| 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   rg   formatrY   )Z	signaturer%   rT   r[   r\   r   r   r   sigdecode_string  s     rj   c                 C   s   t | dkstdt | | \}}t|}t|}t|}t ||ks^td|t |t ||ks~t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   rg   ri   r	   r&   rY   )
rs_stringsr%   r]   r^   rT   r[   r\   r   r   r   sigdecode_strings  s6      

rl   c                 C   sr   t | } t| \}}|dkr2tdt| t|\}}t|\}}|dkrjtdt| ||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
    rM   ztrailing junk after DER sig: %sz#trailing junk after DER numbers: %s)r	   r   Zremove_sequenceZUnexpectedDERr?   r@   Zremove_integer)Zsig_derr%   rk   emptyr[   restr\   r   r   r   sigdecode_der  s    ro   )N)2rh   Z
__future__r   r)   rD   r?   sysZhashlibr   Zsixr   r   r   r   r   Z_compatr	   Zoid_ecPublicKeyZ
encode_oidZencoded_oid_ecPublicKeyZoid_ecDHZ	oid_ecMQVversion_infor   r#   r&   r+   r,   rB   rC   rH   rK   rL   rO   rV   rW   rN   rY   r_   r`   rb   rc   rd   re   rf   	Exceptionrg   rj   rl   ro   r   r   r   r   <module>   sV   





!.