o
    Þý°jü;  ã                   @   sž   d dl mZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ ddgZG d	d„ deƒZG d
d„ deƒZG dd„ deƒZG dd„ deƒZddd„ZdS )é    )ÚDerSequence)Úlong_to_bytes)ÚInteger)ÚHMAC)ÚEccKey)ÚDsaKeyÚDssSigSchemeÚnewc                   @   s@   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S )r   zoA (EC)DSA signature object.
    Do not instantiate directly.
    Use :func:`Cryptodome.Signature.DSS.new`.
    c                 C   s6   || _ || _|| _| j ¡ | _| jd d d | _dS )z¤Create a new Digital Signature Standard (DSS) object.

        Do not instantiate this object directly,
        use `Cryptodome.Signature.DSS.new` instead.
        é   é   N)Ú_keyÚ	_encodingÚ_orderÚsize_in_bitsÚ_order_bitsÚ_order_bytes)ÚselfÚkeyÚencodingÚorder© r   ú‹/root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/Cryptodome/Signature/DSS.pyÚ__init__3   s
   zDssSigScheme.__init__c                 C   s
   | j  ¡ S )zRReturn ``True`` if this signature object can be used
        for signing messages.)r   Úhas_private©r   r   r   r   Úcan_signA   s   
zDssSigScheme.can_signc                 C   ó   t dƒ‚©NzTo be provided by subclasses©ÚNotImplementedError©r   Úmsg_hashr   r   r   Ú_compute_nonceG   ó   zDssSigScheme._compute_noncec                 C   r   r   r   r    r   r   r   Ú_valid_hashJ   r#   zDssSigScheme._valid_hashc                    sŠ   ˆ j  ¡ s	tdƒ‚ˆ  |¡stdƒ‚ˆ  |¡}t | ¡ dˆ j	… ¡}ˆ j  
||¡}ˆ jdkr=d ‡ fdd„|D ƒ¡}|S t|ƒ ¡ }|S )a  Compute the DSA/ECDSA signature of a message.

        Args:
          msg_hash (hash object):
            The hash that was carried out over the message.
            The object belongs to the :mod:`Cryptodome.Hash` package.
            Under mode ``'fips-186-3'``, the hash must be a FIPS
            approved secure hash (SHA-2 or SHA-3).

        :return: The signature as ``bytes``
        :raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key
        :raise TypeError: if the (EC)DSA key has no private half
        zPrivate key is needed to signúHash is not sufficiently strongNÚbinaryó    c                    s   g | ]}t |ˆ jƒ‘qS r   )r   r   ©Ú.0Úxr   r   r   Ú
<listcomp>k   s    ÿz%DssSigScheme.sign.<locals>.<listcomp>)r   r   Ú	TypeErrorr$   Ú
ValueErrorr"   r   Ú
from_bytesÚdigestr   Ú_signr   Újoinr   Úencode)r   r!   ÚnonceÚzÚsig_pairÚoutputr   r   r   ÚsignM   s   



ÿþzDssSigScheme.signc              	   C   sH  |   |¡s	tdƒ‚| jdkr1t|ƒd| j krtdƒ‚dd„ |d| j… || jd… fD ƒ\}}n3z
tƒ j|dd	�}W n ttfyH   td
ƒ‚w t|ƒdksS| ¡ sWtdƒ‚t	|d ƒt	|d ƒ}}d|  k ro| j
k rƒn tdƒ‚d|  k r‚| j
k s‡tdƒ‚ tdƒ‚t	 | ¡ d| j… ¡}| j |||f¡}|s¢tdƒ‚dS )a   Check if a certain (EC)DSA signature is authentic.

        Args:
          msg_hash (hash object):
            The hash that was carried out over the message.
            This is an object belonging to the :mod:`Cryptodome.Hash` module.
            Under mode ``'fips-186-3'``, the hash must be a FIPS
            approved secure hash (SHA-2 or SHA-3).

          signature (``bytes``):
            The signature that needs to be validated.

        :raise ValueError: if the signature is not authentic
        r%   r&   é   z'The signature is not authentic (length)c                 S   s   g | ]}t  |¡‘qS r   )r   r.   r(   r   r   r   r+   �   s    ÿz'DssSigScheme.verify.<locals>.<listcomp>NT)Ústrictz$The signature is not authentic (DER)z,The signature is not authentic (DER content)r   r
   z"The signature is not authentic (d)zThe signature is not authenticF)r$   r-   r   Úlenr   r   ÚdecodeÚ
IndexErrorÚhasOnlyIntsr   r   r.   r/   r   Ú_verify)r   r!   Ú	signatureÚr_primeÚs_primeÚder_seqr4   Úresultr   r   r   Úverifyz   s:   

ÿÿÿÿÿzDssSigScheme.verifyN)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r"   r$   r7   rD   r   r   r   r   r   -   s    -c                       sD   e Zd Z‡ fdd„Zdd„ Zdd„ Zdd„ Zd	d
„ Zdd„ Z‡  Z	S )ÚDeterministicDsaSigSchemec                    ó   t t| ƒ |||¡ || _d S ©N)ÚsuperrI   r   Ú_private_key)r   r   r   r   Úprivate_key©Ú	__class__r   r   r   ª   ó   
z"DeterministicDsaSigScheme.__init__c                 C   s8   t  |¡}| j ¡ }t|ƒd }||kr||| L }|S )zSee 2.3.2 in RFC6979r   )r   r.   r   r   r:   )r   ÚbstrrC   Úq_lenÚb_lenr   r   r   Ú	_bits2int®   s   

z#DeterministicDsaSigScheme._bits2intc                 C   s*   d|  k r| j k sJ ‚ J ‚t|| jƒS )zSee 2.3.3 in RFC6979r   )r   r   r   )r   Ú	int_mod_qr   r   r   Ú_int2octets¹   s   z%DeterministicDsaSigScheme._int2octetsc                 C   s.   |   |¡}|| jk r|}n|| j }|  |¡S )zSee 2.3.4 in RFC6979)rU   r   rW   )r   rR   Úz1Úz2r   r   r   Ú_bits2octets¿   s
   



z&DeterministicDsaSigScheme._bits2octetsc                 C   s  |  ¡ }d|j }d|j }dD ]!}t ||| |  | j¡ |  |¡ |¡  ¡ }t |||¡  ¡ }qd}d|  k r?| jk sˆn |dkrXt ||d |¡  ¡ }t |||¡  ¡ }d}t|ƒ| j	k rut |||¡  ¡ }||7 }t|ƒ| j	k sa|  
|¡}d|  k r†| jk r@|S  q@|S )z!Generate k in a deterministic wayó   ó    )r\   r[   éÿÿÿÿr   r'   )r/   Údigest_sizer   r	   rW   rM   rZ   r   r:   r   rU   )r   ÚmhashÚh1Úmask_vÚnonce_kÚint_octr3   Úmask_tr   r   r   r"   É   sD   


ÿþýýÿÿþ
ðïz(DeterministicDsaSigScheme._compute_noncec                 C   s   dS )NTr   r    r   r   r   r$   ñ   s   z%DeterministicDsaSigScheme._valid_hash)
rE   rF   rG   r   rU   rW   rZ   r"   r$   Ú__classcell__r   r   rO   r   rI   §   s    
(rI   c                       s0   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Z‡  ZS )ÚFipsDsaSigScheme))i   é    )é   éà   )rh   é   )i   rj   c                    sR   t t| ƒ |||¡ || _t|jƒ ¡ }|| jf| jvr'd|| jf }t	|ƒ‚d S )Nz+L/N (%d, %d) is not compliant to FIPS 186-3)
rL   rf   r   Ú	_randfuncr   Úpr   r   Ú_fips_186_3_L_Nr-   )r   r   r   r   ÚrandfuncÚLÚerrorrO   r   r   r     s   ÿýzFipsDsaSigScheme.__init__c                 C   s   t jd| j| jd�S ©Nr
   )Úmin_inclusiveÚmax_exclusivern   )r   Úrandom_ranger   rk   r    r   r   r   r"     s   þzFipsDsaSigScheme._compute_noncec                 C   s   |j dkp
|j  d¡S )z*Verify that SHA-1, SHA-2 or SHA-3 are usedz1.3.14.3.2.26z2.16.840.1.101.3.4.2.)ÚoidÚ
startswithr    r   r   r   r$     s   

ÿzFipsDsaSigScheme._valid_hash)rE   rF   rG   rm   r   r"   r$   re   r   r   rO   r   rf   õ   s
    
rf   c                       s,   e Zd Z‡ fdd„Zdd„ Zdd„ Z‡  ZS )ÚFipsEcDsaSigSchemec                    rJ   rK   )rL   rw   r   rk   )r   r   r   r   rn   rO   r   r   r     rQ   zFipsEcDsaSigScheme.__init__c                 C   s   t jd| jjj| jd�S rq   )r   rt   r   Ú_curver   rk   r    r   r   r   r"     s   þz!FipsEcDsaSigScheme._compute_noncec           	      C   sV   | j j ¡ }d}d}d}d}|| | | }z|j|v }W |S  ty*   d}Y |S w )zxVerify that the strength of the hash matches or exceeds
        the strength of the EC. We fail if the hash is too weak.)z2.16.840.1.101.3.4.2.4z2.16.840.1.101.3.4.2.7z2.16.840.1.101.3.4.2.5)z2.16.840.1.101.3.4.2.1z2.16.840.1.101.3.4.2.8z2.16.840.1.101.3.4.2.6)z2.16.840.1.101.3.4.2.2z2.16.840.1.101.3.4.2.9)z2.16.840.1.101.3.4.2.3z2.16.840.1.101.3.4.2.10F)r   ÚpointQr   ru   ÚAttributeError)	r   r!   Úmodulus_bitsÚsha224Úsha256Úsha384Úsha512ÚshsrC   r   r   r   r$   "  s   þþzFipsEcDsaSigScheme._valid_hash)rE   rF   rG   r   r"   r$   re   r   r   rO   r   rw     s    rw   r&   Nc                 C   sÖ   |dvr
t d| ƒ‚t| tƒr | jj}d}| j d¡st dƒ‚nt| tƒr-t| j	ƒ}d}n
t dt
t| ƒƒ ƒ‚|  ¡ rAt| |ƒ}nd}|d	krNt| |||ƒS |d
kret| tƒr^t| |||ƒS t| |||ƒS t d| ƒ‚)a¯
  Create a signature object :class:`DssSigScheme` that
    can perform (EC)DSA signature or verification.

    .. note::
        Refer to `NIST SP 800 Part 1 Rev 4`_ (or newer release) for an
        overview of the recommended key lengths.

    Args:
        key (:class:`Cryptodome.PublicKey.DSA` or :class:`Cryptodome.PublicKey.ECC`):
            The key to use for computing the signature (*private* keys only)
            or for verifying one.
            For DSA keys, let ``L`` and ``N`` be the bit lengths of the modulus ``p``
            and of ``q``: the pair ``(L,N)`` must appear in the following list,
            in compliance to section 4.2 of `FIPS 186-4`_:

            - (1024, 160) *legacy only; do not create new signatures with this*
            - (2048, 224) *deprecated; do not create new signatures with this*
            - (2048, 256)
            - (3072, 256)

            For ECC, only keys over P-224, P-256, P-384, and P-521 are accepted.

        mode (string):
            The parameter can take these values:

            - ``'fips-186-3'``. The signature generation is randomized and carried out
              according to `FIPS 186-3`_: the nonce ``k`` is taken from the RNG.
            - ``'deterministic-rfc6979'``. The signature generation is not
              randomized. See RFC6979_.

        encoding (string):
            How the signature is encoded. This value determines the output of
            :meth:`sign` and the input to :meth:`verify`.

            The following values are accepted:

            - ``'binary'`` (default), the signature is the raw concatenation
              of ``r`` and ``s``. It is defined in the IEEE P.1363 standard.
              For DSA, the size in bytes of the signature is ``N/4`` bytes
              (e.g. 64 for ``N=256``).
              For ECDSA, the signature is always twice the length of a point
              coordinate (e.g. 64 bytes for P-256).

            - ``'der'``, the signature is a ASN.1 DER SEQUENCE
              with two INTEGERs (``r`` and ``s``). It is defined in RFC3279_.
              The size of the signature is variable.

        randfunc (callable):
            A function that returns random ``bytes``, of a given length.
            If omitted, the internal RNG is used.
            Only applicable for the *'fips-186-3'* mode.

    .. _FIPS 186-3: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
    .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    .. _NIST SP 800 Part 1 Rev 4: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r4.pdf
    .. _RFC6979: http://tools.ietf.org/html/rfc6979
    .. _RFC3279: https://tools.ietf.org/html/rfc3279#section-2.2.2
    )r&   ÚderzUnknown encoding '%s'ÚdÚNISTz ECC key is not on a NIST P curver*   zUnsupported key type Nzdeterministic-rfc6979z
fips-186-3zUnknown DSS mode '%s')r-   Ú
isinstancer   rx   r   Úcurverv   r   r   ÚqÚstrÚtyper   ÚgetattrrI   rw   rf   )r   Úmoder   rn   r   Úprivate_key_attrrN   r   r   r   r	   6  s,   B
ÿ


)r&   N)ÚCryptodome.Util.asn1r   ÚCryptodome.Util.numberr   ÚCryptodome.Math.Numbersr   ÚCryptodome.Hashr   ÚCryptodome.PublicKey.ECCr   ÚCryptodome.PublicKey.DSAr   Ú__all__Úobjectr   rI   rf   rw   r	   r   r   r   r   Ú<module>   s   !zN"