U
    ʹh"                     @   sb   d 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d	d
gZ
dd Zdd	 Zddd
ZdS )a  
RFC 6979:
    Deterministic Usage of the Digital Signature Algorithm (DSA) and
    Elliptic Curve Digital Signature Algorithm (ECDSA)

    http://tools.ietf.org/html/rfc6979

Many thanks to Coda Hale for his implementation in Go language:
    https://github.com/codahale/rfc6979
    N)hexlify   )number_to_stringnumber_to_string_crop
bit_length)hmac_compatr   bits2intbits2octets
generate_kc                 C   s2   t t| d}t| d }||kr.||| ? S |S )N      )intr   len)dataqlenxl r   3./venv/lib/python3.8/site-packages/ecdsa/rfc6979.pyr      s
    c                 C   s,   t | t|}|| }|dk r"|}t||S )Nr   )r   r   r   )r   orderZz1Zz2r   r   r   r	       s
        c                 C   sz  t | }| j}|d d }tt|| tt|| t|f}	d| }
d| }tj||d}||
d  |	D ]}|| qn| }t||
| }
tj||d}||
d  |	D ]}|| q| }t||
| }
d}t	||k rt||
| }
||
7 }qt
||}d|  kr2| k rLn n|dkrD|S |d8 }t||
d | }t||
| }
qd	S )
aD  
    Generate the ``k`` value - the nonce for DSA.

    :param int order: order of the DSA generator used in the signature
    :param int secexp: secure exponent (private key) in numeric form
    :param hash_func: reference to the same hash function used for generating
        hash, like :py:class:`hashlib.sha1`
    :param bytes data: hash in binary form of the signing data
    :param int retry_gen: how many good 'k' values to skip before returning
    :param bytes extra_entropy: additional added data in binary form as per
        section-3.6 of rfc6979
    :rtype: int
       r          )Z	digestmodr   r   r   N)r   Zdigest_sizer   r   r	   hmacnewupdateZdigestr   r   )r   ZsecexpZ	hash_funcr   Z	retry_genZextra_entropyr   ZholenZrolenZbxvkitZsecretr   r   r   r
   +   s@    


)r   r   )__doc__r   Zbinasciir   utilr   r   r   Z_compatr   __all__r   r	   r
   r   r   r   r   <module>   s   	