U
    nciB                     @   s   d Z ddlmZ ddlmZmZmZmZ ddl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
lmZ ddlmZ ddlZ	ddlmZ ddlmZ dZe Ze ZeG dd dZG dd dej Z!G dd dej"ej#Z$dS )zAECDSA verifier and signer that use the ``cryptography`` library.
    )	dataclass)AnyDictOptionalUnionN)backends)hashes)serialization)ec)padding)decode_dss_signature)encode_dss_signature)_helpers)bases   -----BEGIN CERTIFICATE-----c                   @   s^   e Zd ZU dZeed< ejed< eed< e	e
ejejf dddZe	ejdd	d
ZdS )_ESAttributeszA class that models ECDSA attributes.

    Attributes:
        rs_size (int): Size for ASN.1 r and s size.
        sha_algo (hashes.HashAlgorithm): Hash algorithm.
        algorithm (str): Algorithm name.
    rs_sizesha_algo	algorithm)keyc                 C   s   |  |jS N)
from_curvecurve)clsr    r   8/tmp/pip-unpacked-wheel-fpe1mg0e/google/auth/crypt/es.pyfrom_key6   s    z_ESAttributes.from_key)r   c                 C   s0   t |tjr| dt dS | dt dS d S )N0   ZES384    ZES256)
isinstancer
   Z	SECP384R1r   SHA384SHA256)r   r   r   r   r   r   <   s    z_ESAttributes.from_curveN)__name__
__module____qualname____doc__int__annotations__r   ZHashAlgorithmstrclassmethodr   r
   EllipticCurvePublicKeyEllipticCurvePrivateKeyr   ZEllipticCurver   r   r   r   r   r   (   s   

r   c                   @   s\   e Zd ZdZejddddZee	j
eeedddZeeeef d dd	d
ZdS )
EsVerifierzVerifies ECDSA cryptographic signatures using public keys.

    Args:
        public_key (
                cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey):
            The public key used to verify signatures.
    N)
public_keyreturnc                 C   s   || _ t|| _d S r   )_pubkeyr   r   _attributes)selfr,   r   r   r   __init__R   s    zEsVerifier.__init__)message	signaturer-   c              	   C   s   t |}t|| jjd kr"dS tj|d | jj dd}tj|| jjd  dd}t||}t |}z | j	||t
| jj W dS  ttjjfk
r   Y dS X d S )N   Fbig	byteorderT)r   to_byteslenr/   r   r%   
from_bytesr   r.   verifyr
   ECDSAr   
ValueErrorcryptography
exceptionsZInvalidSignature)r0   r2   r3   Z	sig_bytesrsZasn1_sigr   r   r   r;   V   s    


zEsVerifier.verifyc                 C   sR   t |}t|kr*tj|t}| }nt	|t}t
|tjsJtd| |S )ay  Construct an Verifier instance from a public key or public
        certificate string.

        Args:
            public_key (Union[str, bytes]): The public key in PEM format or the
                x509 public key certificate.

        Returns:
            Verifier: The constructed verifier.

        Raises:
            ValueError: If the public key can't be parsed.
        z2Expected public key of type EllipticCurvePublicKey)r   r8   _CERTIFICATE_MARKERr>   x509Zload_pem_x509_certificate_BACKENDr,   r	   Zload_pem_public_keyr   r
   r)   	TypeError)r   r,   Zpublic_key_datacertZpubkeyr   r   r   from_stringg   s    
 
zEsVerifier.from_string)r!   r"   r#   r$   r
   r)   r1   r   copy_docstringr   Verifierbytesboolr;   r(   r   r'   rG   r   r   r   r   r+   I   s   
r+   c                   @   s   e Zd ZdZdejee ddddZe	edddZ
e	eejee dd	d
ZeejeedddZedeeef ee d dddZeeef dddZeeef ddddZdS )EsSignera  Signs messages with an ECDSA private key.

    Args:
        private_key (
                cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey):
            The private key to sign with.
        key_id (str): Optional key ID used to identify this private key. This
            can be useful to associate the private key with its associated
            public key or certificate.
    N)private_keykey_idr-   c                 C   s   || _ || _t|| _d S r   )_key_key_idr   r   r/   )r0   rM   rN   r   r   r   r1      s    zEsSigner.__init__)r-   c                 C   s   | j jS )zkName of the algorithm used to sign messages.
        Returns:
            str: The algorithm name.
        )r/   r   r0   r   r   r   r      s    zEsSigner.algorithmc                 C   s   | j S r   )rP   rQ   r   r   r   rN      s    zEsSigner.key_id)r2   r-   c                 C   sR   t |}| j|t| jj}t|\}}|j| jj	dd|j| jj	dd S )Nr5   r6   )
r   r8   rO   signr
   r<   r/   r   r   r   )r0   r2   Zasn1_signaturer@   rA   r   r   r   rR      s    
 zEsSigner.sign)r   rN   r-   c                 C   s:   t |}tj|dtd}t|tjs.td| ||dS )al  Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        N)passwordbackendz4Expected private key of type EllipticCurvePrivateKey)rN   )	r   r8   r	   load_pem_private_keyrD   r   r
   r*   rE   )r   r   rN   	key_bytesrM   r   r   r   rG      s    
  zEsSigner.from_stringc                 C   s0   | j  }| jjtjjtjjt	 d|d< |S )z1Pickle helper that serializes the _key attribute.)encodingformatZencryption_algorithmrO   )
__dict__copyrO   Zprivate_bytesr	   EncodingZPEMZPrivateFormatZPKCS8ZNoEncryptionr0   stater   r   r   __getstate__   s    

zEsSigner.__getstate__)r]   r-   c                 C   s$   t |d d|d< | j| dS )z3Pickle helper that deserializes the _key attribute.rO   N)r	   rU   rY   updater\   r   r   r   __setstate__   s    zEsSigner.__setstate__)N)N)r!   r"   r#   r$   r
   r*   r   r'   r1   propertyr   r   rH   r   SignerrN   rJ   rR   r(   r   rG   r   r   r^   r`   r   r   r   r   rL      s.     


 
 
rL   )%r$   Zdataclassesr   typingr   r   r   r   Zcryptography.exceptionsr>   Zcryptography.hazmatr   Zcryptography.hazmat.primitivesr   r	   Z)cryptography.hazmat.primitives.asymmetricr
   r   Z/cryptography.hazmat.primitives.asymmetric.utilsr   r   Zcryptography.x509Zgoogle.authr   Zgoogle.auth.cryptr   rB   Zdefault_backendrD   ZPKCS1v15Z_PADDINGr   rI   r+   rb   ZFromServiceAccountMixinrL   r   r   r   r   <module>   s(    >