o
    n~b4                     @   sz   d dl mZmZmZ d dlZd dlmZmZmZ d dl	m
Z
 d dlmZ G dd dZdd	 Zd
d Zdd Zdd ZdS )    )bchrbord
iter_rangeN)ceil_divlong_to_bytesbytes_to_long)strxor)Randomc                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )PSS_SigSchemezzA signature object for ``RSASSA-PSS``.
    Do not instantiate directly.
    Use :func:`Cryptodome.Signature.pss.new`.
    c                 C   s   || _ || _|| _|| _dS )at  Initialize this PKCS#1 PSS signature scheme object.

        :Parameters:
          key : an RSA key object
            If a private half is given, both signature and
            verification are possible.
            If a public half is given, only verification is possible.
          mgfunc : callable
            A mask generation function that accepts two parameters:
            a string to use as seed, and the lenth of the mask to
            generate, in bytes.
          saltLen : integer
            Length of the salt, in bytes.
          randfunc : callable
            A function that returns random bytes.
        N)_key_saltLen_mgfunc	_randfunc)selfkeyZmgfuncZsaltLenZrandfunc r   C/usr/local/lib/python3.10/dist-packages/Cryptodome/Signature/pss.py__init__/   s   
zPSS_SigScheme.__init__c                 C   s
   | j  S )z<Return ``True`` if this object can be used to sign messages.)r   Zhas_private)r   r   r   r   can_signF   s   
zPSS_SigScheme.can_signc           
         s   | j du r	 j}n| j }| jdu r fdd}n| j}tjj| jj}t	|d}t
 |d | j||}t|}| j|}t||}	|	S )a  Create the PKCS#1 PSS signature of a message.

        This function is also called ``RSASSA-PSS-SIGN`` and
        it is specified in
        `section 8.1.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#section-8.1.1>`_.

        :parameter msg_hash:
            This is an object from the :mod:`Cryptodome.Hash` package.
            It has been used to digest the message to sign.
        :type msg_hash: hash object

        :return: the signature encoded as a *byte string*.
        :raise ValueError: if the RSA key is not long enough for the given hash algorithm.
        :raise TypeError: if the RSA key has no private half.
        Nc                       t | | S NMGF1xymsg_hashr   r   <lambda>b       z$PSS_SigScheme.sign.<locals>.<lambda>      )r   digest_sizer   
CryptodomeUtilnumbersizer   nr   _EMSA_PSS_ENCODEr   r   Z_decryptr   )
r   r   sLenmgfmodBitskemem_intZm_int	signaturer   r   r   signJ   s   



zPSS_SigScheme.signc                    s   | j du r	 j}n| j }| jr| j}n fdd}tjj| jj}t	|d}t
||kr1tdt|}| j|}t	|d d}	t||	}
t |
|d || dS )at  Check if the  PKCS#1 PSS signature over a message is valid.

        This function is also called ``RSASSA-PSS-VERIFY`` and
        it is specified in
        `section 8.1.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#section-8.1.2>`_.

        :parameter msg_hash:
            The hash that was carried out over the message. This is an object
            belonging to the :mod:`Cryptodome.Hash` module.
        :type parameter: hash object

        :parameter signature:
            The signature that needs to be validated.
        :type signature: bytes

        :raise ValueError: if the signature is not valid.
        Nc                    r   r   r   r   r   r   r   r      r   z&PSS_SigScheme.verify.<locals>.<lambda>r    Incorrect signaturer!   )r   r"   r   r#   r$   r%   r&   r   r'   r   len
ValueErrorr   Z_encryptr   _EMSA_PSS_VERIFY)r   r   r/   r)   r*   r+   r,   Zsignature_intr.   emLenr-   r   r   r   verifyt   s   


zPSS_SigScheme.verifyN)__name__
__module____qualname____doc__r   r   r0   r6   r   r   r   r   r
   )   s    *r
   c                 C   sb   d}t t||jD ]}t|d}| }|| |  ||  }q
t||ks+J |d| S )a  Mask Generation Function, described in `B.2.1 of RFC8017
    <https://tools.ietf.org/html/rfc8017>`_.

    :param mfgSeed:
        seed from which the mask is generated
    :type mfgSeed: byte string

    :param maskLen:
        intended length in bytes of the mask
    :type maskLen: integer

    :param hash_gen:
        A module or a hash object from :mod:`Cryptodome.Hash`
    :type hash_object:

    :return: the mask, as a *byte string*
           N)r   r   r"   r   newupdatedigestr2   )ZmgfSeedZmaskLenZhash_genTcounterchobjr   r   r   r      s   
r   c                 C   s  t |d}d}td| | D ]}|d? dB }q|| j| d k r%td||}tdd |   | }	|  }
|
|	 td|| | j d  }|td | }||
 || j d }t||}tt	|d | @ |dd  }||
  td }|S )	a  
    Implement the ``EMSA-PSS-ENCODE`` function, as defined
    in PKCS#1 v2.1 (RFC3447, 9.1.1).

    The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M``
    as input, and hash it internally. Here, we expect that the message
    has already been hashed instead.

    :Parameters:
      mhash : hash object
        The hash object that holds the digest of the message being signed.
      emBits : int
        Maximum length of the final encoding, in bits.
      randFunc : callable
        An RNG function that accepts as only parameter an int, and returns
        a string of random bytes, to be used as salt.
      mgf : callable
        A mask generation function that accepts two parameters: a string to
        use as seed, and the lenth of the mask to generate, in bytes.
      sLen : int
        Length of the salt, in bytes.

    :Return: An ``emLen`` byte long string that encodes the hash
      (with ``emLen = \ceil(emBits/8)``).

    :Raise ValueError:
        When digest or salt length are too big.
    r    r   r!         z6Digest or salt length are too long for given key size.N   )
r   r   r"   r3   r   r?   r=   r>   r   r   )mhashemBitsZrandFuncr*   r)   r5   lmaskisaltm_primehZpsdbdbMaskmaskedDBr-   r   r   r   r(      s"   


"r(   c                 C   s|  t |d}d}td| | D ]}|d? dB }q|| j| d k r%tdt|dd d	kr3td|d|| j d  }||| j d d }	|t|d @ rUtd||	|| j d }
t||
}tt|d | @ |dd  }|td|| j | d  td std|dkr|| d }nd
}tdd | 	  | }| 
 }|| |	 }|	|krtddS )a  
    Implement the ``EMSA-PSS-VERIFY`` function, as defined
    in PKCS#1 v2.1 (RFC3447, 9.1.2).

    ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,
    and hash it internally. Here, we expect that the message has already
    been hashed instead.

    :Parameters:
      mhash : hash object
        The hash object that holds the digest of the message to be verified.
      em : string
        The signature to verify, therefore proving that the sender really
        signed the message that was received.
      emBits : int
        Length of the final encoding (em), in bits.
      mgf : callable
        A mask generation function that accepts two parameters: a string to
        use as seed, and the lenth of the mask to generate, in bytes.
      sLen : int
        Length of the salt, in bytes.

    :Raise ValueError:
        When the encoding is inconsistent, or the digest or salt lengths
        are too big.
    r    r   r!   rD   rE   r1   NrF   r;   )r   r   r"   r3   ordr   r   r   
startswithr?   r=   r>   )rG   r-   rH   r*   r)   r5   rI   rJ   rP   rM   rO   rN   rK   rL   rC   hpr   r   r   r4      s6   

"(
r4   c                 K   sX   | dd}| dd}| dd}|du rtj}|r%tdt|  t| |||S )a  Create an object for making or verifying PKCS#1 PSS signatures.

    :parameter rsa_key:
      The RSA key to use for signing or verifying the message.
      This is a :class:`Cryptodome.PublicKey.RSA` object.
      Signing is only possible when ``rsa_key`` is a **private** RSA key.
    :type rsa_key: RSA object

    :Keyword Arguments:

        *   *mask_func* (``callable``) --
            A function that returns the mask (as `bytes`).
            It must accept two parameters: a seed (as `bytes`)
            and the length of the data to return.

            If not specified, it will be the function :func:`MGF1` defined in
            `RFC8017 <https://tools.ietf.org/html/rfc8017#page-67>`_ and
            combined with the same hash algorithm applied to the
            message to sign or verify.

            If you want to use a different function, for instance still :func:`MGF1`
            but together with another hash, you can do::

                from Cryptodome.Hash import SHA256
                from Cryptodome.Signature.pss import MGF1
                mgf = lambda x, y: MGF1(x, y, SHA256)

        *   *salt_bytes* (``integer``) --
            Length of the salt, in bytes.
            It is a value between 0 and ``emLen - hLen - 2``, where ``emLen``
            is the size of the RSA modulus and ``hLen`` is the size of the digest
            applied to the message to sign or verify.

            The salt is generated internally, you don't need to provide it.

            If not specified, the salt length will be ``hLen``.
            If it is zero, the signature scheme becomes deterministic.

            Note that in some implementations such as OpenSSL the default
            salt length is ``emLen - hLen - 2`` (even though it is not more
            secure than ``hLen``).

        *   *rand_func* (``callable``) --
            A function that returns random ``bytes``, of the desired length.
            The default is :func:`Cryptodome.Random.get_random_bytes`.

    :return: a :class:`PSS_SigScheme` signature object
    	mask_funcNZ
salt_bytes	rand_funczUnknown keywords: )popr	   Zget_random_bytesr3   strkeysr
   )Zrsa_keykwargsrU   Zsalt_lenrV   r   r   r   r=   I  s   2r=   )ZCryptodome.Util.py3compatr   r   r   ZCryptodome.Util.numberr#   r   r   r   ZCryptodome.Util.strxorr   r	   r
   r   r(   r4   r=   r   r   r   r   <module>   s   z@I