o
    -׾gx                     @   sj  d dl mZmZmZmZ d dlZd dlZd dlZd dlZddl	m
Z
mZmZmZmZmZmZmZmZmZmZmZ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)m*Z* G d
d dZ+G dd dZ,G dd dZ-dd Z.dd Z/e e!ee"edZ0dd Z1dd Z2d%ddZ3d%ddZ4dd Z5dd  Z6d!d" Z7d#d$ Z8dS )&    )unicode_literalsdivisionabsolute_importprint_functionN   )CertBagCertificateDSAPrivateKeyECPrivateKeyEncryptedDataEncryptedPrivateKeyInfoIntegerOctetStringPfxPrivateKeyInfoPublicKeyInfoRSAPrivateKeyRSAPublicKeySafeContentsunarmor)pbkdf1pbkdf2
pkcs12_kdf)aes_cbc_pkcs7_decryptdes_cbc_pkcs5_decryptrc2_cbc_pkcs5_decryptrc4_decrypttripledes_cbc_pkcs5_decrypt)constant_compare)pretty_message)byte_clsstr_cls	type_namec                   @   sL   e Zd ZdZdZdd Zedd Zedd Zedd	 Z	ed
d Z
dS )_PrivateKeyBaseNc                 C   s   | j dkr| jd jS | j dkr/| jd d }td|d |d |d	 | j | jd jd
S | j dkrL| jd j}| jd d |d< | j |d< |S dS )a.  
        Unwraps the private key into an asn1crypto.keys.RSAPrivateKey,
        asn1crypto.keys.DSAPrivateKey or asn1crypto.keys.ECPrivateKey object

        :return:
            An asn1crypto.keys.RSAPrivateKey, asn1crypto.keys.DSAPrivateKey or
            asn1crypto.keys.ECPrivateKey object
        rsaprivate_keydsaprivate_key_algorithm
parametersr   pqgversionr)   r*   r+   
public_keyr%   ecr.   N)	algorithmasn1parsedr	   r.   unwrap)selfparamsoutput r7   ^/var/www/html/backend_erp/backend_erp_env/lib/python3.10/site-packages/oscrypto/_asymmetric.pyr3   -   s$   




	z_PrivateKeyBase.unwrapc                 C      | j jS zO
        :return:
            A unicode string of "rsa", "dsa" or "ec"
        r1   r0   r4   r7   r7   r8   r0   K      z_PrivateKeyBase.algorithmc                 C      | j jd S H
        :return:
            A unicode string of EC curve name
        r   r1   curver<   r7   r7   r8   rB   T      z_PrivateKeyBase.curvec                 C   r9   zS
        :return:
            The number of bits in the key, as an integer
        r1   bit_sizer<   r7   r7   r8   rF   ]   r=   z_PrivateKeyBase.bit_sizec                 C   r9   zT
        :return:
            The number of bytes in the key, as an integer
        r1   	byte_sizer<   r7   r7   r8   rI   f   r=   z_PrivateKeyBase.byte_size)__name__
__module____qualname__r1   _fingerprintr3   propertyr0   rB   rF   rI   r7   r7   r7   r8   r#   (   s    


r#   c                   @   sX   e Zd ZdZdZdd Zedd Zedd Zedd	 Z	ed
d Z
edd ZdS )_PublicKeyBaseNc                 C   s    | j dkr
| jd S | jd jS )a7  
        Unwraps a public key into an asn1crypto.keys.RSAPublicKey,
        asn1crypto.core.Integer (for DSA) or asn1crypto.keys.ECPointBitString
        object

        :return:
            An asn1crypto.keys.RSAPublicKey, asn1crypto.core.Integer or
            asn1crypto.keys.ECPointBitString object
        r/   r.   )r0   r1   r2   r<   r7   r7   r8   r3   u   s   

z_PublicKeyBase.unwrapc                 C   s   | j du rt | jd| _ | j S )aZ  
        Creates a fingerprint that can be compared with a private key to see if
        the two form a pair.

        This fingerprint is not compatible with fingerprints generated by any
        other software.

        :return:
            A byte string that is a sha256 hash of selected components (based
            on the key type)
        N)rM   r1   r<   r7   r7   r8   fingerprint   s   
z_PublicKeyBase.fingerprintc                 C   r9   r:   r;   r<   r7   r7   r8   r0      r=   z_PublicKeyBase.algorithmc                 C   r>   r?   rA   r<   r7   r7   r8   rB      rC   z_PublicKeyBase.curvec                 C   r9   rD   rE   r<   r7   r7   r8   rF      r=   z_PublicKeyBase.bit_sizec                 C   r9   rG   rH   r<   r7   r7   r8   rI      r=   z_PublicKeyBase.byte_size)rJ   rK   rL   r1   rM   r3   rN   rP   r0   rB   rF   rI   r7   r7   r7   r8   rO   p   s    



rO   c                   @   s@   e Zd ZdZedd Zedd Zedd Zedd	 ZdS )
_CertificateBaseNc                 C   r9   r:   )r.   r0   r<   r7   r7   r8   r0      r=   z_CertificateBase.algorithmc                 C   r9   )r@   )r.   rB   r<   r7   r7   r8   rB      r=   z_CertificateBase.curvec                 C   r9   )zZ
        :return:
            The number of bits in the public key, as an integer
        )r.   rF   r<   r7   r7   r8   rF      r=   z_CertificateBase.bit_sizec                 C   r9   )z[
        :return:
            The number of bytes in the public key, as an integer
        )r.   rI   r<   r7   r7   r8   rI      r=   z_CertificateBase.byte_size)	rJ   rK   rL   r1   rN   r0   rB   rF   rI   r7   r7   r7   r8   rQ      s    


rQ   c                 C   s   | j }|dks|dkr| d jS |dkr=| d d }| d j}td|d |d	 |d
 tt|d
 j|j|d j|dS |dkrP| d j}| d d |d< |S td| j  )a  
    Unwraps an asn1crypto.keys.PrivateKeyInfo object into an
    asn1crypto.keys.RSAPrivateKey, asn1crypto.keys.DSAPrivateKey
    or asn1crypto.keys.ECPrivateKey.

    :param key_info:
        An asn1crypto.keys.PrivateKeyInfo object

    :return:
        One of:
         - asn1crypto.keys.RSAPrivateKey
         - asn1crypto.keys.DSAPrivateKey
         - asn1crypto.keys.ECPrivateKey
    r$   
rsassa_pssr%   r&   r'   r(   r   r)   r*   r+   r,   r/   z#Unsupported key_info.algorithm "%s")r0   r2   r	   r   pownative
ValueError)key_infokey_algr5   r2   r7   r7   r8   _unwrap_private_key_info   s.   


rX   c                 C   s  t | tr| d j}| jdkrd|d j|d jf }nZ| jdkrL| d d }tt|d	 j| d jj|d
 j}d|d
 j|d j|d	 j|jf }n*| jdkrv|d j}|du rf|| j}|jd jj}d| j	d  }|
d}||7 }t |tr|
d}t| S t | tr| jdkr| d j}d|d j|d jf }n=| jdkr| d j}| d d }d|d
 j|d j|d	 j|jf }n| jdkr| d j}d| j	d  }|
d}||7 }t |tr|
d}t| S ttdt| )a5  
    Returns a fingerprint used for correlating public keys and private keys

    :param key_object:
        An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo

    :raises:
        ValueError - when the key_object is not of the proper type

    ;return:
        A byte string fingerprint
    r%   r$   z%d:%dmoduluspublic_exponentr&   r'   r(   r+   r)   z%d:%d:%d:%dr*   r/   r.   Nz%s:r   zutf-8r0   z
        key_object must be an instance of the
        asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo
        classes, not %s
        )
isinstancer   r2   r0   rT   r   rS   r.   r1   rB   encoder!   hashlibsha256digestr   rU   r   r"   )
key_objectload_private_keykeyto_hashr5   r.   public_key_objectr7   r7   r8   rM     sv   




















rM   )rc2rc4des	tripledesaesc                 C   s   t | tsttdt| d}td| dur3t| \}}} |dkr)ttd|dkr3t	
| dS |du s;|dkrizt	| }|j |W S  tyO   Y nw zt| }|j t	
|dW S  tyh   Y nw |du sq|dkrzt| }|d	 d
 }|W S  ty   Y tdw td)a  
    Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
    EC public keys. For RSA keys, both the old RSAPublicKey and
    SubjectPublicKeyInfo structures are supported. Also allows extracting a
    public key from an X.509 certificate.

    :param data:
        A byte string to load the public key from

    :raises:
        ValueError - when the data does not appear to contain a public key

    :return:
        An asn1crypto.keys.PublicKeyInfo object
    <
            data must be a byte string, not %s
            N   \s*-----private keyz
                The data specified does not appear to be a public key or
                certificate, but rather a private key
                r$   
public keycertificatetbs_certificatesubject_public_key_infozQThe data specified does not appear to be a known public key or certificate format)r[   r    	TypeErrorr   r"   rematch_unarmor_pemrU   r   wraploadrT   r   r   )datakey_typealgopkirpkparsed_certrV   r7   r7   r8   parse_public~  sN   




r}   c                 C   s   t | tsttdt| d}td| dur3t| \}}} |dkr)ttd|dkr3ttd|du s;|dkrKzt	
| W S  tyJ   Y nw ttd	)
a@  
    Loads a certificate from a DER or PEM-formatted file. Supports X.509
    certificates only.

    :param data:
        A byte string to load the certificate from

    :raises:
        ValueError - when the data does not appear to contain a certificate

    :return:
        An asn1crypto.x509.Certificate object
    rj   Nrk   rl   z
                The data specified does not appear to be a certificate, but
                rather a private key
                rm   z
                The data specified does not appear to be a certificate, but
                rather a public key
                rn   zU
        The data specified does not appear to be a known certificate format
        )r[   r    rq   r   r"   rr   rs   rt   rU   r   rv   )rw   rx   _r7   r7   r8   parse_certificate  s2   
r   c           
      C   s  t | tsttdt| |dur!t |ts ttdt|nd}td| durGt| |\}}} |dkr=ttd|dkrGttd	zt	
| }|j |W S  ty[   Y nw zt
| }|d
 }|d j}t|||}t	
|}|j |W S  ty   Y nw zt
| }	|	j t	|	dW S  ty   Y nw zt
| }	|	j t	|	dW S  ty   Y nw zt
| }	|	j t	|	dW S  ty   Y nw ttd)a%  
    Loads a private key from a DER or PEM-formatted file. Supports RSA, DSA and
    EC private keys. Works with the follow formats:

     - RSAPrivateKey (PKCS#1)
     - ECPrivateKey (SECG SEC1 V2)
     - DSAPrivateKey (OpenSSL)
     - PrivateKeyInfo (RSA/DSA/EC - PKCS#8)
     - EncryptedPrivateKeyInfo (RSA/DSA/EC - PKCS#8)
     - Encrypted RSAPrivateKey (PEM only, OpenSSL)
     - Encrypted DSAPrivateKey (PEM only, OpenSSL)
     - Encrypted ECPrivateKey (PEM only, OpenSSL)

    :param data:
        A byte string to load the private key from

    :param password:
        The password to unencrypt the private key

    :raises:
        ValueError - when the data does not appear to contain a private key, or the password is invalid

    :return:
        An asn1crypto.keys.PrivateKeyInfo object
    rj   NH
                password must be a byte string, not %s
                    rk   rm   z
                The data specified does not appear to be a private key, but
                rather a public key
                rn   z
                The data specified does not appear to be a private key, but
                rather a certificate
                encryption_algorithmencrypted_datar$   r&   r/   zU
        The data specified does not appear to be a known private key format
        )r[   r    rq   r   r"   rr   rs   rt   rU   r   rv   rT   r   _decrypt_encrypted_datar   ru   r	   r
   )
rw   passwordrx   r~   rz   parsed_wrapperencryption_algorithm_infor   decrypted_datar2   r7   r7   r8   parse_private  s   








r   c           
      C   s   t | \}}}d}t||}|sttd|d}|  } |tg dv r8|d }d|t	|||fS | }	d}|	dkrEd}	n|	d	krMd
}	d}|	||fS )a3  
    Removes PEM-encoding from a public key, private key or certificate. If the
    private key is encrypted, the password will be used to decrypt it.

    :param data:
        A byte string of the PEM-encoded data

    :param password:
        A byte string of the encryption password, or None

    :return:
        A 3-element tuple in the format: (key_type, algorithm, der_bytes). The
        key_type will be a unicode string of "public key", "private key" or
        "certificate". The algorithm will be a unicode string of "rsa", "dsa"
        or "ec".
    zc^((DSA|EC|RSA) PRIVATE KEY|ENCRYPTED PRIVATE KEY|PRIVATE KEY|PUBLIC KEY|RSA PUBLIC KEY|CERTIFICATE)zx
            data does not seem to contain a PEM-encoded certificate, private
            key or public key
            r   )zRSA PRIVATE KEYzDSA PRIVATE KEYzEC PRIVATE KEY   rl   Nzencrypted private keyzrsa public keyrm   r$   )
r   rr   rs   rU   r   groupstripsetlower_unarmor_pem_openssl_private)
rw   r   object_typeheaders	der_bytes
type_regex
armor_type
pem_headerry   rx   r7   r7   r8   rt   v  s(   

rt   c                 C   s  d}d}d}d| v r!| d }| ddkr| d\}}nd}|s%|S |r/t|d}| }i ddd	dd
dddddddddddddddddddddddddddddddd| }t||dd  	 }|t
|kr|t|| |dd  	 7 }|t
|ks|d| }i ddd	dd
ddddddddddddddddddddddd dd dd dd d!d!d| }	t|	 }
|	dkr|
||S |
|||S )"a  
    Parses a PKCS#1 private key, or encrypted private key

    :param headers:
        A dict of "Name: Value" lines from right after the PEM header

    :param data:
        A byte string of the DER-encoded PKCS#1 private key

    :param password:
        A byte string of the password to use if the private key is encrypted

    :return:
        A byte string of the DER-encoded private key
    NzDEK-Info,RC4asciizaes-128-cbc   zaes-128zaes-192-cbc   zaes-192zaes-256-cbc    zaes-256rf   zrc4-64   zrc4-40   z
rc2-64-cbcz
rc2-40-cbczrc2-cbcre   zdes-ede3-cbczdes-ede3des3zdes-ede-cbc)zdes-cbcrg   r   ri   rh   rg   )findr   splitbinascii	unhexlifyr\   r   r]   md5r_   lencrypto_funcs)r   rw   r   enc_algo
enc_iv_hexenc_ivr5   enc_key_lengthenc_keyenc_algo_namedecrypt_funcr7   r7   r8   r     s   	
"	

r   c                    s  t | tsttdt| |dur!t |ts ttdt|nd}i  i }t| }|d }|d jdkr=ttd|j	}|d	 }|r|d
 d d j}dddddddd| }	t
|||d j|d j|	d}
tt|}t|
|d j| }|d
 d j}t||std|D ];}|d }t |trt|j ||| qt |tr|d }|d }|d j}t|||}t| ||| qttdt| }t  }tt||@ }d}d}g }t|dkr|d | }  } fdd  D }|||fS t|dkrtt| d }|| }t dkr2tt  d } | } |= t dkrEtt  d!d" d#}|||fS )$aY  
    Parses a PKCS#12 ANS.1 DER-encoded structure and extracts certs and keys

    :param data:
        A byte string of a DER-encoded PKCS#12 file

    :param password:
        A byte string of the password to any encrypted data

    :param load_private_key:
        A callable that will accept a byte string and return an
        oscrypto.asymmetric.PrivateKey object

    :raises:
        ValueError - when any of the parameters are of the wrong type or value
        OSError - when an error is returned by one of the OS decryption functions

    :return:
        A three-element tuple of:
         1. An asn1crypto.keys.PrivateKeyInfo object
         2. An asn1crypto.x509.Certificate object
         3. A list of zero or more asn1crypto.x509.Certificate objects that are
            "extra" certificates, possibly intermediates from the cert chain
    rj   Nr   r   	auth_safecontent_typerw   zV
            Only password-protected PKCS12 files are currently supported
            mac_datamacdigest_algorithmr0         r   0   @   )sha1sha224r^   sha384sha512
sha512_224
sha512_256mac_salt
iterations   contentr_   zPassword provided is invalidencrypted_content_infocontent_encryption_algorithmencrypted_contentz[
                Public-key-based PKCS12 files are not currently supported
                r   r   c                    s   g | ]
}|kr | qS r7   r7   ).0fcertsrP   r7   r8   
<listcomp>|  s    z!_parse_pkcs12.<locals>.<listcomp>c                 S   r9   N)subjecthuman_friendly)cr7   r7   r8   <lambda>  s    z_parse_pkcs12.<locals>.<lambda>)rb   )r[   r    rq   r   r"   r   rv   rT   rU   authenticated_safer   getattrr]   hmacnewcontentsr_   r   r   _parse_safe_contentsr   r   r   keyssortedlistr   values)rw   r   ra   private_keyspfxr   r   r   mac_algo
key_lengthmac_keyhash_modcomputed_hmacstored_hmaccontent_infor   r   r   r   decrypted_contentkey_fingerprintscert_fingerprintscommon_fingerprintsrb   certother_certs	first_keyr7   r   r8   _parse_pkcs12  s   


	






r   c                 C   s   t | tr
t| } | D ]e}|d }t |tr4|d jdkr3|d j}|d d }|d j|t|d< qt |trA||t||< qt |t	rb|d }	|d	 j}
t
|	|
|}t|}||t||< qt |trpt||||| q	 qdS )
a&  
    Parses a SafeContents PKCS#12 ANS.1 structure and extracts certs and keys

    :param safe_contents:
        A byte string of ber-encoded SafeContents, or a asn1crypto.pkcs12.SafeContents
        parsed object

    :param certs:
        A dict to store certificates in

    :param keys:
        A dict to store keys in

    :param password:
        A byte string of the password to any encrypted data

    :param load_private_key:
        A callable that will accept a byte string and return an
        oscrypto.asymmetric.PrivateKey object
    	bag_valuecert_idx509
cert_valuero   rp   Nr   r   )r[   r    r   rv   r   rT   r2   rM   r   r   r   r   )safe_contentsr   r   r   ra   safe_bagr   r   public_key_infor   encrypted_key_bytesdecrypted_key_bytesr%   r7   r7   r8   r     s,   








r   c                 C   s  t | j }| jdkr,| jdkrttdt| j|| j| j| j	}| j
}||||}|S | jdkrSt| j|| j| j| j	d }|dd }|dd }||||}|S | jdkrt| j|| j| j| j	d	}| jd
krq|||}|S t| j|| j| j| jd}||||}|S )al  
    Decrypts encrypted ASN.1 data

    :param encryption_algorithm_info:
        An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm

    :param encrypted_content:
        A byte string of the encrypted content

    :param password:
        A byte string of the encrypted content's password

    :return:
        A byte string of the decrypted plaintext
    r   rc5zc
                PBES2 encryption scheme utilizing RC5 encryption is not supported
                r   r   r   r   r   r   rf   r   )r   encryption_cipherkdfrU   r   r   kdf_hmackdf_saltkdf_iterationsr   encryption_ivr   r   encryption_block_size)r   r   r   r   r   r   	plaintextderived_outputr7   r7   r8   r     sd   


(




r   r   )9
__future__r   r   r   r   r]   r   rr   r   _asn1r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   	symmetricr   r   r   r   r   utilr   _errorsr   _typesr    r!   r"   r#   rO   rQ   rX   rM   r   r}   r   r   rt   r   r   r   r   r7   r7   r7   r8   <module>   s>   DHK)-e	I
:
u3[ 4