o
    6h                     @   sH  d Z ddlZddlmZ ddlZddlmZ ddlmZm	Z	 ddlm
Z
mZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddlmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZ ddl m!Z! ddl"m#Z# ddlm$Z$m%Z% g dZ&G dd de'Z(G dd de'Z)dd Z*G dd de+Z,G dd de+Z-dS )zE
Primary classes for performing signing and verification operations.
    N)sha1)PY2   )ecdsaeddsa)derssh)rfc6979)ellipticcurve)NIST192pCurveEd25519Ed448)RSZeroError)string_to_numbernumber_to_string	randrange)sigencode_stringsigdecode_string
bit_length)oid_ecPublicKeyencoded_oid_ecPublicKeyoid_ecDH	oid_ecMQVMalformedSignature)normalise_bytes)MalformedPointError)PointJacobi	CurveEdTw)BadSignatureErrorBadDigestErrorVerifyingKey
SigningKeyr   c                   @      e Zd ZdZdS )r   al  
    Raised when verification of signature failed.

    Will be raised irrespective of reason of the failure:

    * the calculated or provided hash does not match the signature
    * the signature does not match the curve/public key
    * the encoding of the signature is malformed
    * the size of the signature does not match the curve of the VerifyingKey
    N__name__
__module____qualname____doc__ r)   r)   ^/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/ecdsa/keys.pyr   &   s    r   c                   @   r#   )r    z<Raised in case the selected hash is too large for the curve.Nr$   r)   r)   r)   r*   r    5   s    r    c                 C   st   |st | |jkrtd|jdt |  n| d|j } t| }|r8t|j}t | d }|td|| L }|S )z,Truncates and converts digest to an integer.zAthis curve ({0}) is too short for the length of your digest ({1})   Nr   )	lenbaselenr    formatnamer   r   ordermax)digestcurveallow_truncatenumber
max_lengthlengthr)   r)   r*   _truncate_and_convert_digest;   s    
r8   c                   @   s   e Zd ZdZd)ddZdd Zdd Zd	d
 Zee	e
dfddZd*ddZee	e
ddfddZee
ddfddZee
ddfddZee
edfddZee
edfddZd+ddZ	d,dd Z	d,d!d"Zd#d$ Zdedfd%d&Zedfd'd(ZdS )-r!   a  
    Class for handling keys that can verify signatures (public keys).

    :ivar `~ecdsa.curves.Curve` ~.curve: The Curve over which all the
        cryptographic operations will take place
    :ivar default_hashfunc: the function that will be used for hashing the
        data. Should implement the same API as hashlib.sha1
    :vartype default_hashfunc: callable
    :ivar pubkey: the actual public key
    :vartype pubkey: ~ecdsa.ecdsa.Public_key
    Nc                 C   s"   |st dd| _d| _d| _dS )>Unsupported, please use one of the classmethods to initialise.z2Please use VerifyingKey.generate() to construct meN)	TypeErrorr3   default_hashfuncpubkeyself_error__please_use_generater)   r)   r*   __init__h   s   
zVerifyingKey.__init__c                 C   s0   |  d}| jr|  j}nd}d|| j|S )N
compressedNonez+VerifyingKey.from_string({0!r}, {1!r}, {2}))	to_stringr;   r/   r.   r3   )r>   pub_key	hash_namer)   r)   r*   __repr__r   s   
zVerifyingKey.__repr__c                 C   s&   t |tr| j|jko| j|jkS tS z9Return True if the points are identical, False otherwise.)
isinstancer!   r3   r<   NotImplementedr>   otherr)   r)   r*   __eq__|   s   
zVerifyingKey.__eq__c                 C   
   | |k S z9Return False if the points are identical, True otherwise.r)   rJ   r)   r)   r*   __ne__      
zVerifyingKey.__ne__Tc                 C   s   | dd}t |jtrtdt |tjstj|}||_||_zt	|j
|||_W n tjy8   tdw |j|j_|S )a  
        Initialise the object from a Point object.

        This is a low-level method, generally you will not want to use it.

        :param point: The point to wrap around, the actual public key
        :type point: ~ecdsa.ellipticcurve.AbstractPoint
        :param curve: The curve on which the point needs to reside, defaults
            to NIST192p
        :type curve: ~ecdsa.curves.Curve
        :param hashfunc: The default hash function that will be used for
            verification, needs to implement the same interface
            as :py:class:`hashlib.sha1`
        :type hashfunc: callable
        :type bool validate_point: whether to check if the point lays on curve
            should always be used if the public point is not a result
            of our own calculation

        :raises MalformedPointError: if the public point does not lay on the
            curve

        :return: Initialised VerifyingKey object
        :rtype: VerifyingKey
        Tr?   z'Method incompatible with Edwards curveszPoint does not lay on the curve)rH   r3   r   
ValueErrorr
   r   from_affiner;   r   
Public_key	generatorr<   InvalidPointErrorr   r0   )clspointr3   hashfuncvalidate_pointr>   r)   r)   r*   from_public_point   s    


zVerifyingKey.from_public_pointFc              	   C   s~   t | jjtr(| jj}tj| | | d| |  | jj	dd| j_ntj
| jjd| j_|s=| jjd  dS dS )al  
        Precompute multiplication tables for faster signature verification.

        Calling this method will cause the library to precompute the
        scalar multiplication tables, used in signature verification.
        While it's an expensive operation (comparable to performing
        as many signatures as the bit size of the curve, i.e. 256 for NIST256p)
        it speeds up verification 2 times. You should call this method
        if you expect to verify hundreds of signatures (or more) using the same
        VerifyingKey object.

        Note: You should call this method only once, this method generates a
        new precomputation table every time it's called.

        :param bool lazy: whether to calculate the precomputation table now
           (if set to False) or if it should be delayed to the time of first
           use (when set to True)
        r   T)rU      N)rH   r3   r   r<   rX   r
   PointEdwardsxyr0   r   rS   )r>   lazyptr)   r)   r*   
precompute   s"   
zVerifyingKey.precomputec                 C   st   t |jtr(| dd}||_d|_zt|j||_W |S  ty'   t	dw t
j|j|||d}| ||||S )a^  
        Initialise the object from byte encoding of public key.

        The method does accept and automatically detect the type of point
        encoding used. It supports the :term:`raw encoding`,
        :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings.
        It also works with the native encoding of Ed25519 and Ed448 public
        keys (technically those are compressed, but encoded differently than
        in other signature systems).

        Note, while the method is named "from_string" it's a misnomer from
        Python 2 days when there were no binary strings. In Python 3 the
        input needs to be a bytes-like object.

        :param string: single point encoding of the public key
        :type string: :term:`bytes-like object`
        :param curve: the curve on which the public key is expected to lay
        :type curve: ~ecdsa.curves.Curve
        :param hashfunc: The default hash function that will be used for
            verification, needs to implement the same interface as
            hashlib.sha1. Ignored for EdDSA.
        :type hashfunc: callable
        :param validate_point: whether to verify that the point lays on the
            provided curve or not, defaults to True. Ignored for EdDSA.
        :type validate_point: bool
        :param valid_encodings: list of acceptable point encoding formats,
            supported ones are: :term:`uncompressed`, :term:`compressed`,
            :term:`hybrid`, and :term:`raw encoding` (specified with ``raw``
            name). All formats by default (specified with ``None``).
            Ignored for EdDSA.
        :type valid_encodings: :term:`set-like object`

        :raises MalformedPointError: if the public point does not lay on the
            curve or the encoding is invalid

        :return: Initialised VerifyingKey object
        :rtype: VerifyingKey
        TrQ   NzMalformed point for the curve)validate_encodingvalid_encodings)rH   r3   r   r;   r   	PublicKeyrU   r<   rR   r   r   
from_bytesr[   )rW   stringr3   rY   rZ   rd   r>   rX   r)   r)   r*   from_string   s"   /
zVerifyingKey.from_stringc                 C   s   | j t||||dS )a(  
        Initialise from public key stored in :term:`PEM` format.

        The PEM header of the key should be ``BEGIN PUBLIC KEY``.

        See the :func:`~VerifyingKey.from_der()` method for details of the
        format supported.

        Note: only a single PEM object decoding is supported in provided
        string.

        :param string: text with PEM-encoded public ECDSA key
        :type string: str
        :param valid_encodings: list of allowed point encodings.
            By default :term:`uncompressed`, :term:`compressed`, and
            :term:`hybrid`. To read malformed files, include
            :term:`raw encoding` with ``raw`` in the list.
        :type valid_encodings: :term:`set-like object`
        :param valid_curve_encodings: list of allowed encoding formats
            for curve parameters. By default (``None``) all are supported:
            ``named_curve`` and ``explicit``.
        :type valid_curve_encodings: :term:`set-like object`


        :return: Initialised VerifyingKey object
        :rtype: VerifyingKey
        )rY   rd   valid_curve_encodings)from_derr   unpem)rW   rg   rY   rd   ri   r)   r)   r*   from_pem  s   #zVerifyingKey.from_pemc                 C   s:  |du r
t g d}t|}t|\}}|dkr#tdt| t|\}}t|\}	}
|	tj	t
j	fv r`|	tj	krAt}n	|	t
j	ksHJ t
}t|d\}}|rYtd| ||dS |	tksltd|	t|
|}t|d\}}|dkrtdt| t||jkrtd	| j||||d
S )a  
        Initialise the key stored in :term:`DER` format.

        The expected format of the key is the SubjectPublicKeyInfo structure
        from RFC5912 (for RSA keys, it's known as the PKCS#1 format)::

           SubjectPublicKeyInfo {PUBLIC-KEY: IOSet} ::= SEQUENCE {
               algorithm        AlgorithmIdentifier {PUBLIC-KEY, {IOSet}},
               subjectPublicKey BIT STRING
           }

        Note: only public EC keys are supported by this method. The
        SubjectPublicKeyInfo.algorithm.algorithm field must specify
        id-ecPublicKey (see RFC3279).

        Only the named curve encoding is supported, thus the
        SubjectPublicKeyInfo.algorithm.parameters field needs to be an
        object identifier. A sequence in that field indicates an explicit
        parameter curve encoding, this format is not supported. A NULL object
        in that field indicates an "implicitlyCA" encoding, where the curve
        parameters come from CA certificate, those, again, are not supported.

        :param string: binary string with the DER encoding of public ECDSA key
        :type string: bytes-like object
        :param valid_encodings: list of allowed point encodings.
            By default :term:`uncompressed`, :term:`compressed`, and
            :term:`hybrid`. To read malformed files, include
            :term:`raw encoding` with ``raw`` in the list.
        :type valid_encodings: :term:`set-like object`
        :param valid_curve_encodings: list of allowed encoding formats
            for curve parameters. By default (``None``) all are supported:
            ``named_curve`` and ``explicit``.
        :type valid_curve_encodings: :term:`set-like object`

        :return: Initialised VerifyingKey object
        :rtype: VerifyingKey
        N)uncompressedrA   hybrid    z"trailing junk after DER pubkey: %sr   ztrailing junk after public keyz3Unexpected object identifier in DER encoding: {0!r}z*trailing junk after pubkey pointstring: %sz"Malformed encoding of public point)rY   rd   )setr   r   remove_sequenceUnexpectedDERbinasciihexlifyremove_objectr   oidr   remove_bitstringrh   r   r.   r   rj   r,   verifying_key_length)rW   rg   rY   rd   ri   s1emptys2point_str_bitstringoid_pkrestr3   	point_strr)   r)   r*   rj   E  sP   -


zVerifyingKey.from_derc                 C   s>   t |jtr
tdt|}|| }| j||||||dS )a  
        Return keys that can be used as verifiers of the provided signature.

        Tries to recover the public key that can be used to verify the
        signature, usually returns two keys like that.

        :param signature: the byte string with the encoded signature
        :type signature: bytes-like object
        :param data: the data to be hashed for signature verification
        :type data: bytes-like object
        :param curve: the curve over which the signature was performed
        :type curve: ~ecdsa.curves.Curve
        :param hashfunc: The default hash function that will be used for
            verification, needs to implement the same interface as hashlib.sha1
        :type hashfunc: callable
        :param sigdecode: Callable to define the way the signature needs to
            be decoded to an object, needs to handle `signature` as the
            first parameter, the curve order (an int) as the second and return
            a tuple with two integers, "r" as the first one and "s" as the
            second one. See :func:`ecdsa.util.sigdecode_string` and
            :func:`ecdsa.util.sigdecode_der` for examples.
        :param bool allow_truncate: if True, the provided hashfunc can generate
            values larger than the bit size of the order of the curve, the
            extra bits (at the end of the digest) will be truncated.
        :type sigdecode: callable

        :return: Initialised VerifyingKey objects
        :rtype: list of VerifyingKey
        %Method unsupported for Edwards curves)rY   	sigdecoder4   )rH   r3   r   rR   r   r2   $from_public_key_recovery_with_digest)rW   	signaturedatar3   rY   r   r4   r2   r)   r)   r*   from_public_key_recovery  s   'z%VerifyingKey.from_public_key_recoveryc                    sr   t jtr
tdj}||| \}}	t||	}
t|}t	||}|

||} fdd|D }|S )a  
        Return keys that can be used as verifiers of the provided signature.

        Tries to recover the public key that can be used to verify the
        signature, usually returns two keys like that.

        :param signature: the byte string with the encoded signature
        :type signature: bytes-like object
        :param digest: the hash value of the message signed by the signature
        :type digest: bytes-like object
        :param curve: the curve over which the signature was performed
        :type curve: ~ecdsa.curves.Curve
        :param hashfunc: The default hash function that will be used for
            verification, needs to implement the same interface as hashlib.sha1
        :type hashfunc: callable
        :param sigdecode: Callable to define the way the signature needs to
            be decoded to an object, needs to handle `signature` as the
            first parameter, the curve order (an int) as the second and return
            a tuple with two integers, "r" as the first one and "s" as the
            second one. See :func:`ecdsa.util.sigdecode_string` and
            :func:`ecdsa.util.sigdecode_der` for examples.
        :type sigdecode: callable
        :param bool allow_truncate: if True, the provided hashfunc can generate
            values larger than the bit size of the order of the curve (and
            the length of provided `digest`), the extra bits (at the end of the
            digest) will be truncated.

        :return: Initialised VerifyingKey object
        :rtype: VerifyingKey
        r   c                    s   g | ]
}  |jqS r)   )r[   rX   ).0pkrW   r3   rY   r)   r*   
<listcomp>  s    zEVerifyingKey.from_public_key_recovery_with_digest.<locals>.<listcomp>)rH   r3   r   rR   rU   r0   r   	Signaturer   r8   recover_public_keys)rW   r   r2   r3   rY   r   r4   rU   rssigdigest_as_numberpksverifying_keysr)   r   r*   r     s   (z1VerifyingKey.from_public_key_recovery_with_digestrawc                 C   s   |dv sJ | j j|S )a  
        Convert the public key to a byte string.

        The method by default uses the :term:`raw encoding` (specified
        by `encoding="raw"`. It can also output keys in :term:`uncompressed`,
        :term:`compressed` and :term:`hybrid` formats.

        Remember that the curve identification is not part of the encoding
        so to decode the point using :func:`~VerifyingKey.from_string`, curve
        needs to be specified.

        Note: while the method is called "to_string", it's a misnomer from
        Python 2 days when character strings and byte strings shared type.
        On Python 3 the returned type will be `bytes`.

        :return: :term:`raw encoding` of the public key (public point) on the
            curve
        :rtype: bytes
        )r   rm   rA   rn   )r<   rX   to_bytes)r>   encodingr)   r)   r*   rC     s   zVerifyingKey.to_stringrm   c                 C   s   t | ||dS )a  
        Convert the public key to the :term:`PEM` format.

        The PEM header of the key will be ``BEGIN PUBLIC KEY``.

        The format of the key is described in the
        :func:`~VerifyingKey.from_der()` method.
        This method supports only "named curve" encoding of keys.

        :param str point_encoding: specification of the encoding format
            of public keys. "uncompressed" is most portable, "compressed" is
            smallest. "hybrid" is uncommon and unsupported by most
            implementations, it is as big as "uncompressed".
        :param str curve_parameters_encoding: the encoding for curve parameters
            to use, by default tries to use ``named_curve`` encoding,
            if that is not possible, falls back to ``explicit`` encoding.

        :return: portable encoding of the public key
        :rtype: bytes

        .. warning:: The PEM is encoded to US-ASCII, it needs to be
            re-encoded if the system is incompatible (e.g. uses UTF-16)
        z
PUBLIC KEYr   topemto_der)r>   point_encodingcurve_parameters_encodingr)   r)   r*   to_pem#  s   
zVerifyingKey.to_pemc              	   C   sv   |dkrt d| |}t| jjtr(tttj| jj t	t
|dS ttt| j||t	|dS )a&  
        Convert the public key to the :term:`DER` format.

        The format of the key is described in the
        :func:`~VerifyingKey.from_der()` method.
        This method supports only "named curve" encoding of keys.

        :param str point_encoding: specification of the encoding format
            of public keys. "uncompressed" is most portable, "compressed" is
            smallest. "hybrid" is uncommon and unsupported by most
            implementations, it is as big as "uncompressed".
        :param str curve_parameters_encoding: the encoding for curve parameters
            to use, by default tries to use ``named_curve`` encoding,
            if that is not possible, falls back to ``explicit`` encoding.

        :return: DER encoding of the public key
        :rtype: bytes
        r   z%raw point_encoding not allowed in DERr   )rR   rC   rH   r3   r   r   encode_sequence
encode_oidrv   encode_bitstringbytesr   r   )r>   r   r   r   r)   r)   r*   r   B  s   

zVerifyingKey.to_derc                 C   s   t | jj|  S )z
        Convert the public key to the SSH format.

        :return: SSH encoding of the public key
        :rtype: bytes
        )r   serialize_publicr3   r/   rC   r>   r)   r)   r*   to_sshi  s   zVerifyingKey.to_sshc              
   C   s|   t |}t| jjtr+t |}z| j||W S  ttfy* } ztd|d}~ww |p/| j	}||
 }| ||||S )a  
        Verify a signature made over provided data.

        Will hash `data` to verify the signature.

        By default expects signature in :term:`raw encoding`. Can also be used
        to verify signatures in ASN.1 DER encoding by using
        :func:`ecdsa.util.sigdecode_der`
        as the `sigdecode` parameter.

        :param signature: encoding of the signature
        :type signature: sigdecode method dependent
        :param data: data signed by the `signature`, will be hashed using
            `hashfunc`, if specified, or default hash function
        :type data: :term:`bytes-like object`
        :param hashfunc: The default hash function that will be used for
            verification, needs to implement the same interface as hashlib.sha1
        :type hashfunc: callable
        :param sigdecode: Callable to define the way the signature needs to
            be decoded to an object, needs to handle `signature` as the
            first parameter, the curve order (an int) as the second and return
            a tuple with two integers, "r" as the first one and "s" as the
            second one. See :func:`ecdsa.util.sigdecode_string` and
            :func:`ecdsa.util.sigdecode_der` for examples.
        :type sigdecode: callable
        :param bool allow_truncate: if True, the provided digest can have
            bigger bit-size than the order of the curve, the extra bits (at
            the end of the digest) will be truncated. Use it when verifying
            SHA-384 output using NIST256p or in similar situations. Defaults to
            True.

        :raises BadSignatureError: if the signature is invalid or malformed

        :return: True if the verification was successful
        :rtype: bool
        Signature verification failedN)r   rH   r3   r   r<   verifyrR   r   r   r;   r2   verify_digest)r>   r   r   rY   r   r4   er2   r)   r)   r*   r   u  s   .

zVerifyingKey.verifyc           
   
   C   s|   t |}t|| j|}z||| jj\}}W n tjtfy* } ztd|d}~ww t	
||}	| j||	r:dS td)a-  
        Verify a signature made over provided hash value.

        By default expects signature in :term:`raw encoding`. Can also be used
        to verify signatures in ASN.1 DER encoding by using
        :func:`ecdsa.util.sigdecode_der`
        as the `sigdecode` parameter.

        :param signature: encoding of the signature
        :type signature: sigdecode method dependent
        :param digest: raw hash value that the signature authenticates.
        :type digest: :term:`bytes-like object`
        :param sigdecode: Callable to define the way the signature needs to
            be decoded to an object, needs to handle `signature` as the
            first parameter, the curve order (an int) as the second and return
            a tuple with two integers, "r" as the first one and "s" as the
            second one. See :func:`ecdsa.util.sigdecode_string` and
            :func:`ecdsa.util.sigdecode_der` for examples.
        :type sigdecode: callable
        :param bool allow_truncate: if True, the provided digest can have
            bigger bit-size than the order of the curve, the extra bits (at
            the end of the digest) will be truncated. Use it when verifying
            SHA-384 output using NIST256p or in similar situations.

        :raises BadSignatureError: if the signature is invalid or malformed
        :raises BadDigestError: if the provided digest is too big for the curve
            associated with this VerifyingKey and allow_truncate was not set

        :return: True if the verification was successful
        :rtype: bool
        z!Malformed formatting of signatureNTr   )r   r8   r3   r<   r0   r   rr   r   r   r   r   verifies)
r>   r   r2   r   r4   r5   r   r   r   r   r)   r)   r*   r     s    (
zVerifyingKey.verify_digestN)F)r   )rm   N)r%   r&   r'   r(   r@   rF   rL   rO   classmethodr   r   r[   rb   rh   rl   rj   r   r   r   rC   r   r   r   r   r   r)   r)   r)   r*   r!   [   sb    



+(@)X3
9
 
'
>r!   c                   @   s0  e Zd ZdZd2ddZdd Zdd Zed	d
 Zedd Z	ee
defddZee
efddZee
efddZeedfddZeedfddZdd Z			d3ddZdd Z			d3dd Zd!d" Zd#d$ Zded%fd&d'Zded%d(fd)d*Zddedd+fd,d-Zdedd(fd.d/Zd4d0d1ZdS )5r"   aQ  
    Class for handling keys that can create signatures (private keys).

    :ivar `~ecdsa.curves.Curve` curve: The Curve over which all the
        cryptographic operations will take place
    :ivar default_hashfunc: the function that will be used for hashing the
        data. Should implement the same API as :py:class:`hashlib.sha1`
    :ivar int baselen: the length of a :term:`raw encoding` of private key
    :ivar `~ecdsa.keys.VerifyingKey` verifying_key: the public key
        associated with this private key
    :ivar `~ecdsa.ecdsa.Private_key` privkey: the actual private key
    Nc                 C   s.   |st dd| _d| _d| _d| _d| _dS )r9   z0Please use SigningKey.generate() to construct meN)r:   r3   r;   r-   verifying_keyprivkeyr=   r)   r)   r*   r@     s   
zSigningKey.__init__c                 C   s2   t |tr| j|jko| j|jko| j|jkS tS rG   )rH   r"   r3   r   r   rI   rJ   r)   r)   r*   rL      s   


zSigningKey.__eq__c                 C   rM   rN   r)   rJ   r)   r)   r*   rO   
  rP   zSigningKey.__ne__c                 C   sh   |st j}||j}t|j|}| }t| |}| dd}||_	d|_
|j|_||_||_|S )z2Generate a private key on a Twisted Edwards curve.TrQ   N)osurandomr-   r   
PrivateKeyrU   
public_keyr!   rh   r3   r;   r   r   )rW   r3   entropyrandomprivate_keyr   r   r>   r)   r)   r*   _twisted_edwards_keygen  s   

z"SigningKey._twisted_edwards_keygenc                 C   s   t |j|}| |||S )z.Generate a private key on a Weierstrass curve.)r   r0   from_secret_exponent)rW   r3   r   rY   secexpr)   r)   r*   _weierstrass_keygen#  s   zSigningKey._weierstrass_keygenc                 C   s&   t |jtr| ||S | |||S )a  
        Generate a random private key.

        :param curve: The curve on which the point needs to reside, defaults
            to NIST192p
        :type curve: ~ecdsa.curves.Curve
        :param entropy: Source of randomness for generating the private keys,
            should provide cryptographically secure random numbers if the keys
            need to be secure. Uses os.urandom() by default.
        :type entropy: callable
        :param hashfunc: The default hash function that will be used for
            signing, needs to implement the same interface
            as hashlib.sha1
        :type hashfunc: callable

        :return: Initialised SigningKey object
        :rtype: SigningKey
        )rH   r3   r   r   r   )rW   r3   r   rY   r)   r)   r*   generate)  s   zSigningKey.generatec                 C   s   t |jtr
td| dd}||_||_|j|_|j}d|  kr&|k s.n td||j	| }t
|dr<| }t|||d|_|jj}t|||_||j_|S )a  
        Create a private key from a random integer.

        Note: it's a low level method, it's recommended to use the
        :func:`~SigningKey.generate` method to create private keys.

        :param int secexp: secret multiplier (the actual private key in ECDSA).
            Needs to be an integer between 1 and the curve order.
        :param curve: The curve on which the point needs to reside
        :type curve: ~ecdsa.curves.Curve
        :param hashfunc: The default hash function that will be used for
            signing, needs to implement the same interface
            as hashlib.sha1
        :type hashfunc: callable

        :raises MalformedPointError: when the provided secexp is too large
            or too small for the curve selected
        :raises RuntimeError: if the generation of public key from private
            key failed

        :return: Initialised SigningKey object
        :rtype: SigningKey
        zHEdwards keys don't support setting the secret scalar (exponent) directlyTrQ   r   z<Invalid value for secexp, expected integer between 1 and {0}scaleF)rH   r3   r   rR   r;   r-   r0   r   r.   rU   hasattrr   r!   r[   r   r<   r   Private_keyr   )rW   r   r3   rY   r>   npubkey_pointr<   r)   r)   r*   r   A  s0   


zSigningKey.from_secret_exponentc                 C   s   t |}t||jkrtdt||jt|jtrA| dd}||_d|_|j|_t	
|j||_t|j  ||_|S t|}| |||S )a  
        Decode the private key from :term:`raw encoding`.

        Note: the name of this method is a misnomer coming from days of
        Python 2, when binary strings and character strings shared a type.
        In Python 3, the expected type is `bytes`.

        :param string: the raw encoding of the private key
        :type string: :term:`bytes-like object`
        :param curve: The curve on which the point needs to reside
        :type curve: ~ecdsa.curves.Curve
        :param hashfunc: The default hash function that will be used for
            signing, needs to implement the same interface
            as hashlib.sha1
        :type hashfunc: callable

        :raises MalformedPointError: if the length of encoding doesn't match
            the provided curve or the encoded values is too large
        :raises RuntimeError: if the generation of public key from private
            key failed

        :return: Initialised SigningKey object
        :rtype: SigningKey
        z9Invalid length of private key, received {0}, expected {1}TrQ   N)r   r,   r-   r   r.   rH   r3   r   r;   r   r   rU   r   r!   rh   r   r   r   r   )rW   rg   r3   rY   r>   r   r)   r)   r*   rh   t  s$   
zSigningKey.from_stringc                 C   sN   t st|tr| }|d}|dkr|d}| t||d ||S )am  
        Initialise from key stored in :term:`PEM` format.

        The PEM formats supported are the un-encrypted RFC5915
        (the ssleay format) supported by OpenSSL, and the more common
        un-encrypted RFC5958 (the PKCS #8 format).

        The legacy format files have the header with the string
        ``BEGIN EC PRIVATE KEY``.
        PKCS#8 files have the header ``BEGIN PRIVATE KEY``.
        Encrypted files (ones that include the string
        ``Proc-Type: 4,ENCRYPTED``
        right after the PEM header) are not supported.

        See :func:`~SigningKey.from_der` for ASN.1 syntax of the objects in
        this files.

        :param string: text with PEM-encoded private ECDSA key
        :type string: str
        :param valid_curve_encodings: list of allowed encoding formats
            for curve parameters. By default (``None``) all are supported:
            ``named_curve`` and ``explicit``.
        :type valid_curve_encodings: :term:`set-like object`


        :raises MalformedPointError: if the length of encoding doesn't match
            the provided curve or the encoded values is too large
        :raises RuntimeError: if the generation of public key from private
            key failed
        :raises UnexpectedDER: if the encoding of the PEM file is incorrect

        :return: Initialised SigningKey object
        :rtype: SigningKey
        s   -----BEGIN EC PRIVATE KEY-----s   -----BEGIN PRIVATE KEY-----N)	r   rH   strencodefindindexrj   r   rk   )rW   rg   rY   ri   private_key_indexr)   r)   r*   rl     s   $

zSigningKey.from_pemc                 C   s  t |}d}t|\}}|dkrtdt| t|\}}t|r|dvr2td| t|\}}t|\}	}
|	t	j
tj
fv r||
rOtdt|\}}t|\}}|rdtd|	t	j
krlt	}n	|	tj
kssJ t}| ||dS |	tttfvrtd|	f t|
|}t|\}}t|\}}|dkrtdt| t|\}}|d	krtd
| t|\}}|st|\}}}|dkrtd| t||}t||jk rd|jt|  | }| |||S )a	  
        Initialise from key stored in :term:`DER` format.

        The DER formats supported are the un-encrypted RFC5915
        (the ssleay format) supported by OpenSSL, and the more common
        un-encrypted RFC5958 (the PKCS #8 format).

        Both formats contain an ASN.1 object following the syntax specified
        in RFC5915::

            ECPrivateKey ::= SEQUENCE {
              version        INTEGER { ecPrivkeyVer1(1) }} (ecPrivkeyVer1),
              privateKey     OCTET STRING,
              parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
              publicKey  [1] BIT STRING OPTIONAL
            }

        `publicKey` field is ignored completely (errors, if any, in it will
        be undetected).

        Two formats are supported for the `parameters` field: the named
        curve and the explicit encoding of curve parameters.
        In the legacy ssleay format, this implementation requires the optional
        `parameters` field to get the curve name. In PKCS #8 format, the curve
        is part of the PrivateKeyAlgorithmIdentifier.

        The PKCS #8 format includes an ECPrivateKey object as the `privateKey`
        field within a larger structure::

            OneAsymmetricKey ::= SEQUENCE {
                version                   Version,
                privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
                privateKey                PrivateKey,
                attributes            [0] Attributes OPTIONAL,
                ...,
                [[2: publicKey        [1] PublicKey OPTIONAL ]],
                ...
            }

        The `attributes` and `publicKey` fields are completely ignored; errors
        in them will not be detected.

        :param string: binary string with DER-encoded private ECDSA key
        :type string: :term:`bytes-like object`
        :param valid_curve_encodings: list of allowed encoding formats
            for curve parameters. By default (``None``) all are supported:
            ``named_curve`` and ``explicit``.
            Ignored for EdDSA.
        :type valid_curve_encodings: :term:`set-like object`

        :raises MalformedPointError: if the length of encoding doesn't match
            the provided curve or the encoded values is too large
        :raises RuntimeError: if the generation of public key from private
            key failed
        :raises UnexpectedDER: if the encoding of the DER file is incorrect

        :return: Initialised SigningKey object
        :rtype: SigningKey
        Nro   z#trailing junk after DER privkey: %s)r   r   z7expected version '0' or '1' at start of privkey, got %dz#Non NULL parameters for a EdDSA keyz+trailing junk after the encoded private keyz$unexpected algorithm identifier '%s'r   z4expected version '1' at start of DER privkey, got %dr   z%expected tag 0 in DER privkey, got %d    )r   r   rq   rr   rs   rt   remove_integeris_sequenceru   r   rv   r   remove_octet_stringrh   r   r   r   r   rj   remove_constructedr,   r-   )rW   rg   rY   ri   r   r3   rz   versionsequencealgorithm_oidalgorithm_identifierkey_str_derkey_str_privkey_strtagcurve_oid_strr)   r)   r*   rj     s   =

zSigningKey.from_derc                 C   s4   t | jjtrt| jjS | jj}t|| jj}|S )aK  
        Convert the private key to :term:`raw encoding`.

        Note: while the method is named "to_string", its name comes from
        Python 2 days, when binary and character strings used the same type.
        The type used in Python 3 is `bytes`.

        :return: raw encoding of private key
        :rtype: bytes
        )	rH   r3   r   r   r   r   secret_multiplierr   r0   )r>   r   r   r)   r)   r*   rC     s
   zSigningKey.to_stringrm   ssleayc                 C   s2   |dv sJ |dkrdnd}t | ||||S )a"  
        Convert the private key to the :term:`PEM` format.

        See :func:`~SigningKey.from_pem` method for format description.

        Only the named curve format is supported.
        The public key will be included in generated string.

        The PEM header will specify ``BEGIN EC PRIVATE KEY`` or
        ``BEGIN PRIVATE KEY``, depending on the desired format.

        :param str point_encoding: format to use for encoding public point
        :param str format: either ``ssleay`` (default) or ``pkcs8``
        :param str curve_parameters_encoding: format of encoded curve
            parameters, default depends on the curve, if the curve has
            an associated OID, ``named_curve`` format will be used,
            if no OID is associated with the curve, the fallback of
            ``explicit`` parameters will be used.

        :return: PEM encoded private key
        :rtype: bytes

        .. warning:: The PEM is encoded to US-ASCII, it needs to be
            re-encoded if the system is incompatible (e.g. uses UTF-16)
        r   pkcs8r   zEC PRIVATE KEYzPRIVATE KEYr   )r>   r   r.   r   headerr)   r)   r*   r     s    zSigningKey.to_pemc                 C   s8   t |  }t t dt t j| jj t |S )z'Create a PKCS#8 encoding of EdDSA keys.r   )r   encode_octet_stringrC   r   encode_integerr   r3   rv   )r>   ec_private_keyr)   r)   r*   _encode_eddsa  s   zSigningKey._encode_eddsac              	   C   s   |dkrt d|dv sJ t| jjtr!|dkrt d|  S |  |}tdt	|  g}|dkrE|
td| j| |
tdt|d tj| }|dkr]|S ttdttjt | j|t	|S )	a  
        Convert the private key to the :term:`DER` format.

        See :func:`~SigningKey.from_der` method for format specification.

        Only the named curve format is supported.
        The public key will be included in the generated string.

        :param str point_encoding: format to use for encoding public point
            Ignored for EdDSA
        :param str format: either ``ssleay`` (default) or ``pkcs8``.
            EdDSA keys require ``pkcs8``.
        :param str curve_parameters_encoding: format of encoded curve
            parameters, default depends on the curve, if the curve has
            an associated OID, ``named_curve`` format will be used,
            if no OID is associated with the curve, the fallback of
            ``explicit`` parameters will be used.
            Ignored for EdDSA.

        :return: DER encoded private key
        :rtype: bytes
        r   zraw encoding not allowed in DERr   r   z+Only PKCS#8 format supported for EdDSA keysr   r   r   )rR   rH   r3   r   r   get_verifying_keyrC   r   r   r   appendencode_constructedr   r   r   r   r   )r>   r   r.   r   
encoded_vkpriv_key_elemsr   r)   r)   r*   r     s>   

zSigningKey.to_derc                 C   s   t | jj| j |  S )z|
        Convert the private key to the SSH format.

        :return: SSH encoded private key
        :rtype: bytes
        )r   serialize_privater3   r/   r   rC   r   r)   r)   r*   r   
  s
   zSigningKey.to_sshc                 C   s   | j S )a   
        Return the VerifyingKey associated with this private key.

        Equivalent to reading the `verifying_key` field of an instance.

        :return: a public key that can be used to verify the signatures made
            with this SigningKey
        :rtype: VerifyingKey
        )r   r   r)   r)   r*   r     s   
zSigningKey.get_verifying_keyro   c                 C   sT   |p| j }t|}t| jjtr| j|S t|}|| }| j||||ddS )aE  
        Create signature over data.

        For Weierstrass curves it uses the deterministic RFC6979 algorithm.
        For Edwards curves it uses the standard EdDSA algorithm.

        For ECDSA the data will be hashed using the `hashfunc` function before
        signing.
        For EdDSA the data will be hashed with the hash associated with the
        curve (SHA-512 for Ed25519 and SHAKE-256 for Ed448).

        This is the recommended method for performing signatures when hashing
        of data is necessary.

        :param data: data to be hashed and computed signature over
        :type data: :term:`bytes-like object`
        :param hashfunc: hash function to use for computing the signature,
            if unspecified, the default hash function selected during
            object initialisation will be used (see
            `VerifyingKey.default_hashfunc`). The object needs to implement
            the same interface as hashlib.sha1.
            Ignored with EdDSA.
        :type hashfunc: callable
        :param sigencode: function used to encode the signature.
            The function needs to accept three parameters: the two integers
            that are the signature and the order of the curve over which the
            signature was computed. It needs to return an encoded signature.
            See `ecdsa.util.sigencode_string` and `ecdsa.util.sigencode_der`
            as examples of such functions.
            Ignored with EdDSA.
        :type sigencode: callable
        :param extra_entropy: additional data that will be fed into the random
            number generator used in the RFC6979 process. Entirely optional.
            Ignored with EdDSA.
        :type extra_entropy: :term:`bytes-like object`

        :return: encoded signature over `data`
        :rtype: bytes or sigencode function dependent type
        T)rY   	sigencodeextra_entropyr4   )	r;   r   rH   r3   r   r   signr2   sign_digest_deterministic)r>   r   rY   r   r   r2   r)   r)   r*   sign_deterministic#  s   
.zSigningKey.sign_deterministicFc                 C   s   t | jjtrtd| jj}|p| j}t|}t|}dd }d}	 tj	| jj
 |||||d}	z| j|||	|d\}
}}W n tyM   |d7 }Y nw q#||
||S )	a  
        Create signature for digest using the deterministic RFC6979 algorithm.

        `digest` should be the output of cryptographically secure hash function
        like SHA256 or SHA-3-256.

        This is the recommended method for performing signatures when no
        hashing of data is necessary.

        :param digest: hash of data that will be signed
        :type digest: :term:`bytes-like object`
        :param hashfunc: hash function to use for computing the random "k"
            value from RFC6979 process,
            if unspecified, the default hash function selected during
            object initialisation will be used (see
            :attr:`.VerifyingKey.default_hashfunc`). The object needs to
            implement
            the same interface as :func:`~hashlib.sha1` from :py:mod:`hashlib`.
        :type hashfunc: callable
        :param sigencode: function used to encode the signature.
            The function needs to accept three parameters: the two integers
            that are the signature and the order of the curve over which the
            signature was computed. It needs to return an encoded signature.
            See :func:`~ecdsa.util.sigencode_string` and
            :func:`~ecdsa.util.sigencode_der`
            as examples of such functions.
        :type sigencode: callable
        :param extra_entropy: additional data that will be fed into the random
            number generator used in the RFC6979 process. Entirely optional.
        :type extra_entropy: :term:`bytes-like object`
        :param bool allow_truncate: if True, the provided digest can have
            bigger bit-size than the order of the curve, the extra bits (at
            the end of the digest) will be truncated. Use it when signing
            SHA-384 output using NIST256p or in similar situations.

        :return: encoded signature for the `digest` hash
        :rtype: bytes or sigencode function dependent type
        r   c                 S   s
   | ||fS r   r)   )r   r   r0   r)   r)   r*   
simple_r_s  s   
z8SigningKey.sign_digest_deterministic.<locals>.simple_r_sr   T)	retry_genr   )r   kr4   r   )rH   r3   r   rR   r   r   r;   r   r	   
generate_krU   r0   sign_digestr   )r>   r2   rY   r   r   r4   r   r   r   r   r   r   r0   r)   r)   r*   r   b  s<   .

z$SigningKey.sign_digest_deterministicTc                 C   sH   |p| j }t|}t| jjtr| |S || }| |||||S )a0  
        Create signature over data.

        Uses the probabilistic ECDSA algorithm for Weierstrass curves
        (NIST256p, etc.) and the deterministic EdDSA algorithm for the
        Edwards curves (Ed25519, Ed448).

        This method uses the standard ECDSA algorithm that requires a
        cryptographically secure random number generator.

        It's recommended to use the :func:`~SigningKey.sign_deterministic`
        method instead of this one.

        :param data: data that will be hashed for signing
        :type data: :term:`bytes-like object`
        :param callable entropy: randomness source, :func:`os.urandom` by
            default. Ignored with EdDSA.
        :param hashfunc: hash function to use for hashing the provided
            ``data``.
            If unspecified the default hash function selected during
            object initialisation will be used (see
            :attr:`.VerifyingKey.default_hashfunc`).
            Should behave like :func:`~hashlib.sha1` from :py:mod:`hashlib`.
            The output length of the
            hash (in bytes) must not be longer than the length of the curve
            order (rounded up to the nearest byte), so using SHA256 with
            NIST256p is ok, but SHA256 with NIST192p is not. (In the 2**-96ish
            unlikely event of a hash output larger than the curve order, the
            hash will effectively be wrapped mod n).
            If you want to explicitly allow use of large hashes with small
            curves set the ``allow_truncate`` to ``True``.
            Use ``hashfunc=hashlib.sha1`` to match openssl's
            ``-ecdsa-with-SHA1`` mode,
            or ``hashfunc=hashlib.sha256`` for openssl-1.0.0's
            ``-ecdsa-with-SHA256``.
            Ignored for EdDSA
        :type hashfunc: callable
        :param sigencode: function used to encode the signature.
            The function needs to accept three parameters: the two integers
            that are the signature and the order of the curve over which the
            signature was computed. It needs to return an encoded signature.
            See :func:`~ecdsa.util.sigencode_string` and
            :func:`~ecdsa.util.sigencode_der`
            as examples of such functions.
            Ignored for EdDSA
        :type sigencode: callable
        :param int k: a pre-selected nonce for calculating the signature.
            In typical use cases, it should be set to None (the default) to
            allow its generation from an entropy source.
            Ignored for EdDSA.
        :param bool allow_truncate: if ``True``, the provided digest can have
            bigger bit-size than the order of the curve, the extra bits (at
            the end of the digest) will be truncated. Use it when signing
            SHA-384 output using NIST256p or in similar situations. True by
            default.
            Ignored for EdDSA.

        :raises RSZeroError: in the unlikely event when *r* parameter or
            *s* parameter of the created signature is equal 0, as that would
            leak the key. Caller should try a better entropy source, retry with
            different ``k``, or use the
            :func:`~SigningKey.sign_deterministic` in such case.

        :return: encoded signature of the hash of `data`
        :rtype: bytes or sigencode function dependent type
        )r;   r   rH   r3   r   r   r2   r   )r>   r   r   rY   r   r   r4   hr)   r)   r*   r     s   
K
zSigningKey.signc           	      C   sN   t | jjtrtdt|}t|| j|}| |||\}}|||| jjS )a  
        Create signature over digest using the probabilistic ECDSA algorithm.

        This method uses the standard ECDSA algorithm that requires a
        cryptographically secure random number generator.

        This method does not hash the input.

        It's recommended to use the
        :func:`~SigningKey.sign_digest_deterministic` method
        instead of this one.

        :param digest: hash value that will be signed
        :type digest: :term:`bytes-like object`
        :param callable entropy: randomness source, os.urandom by default
        :param sigencode: function used to encode the signature.
            The function needs to accept three parameters: the two integers
            that are the signature and the order of the curve over which the
            signature was computed. It needs to return an encoded signature.
            See `ecdsa.util.sigencode_string` and `ecdsa.util.sigencode_der`
            as examples of such functions.
        :type sigencode: callable
        :param int k: a pre-selected nonce for calculating the signature.
            In typical use cases, it should be set to None (the default) to
            allow its generation from an entropy source.
        :param bool allow_truncate: if True, the provided digest can have
            bigger bit-size than the order of the curve, the extra bits (at
            the end of the digest) will be truncated. Use it when signing
            SHA-384 output using NIST256p or in similar situations.

        :raises RSZeroError: in the unlikely event when "r" parameter or
            "s" parameter of the created signature is equal 0, as that would
            leak the key. Caller should try a better entropy source, retry with
            different 'k', or use the
            :func:`~SigningKey.sign_digest_deterministic` in such case.

        :return: encoded signature for the `digest` hash
        :rtype: bytes or sigencode function dependent type
        r   )	rH   r3   r   rR   r   r8   sign_numberr   r0   )	r>   r2   r   r   r   r4   r5   r   r   r)   r)   r*   r     s   /zSigningKey.sign_digestc                 C   sl   t | jjtrtd| jj}|dur|}nt||}d|  kr&|k s)J  J | j||}|j|j	fS )a  
        Sign an integer directly.

        Note, this is a low level method, usually you will want to use
        :func:`~SigningKey.sign_deterministic` or
        :func:`~SigningKey.sign_digest_deterministic`.

        :param int number: number to sign using the probabilistic ECDSA
            algorithm.
        :param callable entropy: entropy source, os.urandom by default
        :param int k: pre-selected nonce for signature operation. If unset
            it will be selected at random using the entropy source.

        :raises RSZeroError: in the unlikely event when "r" parameter or
            "s" parameter of the created signature is equal 0, as that would
            leak the key. Caller should try a better entropy source, retry with
            different 'k', or use the
            :func:`~SigningKey.sign_digest_deterministic` in such case.

        :return: the "r" and "s" parameters of the signature
        :rtype: tuple of ints
        r   Nr   )
rH   r3   r   rR   r   r0   r   r   r   r   )r>   r5   r   r   r0   _kr   r)   r)   r*   r   =  s   
zSigningKey.sign_numberr   )rm   r   N)NN)r%   r&   r'   r(   r@   rL   rO   r   r   r   r   r   r   r   rh   rl   rj   rC   r   r   r   r   r   r   r   r   r   r   r   r)   r)   r)   r*   r"     sj    




2-3 .
'
E
B
R
U
:r"   ).r(   rs   hashlibr   r   sixr    r   r   r   r   r	   r
   curvesr   r   r   r   r   utilr   r   r   r   r   r   r   r   r   r   r   _compatr   errorsr   r   r   __all__	Exceptionr   r    r8   objectr!   r"   r)   r)   r)   r*   <module>   s8    	      