o
    Œõ±jÜû  ã                   @   sL  d dl mZmZmZmZ d dlm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 ddlmZmZmZmZmZmZmZmZmZ ddlm Z  ddl!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-m.Z. d	dl/m0Z0m1Z1m2Z2 d	dl3m4Z4 ddl5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZA g d¢ZBG dd„ deƒZCG dd„ deƒZDG dd„ deƒZdIdd„ZEdd„ ZFdd„ ZGdd„ ZHdJdd „ZId!d"„ ZJd#d$„ ZKdJd%d&„ZLdJd'd(„ZMd)d*„ ZNd+d,„ ZOd-d.„ ZPd/d0„ ZQd1d2„ ZRd3d4„ ZSd5d6„ ZTd7d8„ ZUd9d:„ ZVd;d<„ ZWd=d>„ ZXd?d@„ ZYdAdB„ ZZdCdD„ Z[dEdF„ Z\dGdH„ Z]dS )Ké    )Úunicode_literalsÚdivisionÚabsolute_importÚprint_function)Ú	b32encodeNé   )	ÚCertificateÚECDomainParametersÚIntegerÚKeyExchangeAlgorithmÚNullÚPrivateKeyInfoÚPublicKeyAlgorithmÚPublicKeyInfoÚRSAPublicKey)	Ú_CertificateBaseÚ_fingerprintÚ_parse_pkcs12Ú_PrivateKeyBaseÚ_PublicKeyBaseÚ_unwrap_private_key_infoÚparse_certificateÚparse_privateÚparse_public)Úpretty_message)ÚnewÚunwrapÚbytes_from_bufferÚbuffer_from_bytesÚderefÚnullÚis_nullÚpointer_seté   )ÚSecurityÚSecurityConstÚhandle_sec_errorÚosx_version_info)ÚCoreFoundationÚ	CFHelpersÚhandle_cf_error)Ú
rand_bytes)ÚAsymmetricKeyErrorÚIncompleteAsymmetricKeyErrorÚSignatureError)Úadd_pss_paddingÚverify_pss_paddingÚ"remove_pkcs1v15_encryption_padding)Ú	type_nameÚstr_clsÚbyte_clsÚ	int_types)r   Údsa_signÚ
dsa_verifyÚ
ecdsa_signÚecdsa_verifyÚgenerate_pairÚload_certificateÚload_pkcs12Úload_private_keyÚload_public_keyÚparse_pkcs12Ú
PrivateKeyÚ	PublicKeyÚrsa_oaep_decryptÚrsa_oaep_encryptÚrsa_pkcs1v15_decryptÚrsa_pkcs1v15_encryptÚrsa_pkcs1v15_signÚrsa_pkcs1v15_verifyÚrsa_pss_signÚrsa_pss_verifyc                   @   sD   e Zd ZdZdZdZdZdd„ Zedd„ ƒZ	edd„ ƒZ
d	d
„ ZdS )r@   zM
    Container for the OS crypto library representation of a private key
    Nc                 C   ó   || _ || _t| _dS )zÌ
        :param sec_key_ref:
            A Security framework SecKeyRef value from loading/importing the
            key

        :param asn1:
            An asn1crypto.keys.PrivateKeyInfo object
        N©Úsec_key_refÚasn1r(   Ú_lib©ÚselfrL   rM   © rQ   ú‹/root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/oscrypto/_mac/asymmetric.pyÚ__init__M   ó   

zPrivateKey.__init__c              	   C   sT  | j du r§d}z‘ttdƒ}t | jddtƒ |¡}t|ƒ t|ƒ}t	 
|¡}t|ƒ}|jdkrKttdtƒ dœƒt|d jd |d jd d	œƒd
œƒ}nE|jdkru|d d }ttd| ¡ dœƒtt|d j|d jj|d jƒƒd
œƒ}n|jdkr�ttdtd| jd�dœƒ|d jd d
œƒ}W |r˜t |¡ n	|r¡t |¡ w w t|ƒ| _ | j S )z\
        :return:
            A PublicKey object corresponding to this private key.
        NúCFDataRef *r   Úrsa)Ú	algorithmÚ
parametersÚprivate_keyÚmodulusÚpublic_exponent)rZ   r[   )rW   Ú
public_keyÚdsaÚprivate_key_algorithmrX   ÚgÚpÚecÚnamed)ÚnameÚvaluer\   )Ú_public_keyr   r(   r$   ÚSecItemExportrL   r    r&   r   r)   Úcf_data_to_bytesr   rW   r   r   r   r   ÚparsedÚcopyr
   ÚpowÚnativer	   ÚcurveÚ	CFReleaseÚ	_load_key)rP   Úcf_data_privateÚcf_data_private_pointerÚresultÚprivate_key_bytesÚkeyÚpublic_asn1ÚparamsrQ   rQ   rR   r\   [   sj   



þþ
û
þ
ý
û
þþø€
€ÿÿ
zPrivateKey.public_keyc                 C   s   | j du rt | jtƒ| _ | j S )aY  
        Creates a fingerprint that can be compared with a public 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)r   rM   r=   ©rP   rQ   rQ   rR   Úfingerprint�   s   
zPrivateKey.fingerprintc                 C   ó(   | j r| j | j ¡ d | _d | _ d S d S ©N©rL   rN   rm   rv   rQ   rQ   rR   Ú__del__¯   ó
   
ýzPrivateKey.__del__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rL   re   rN   rS   Úpropertyr\   rw   r{   rQ   rQ   rQ   rR   r@   A   s    
A
r@   c                   @   s(   e Zd ZdZdZdZdd„ Zdd„ ZdS )rA   zL
    Container for the OS crypto library representation of a public key
    Nc                 C   rJ   )zË
        :param sec_key_ref:
            A Security framework SecKeyRef value from loading/importing the
            key

        :param asn1:
            An asn1crypto.keys.PublicKeyInfo object
        NrK   rO   rQ   rQ   rR   rS   Á   rT   zPublicKey.__init__c                 C   rx   ry   rz   rv   rQ   rQ   rR   r{   Ï   r|   zPublicKey.__del__)r}   r~   r   r€   rL   rN   rS   r{   rQ   rQ   rQ   rR   rA   ¶   s    rA   c                   @   sP   e Zd ZdZdZdZdZdd„ Zedd„ ƒZ	edd„ ƒZ
ed	d
„ ƒZdd„ ZdS )r   zM
    Container for the OS crypto library representation of a certificate
    Nc                 C   s   || _ || _dS )zá
        :param sec_certificate_ref:
            A Security framework SecCertificateRef value from loading/importing
            the certificate

        :param asn1:
            An asn1crypto.x509.Certificate object
        N)Úsec_certificate_refrM   )rP   r‚   rM   rQ   rQ   rR   rS   ß   s   

zCertificate.__init__c                 C   s   | j jS )zF
        :return:
            The SecKeyRef of the public key
        )r\   rL   rv   rQ   rQ   rR   rL   ì   s   zCertificate.sec_key_refc                 C   sŽ   | j sD| jrD| jjdkr#| j ¡ }d|d d d d< t|ƒ}|j}n| j}ttdƒ}t ||¡}t	|ƒ t
|ƒ}t|| jd d ƒ| _ | j S )zh
        :return:
            The PublicKey object for the public key this certificate contains
        Ú
rsassa_pssrV   Útbs_certificateÚsubject_public_key_inforW   úSecKeyRef *)re   r‚   rM   Úsignature_algori   Ú
_load_x509r   r$   ÚSecCertificateCopyPublicKeyr&   r   rA   )rP   rM   Ú	temp_certÚsec_cert_refÚsec_public_key_ref_pointerÚresÚsec_public_key_refrQ   rQ   rR   r\   õ   s   

zCertificate.public_keyc                 C   sÐ   | j du red| _ | jjtddgƒv re| jd j}| jd j}|dkr%t}n|dkr,t}n|dkr3t}n|d	kr:t	}nt
td
|ƒƒ‚z|| j| jd j| jd  ¡ |ƒ d| _ W | j S  tyd   Y | j S w | j S )zT
        :return:
            A boolean - if the certificate is self-signed
        NFÚyesÚmaybeÚsignature_algorithmÚrsassa_pkcs1v15rƒ   r]   Úecdsaz¦
                        Unable to verify the signature of the certificate since
                        it uses the unsupported algorithm %s
                        Úsignature_valuer„   T)Ú_self_signedrM   Úself_signedÚsetr‡   Ú	hash_algorG   rI   r7   r9   ÚOSErrorr   r\   rk   Údumpr.   )rP   r‡   r˜   Úverify_funcrQ   rQ   rR   r–     s>   
û
üýýzCertificate.self_signedc                 C   s6   | j r| j  ¡  d | _ | jrt | j¡ d | _d S d S ry   )re   r{   r‚   r(   rm   rv   rQ   rQ   rR   r{   ;  s   

þzCertificate.__del__)r}   r~   r   r€   r‚   re   r•   rS   r�   rL   r\   r–   r{   rQ   rQ   rQ   rR   r   Ö   s    


+r   c                 C   sî  | t g d¢ƒvrttdt| ƒƒƒ‚| dkr'|t g d¢ƒvr&ttdt|ƒƒƒ‚n*| dkr<|t dgƒvr;ttdt|ƒƒƒ‚n| d	krQ|t g d
¢ƒvrQttdt|ƒƒƒ‚d}d}d}d}d}d}d}	d}
d}�z;tjtjtjdœ|  }| d	kr}dddd
œ| }n|}tt	dƒ}tt	dƒ}t
 d¡}d}td| ƒ}|dd… }t|dd… ƒ d¡}t ¡ }tj ||¡ d¡}tt	dƒ}t	 |||dtƒ |¡}t|ƒ t|ƒ}
tt	dƒ}t	 |tƒ |¡}t|ƒ t|ƒ}	t	 |
||dtjtjtjB tjtjtjB |	||¡}t|ƒ t|ƒ}t|ƒ}ttdƒ}t	  |ddtƒ |¡}t|ƒ t|ƒ}t
 !|¡}ttdƒ}t	  |ddtƒ |¡}t|ƒ t|ƒ}t
 !|¡}t	 "|¡}t|ƒ t	 "|¡}t|ƒ W |�rZt #|¡ |�rbt #|¡ |�rjt #|¡ |�rrt #|¡ |�rzt #|¡ |�r‚t #|¡ |
�r�t	 $|
¡ t #|
¡ |�r—t% &|¡ |	�rŸt #|	¡ nO|�r¨t #|¡ |�r°t #|¡ |�r¸t #|¡ |�rÀt #|¡ |�rÈt #|¡ |�rÐt #|¡ |
�rÝt	 $|
¡ t #|
¡ |�råt% &|¡ |	�rît #|	¡ w w t'|ƒt(|ƒfS )a  
    Generates a public/private key pair

    :param algorithm:
        The key algorithm - "rsa", "dsa" or "ec"

    :param bit_size:
        An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
        2048, 3072 or 4096. For "dsa" the value may be 1024.

    :param curve:
        A unicode string - used for "ec" keys. Valid values include "secp256r1",
        "secp384r1" and "secp521r1".

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A 2-element tuple of (PublicKey, PrivateKey). The contents of each key
        may be saved by calling .asn1.dump().
    )rV   r]   ra   zM
            algorithm must be one of "rsa", "dsa", "ec", not %s
            rV   )é   i   i   é   zX
                bit_size must be one of 1024, 2048, 3072, 4096, not %s
                r]   rœ   z?
                bit_size must be 1024, not %s
                ra   ©Ú	secp256r1Ú	secp384r1Ú	secp521r1zd
                curve must be one of "secp256r1", "secp384r1", "secp521r1", not %s
                N)r]   ra   rV   é   é€  i	  r†   úTemporary oscrypto keyé   é
   úutf-8úSecKeychainRef *FúSecAccessRef *r   rU   ))r—   Ú
ValueErrorr   Úreprr%   ÚCSSM_ALGID_DSAÚCSSM_ALGID_ECDSAÚCSSM_ALGID_RSAr   r$   r)   Úcf_string_from_unicoder+   r   ÚdecodeÚtempfileÚmkdtempÚosÚpathÚjoinÚencodeÚSecKeychainCreater    r&   r   ÚSecAccessCreateÚSecKeyCreatePairÚCSSM_KEYUSE_VERIFYÚCSSM_KEYATTR_EXTRACTABLEÚCSSM_KEYATTR_PERMANENTÚCSSM_KEYUSE_SIGNr(   rf   rg   ÚSecKeychainItemDeleterm   ÚSecKeychainDeleteÚshutilÚrmtreer>   r=   )rW   Úbit_sizerl   Úcf_dictÚpublic_key_refÚprivate_key_refÚcf_data_publicro   Ú	cf_stringÚsec_access_refÚsec_keychain_refÚtemp_dirÚalg_idÚkey_sizeÚprivate_key_pointerÚpublic_key_pointerÚpassphrase_lenÚ	rand_dataÚ
passphraseÚtemp_filenameÚ	temp_pathÚsec_keychain_ref_pointerrq   Úsec_access_ref_pointerÚcf_data_public_pointerÚpublic_key_bytesrp   rr   rQ   rQ   rR   r:   E  s   üüÿüÿüýüýü



ú


õ
















€î








ÿr:   c                 C   s  t | tƒsttdt| ƒƒƒ‚| dk rtdƒ‚| dkrtdƒ‚| d dkr(tdƒ‚d	}d	}d	}d	}d	}d	}d	}d	}�zttd
ƒ}	ttd
ƒ}
t 	d¡}d}t
d| ƒ}|dd	… }t|d	d… ƒ d¡}t ¡ }tj ||¡ d¡}ttdƒ}t |||dtƒ |¡}t|ƒ t|ƒ}ttdƒ}t |tƒ |¡}t|ƒ t|ƒ}t |tj| ddtjtjB dtjtjB ||	|
¡}t|ƒ t|	ƒ}t|
ƒ}ttdƒ}t |ddtƒ |¡}t|ƒ t|ƒ}t |¡}t  |¡}t|ƒ t  |¡}t|ƒ t! "|¡d W |rýt #|¡ |�rt #|¡ |�rt #|¡ |�rt #|¡ |�rt #|¡ |�r*t $|¡ t #|¡ |�r2t% &|¡ |�r;t #|¡ S S |�rDt #|¡ |�rLt #|¡ |�rTt #|¡ |�r\t #|¡ |�rdt #|¡ |�rqt $|¡ t #|¡ |�ryt% &|¡ |�r‚t #|¡ w w )a`  
    Generates DH parameters for use with Diffie-Hellman key exchange. Returns
    a structure in the format of DHParameter defined in PKCS#3, which is also
    used by the OpenSSL dhparam tool.

    THIS CAN BE VERY TIME CONSUMING!

    :param bit_size:
        The integer bit size of the parameters to generate. Must be between 512
        and 4096, and divisible by 64. Recommended secure value as of early 2016
        is 2048, with an absolute minimum of 1024.

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        An asn1crypto.algos.DHParameters object. Use
        oscrypto.asymmetric.dump_dh_parameters() to save to disk for usage with
        web servers.
    z=
            bit_size must be an integer, not %s
            é   z-bit_size must be greater than or equal to 512r�   z+bit_size must be less than or equal to 4096é@   r   z!bit_size must be a multiple of 64Nr†   r¤   r¥   r¦   r§   r¨   Fr©   rU   rX   )'Ú
isinstancer5   Ú	TypeErrorr   r2   rª   r   r$   r)   r¯   r+   r   r°   r±   r²   r³   r´   rµ   r¶   r·   r    r&   r   r¸   r¹   r%   ÚCSSM_ALGID_DHr»   r¼   r(   rf   rg   r¾   r   Úloadrm   r¿   rÀ   rÁ   )rÂ   rÄ   rÅ   rÆ   ro   rÇ   rÉ   rÈ   rÊ   rÎ   rÍ   rÏ   rÐ   rÑ   rÒ   rÓ   rÔ   rq   rÕ   rp   rr   rQ   rQ   rR   Úgenerate_dh_parametersù  sÔ   
ü



ú


õ











ÿñ







ÿrÞ   c                 C   ó�   t | tƒr| }t
|ƒS t | tƒrt| ƒ}t
|ƒS t | tƒr?t| dƒ�}t| ¡ ƒ}W d  ƒ t
|ƒS 1 s6w   Y  t
|ƒS ttdt	| ƒƒƒ‚)aÐ  
    Loads an x509 certificate into a Certificate object

    :param source:
        A byte string of file contents, a unicode string filename or an
        asn1crypto.x509.Certificate object

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A Certificate object
    ÚrbNz€
            source must be a byte string, unicode string or
            asn1crypto.x509.Certificate object, not %s
            )rÚ   ÚAsn1Certificater4   r   r3   ÚopenÚreadrÛ   r   r2   rˆ   )ÚsourceÚcertificateÚfrQ   rQ   rR   r;     s"   

ð
ó
ÿôøûr;   c              	   C   sT   |   ¡ }d}zt |¡}t tj|¡}t|| ƒW |r t |¡ S S |r)t |¡ w w )zÂ
    Loads an ASN.1 object of an x509 certificate into a Certificate object

    :param certificate:
        An asn1crypto.x509.Certificate object

    :return:
        A Certificate object
    N)	rš   r)   Úcf_data_from_bytesr$   ÚSecCertificateCreateWithDatar(   ÚkCFAllocatorDefaultr   rm   )rå   rä   Ú	cf_sourcerL   rQ   rQ   rR   rˆ   ¦  s   

ÿÿrˆ   c                 C   sº   t | tƒr| }t|ƒS |dur't |tƒr| d¡}t |tƒs'ttdt|ƒƒƒ‚t | tƒrFt| dƒ�}| 	¡ } W d  ƒ n1 s@w   Y  nt | tƒsTttdt| ƒƒƒ‚t
| |ƒ}t|ƒS )a   
    Loads a private key into a PrivateKey object

    :param source:
        A byte string of file contents, a unicode string filename or an
        asn1crypto.keys.PrivateKeyInfo object

    :param password:
        A byte or unicode string to decrypt the private key file. Unicode
        strings will be encoded using UTF-8. Not used is the source is a
        PrivateKeyInfo object.

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        oscrypto.errors.AsymmetricKeyError - when the private key is incompatible with the OS crypto library
        OSError - when an error is returned by the OS crypto library

    :return:
        A PrivateKey object
    Nr§   zP
                    password must be a byte string, not %s
                    rà   z�
                source must be a byte string, unicode string or
                asn1crypto.keys.PrivateKeyInfo object, not %s
                )rÚ   r   r3   r¶   r4   rÛ   r   r2   râ   rã   r   rn   )rä   ÚpasswordÚprivate_objectræ   rQ   rQ   rR   r=   ¾  s.   
æ


ü

ÿ€
û
r=   c                 C   rß   )a3  
    Loads a public key into a PublicKey object

    :param source:
        A byte string of file contents, a unicode string filename or an
        asn1crypto.keys.PublicKeyInfo object

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        oscrypto.errors.AsymmetricKeyError - when the public key is incompatible with the OS crypto library
        OSError - when an error is returned by the OS crypto library

    :return:
        A PublicKey object
    rà   Nz‚
            source must be a byte string, unicode string or
            asn1crypto.keys.PublicKeyInfo object, not %s
            )rÚ   r   r4   r   r3   râ   rã   rÛ   r   r2   rn   )rä   r\   ræ   rQ   rQ   rR   r>   ö  s"   

ð
ó
ÿôøûr>   c              
   C   sÔ  | j dkr!| j\}}|dkrtdƒ‚|tg d¢ƒvr ttdƒƒ‚n"| j dkr3| jdkr3ttd| jƒƒ‚| j dkrC| jd	u rCttd
ƒƒ‚t| t	ƒrd| j dkr\|  
¡ }d|d d< | ¡ }n|  ¡ }tj}n	t| ƒ ¡ }tj}d	}d	}d	}zÜt |¡}ttdƒ}	t|	tjƒ ttdƒ}
t|
|ƒ ttdƒ}t tjg¡}ttdƒ}t|ƒ}d|_d|_tƒ |_tƒ |_tƒ |_tƒ |_ tƒ |_!||_"t #|tƒ |	|
d|tƒ |¡}t$|ƒ t|ƒ}t %|¡}|dkrêt &|d¡}t '|¡ |tjk�rt(|| ƒW |rüt )|¡ |�rt )|¡ |�rt )|¡ S S |tjk�r3t*|| ƒW |�r!t )|¡ |�r)t )|¡ |�r2t )|¡ S S W |�r<t )|¡ |�rDt )|¡ |�rNt )|¡ d	S d	S |�rXt )|¡ |�r`t )|¡ |�rit )|¡ w w )aN  
    Common code to load public and private keys into PublicKey and PrivateKey
    objects

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

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library
        OSError - when an error is returned by the OS crypto library

    :return:
        A PublicKey or PrivateKey object
    ra   rb   z-OS X only supports EC keys using named curvesrž   z†
                OS X only supports EC keys using the named curves secp256r1,
                secp384r1 and secp521r1
                r]   Úsha2zŽ
            OS X only supports DSA keys based on SHA1 (2048 bits or less) - this
            key is based on SHA2 and is %s bits
            Nzz
            The DSA key does not contain the necessary p, q and g parameters
            and can not be used
            rƒ   rV   rW   z
uint32_t *zCFArrayRef *z"SecItemImportExportKeyParameters *r   )+rW   rl   r,   r—   r   r˜   rÂ   r-   rÚ   r   ri   rš   r%   ÚkSecItemTypePublicKeyr   ÚkSecItemTypePrivateKeyr)   rç   r   r$   r"   ÚkSecFormatOpenSSLr(   Úcf_array_from_listÚkSecAttrIsExtractabler   ÚversionÚflagsr    rÑ   Ú
alertTitleÚalertPromptÚ	accessRefÚkeyUsageÚkeyAttributesÚSecItemImportr&   ÚCFArrayGetCountÚCFArrayGetValueAtIndexÚCFRetainrA   rm   r@   )Ú
key_objectÚ
curve_typeÚdetailsÚtemp_key_objecträ   Ú	item_typerê   Ú
keys_arrayÚ
attr_arrayÚformat_pointerÚtype_pointerÚkeys_pointerÚimport_export_params_pointerÚimport_export_paramsr�   ÚlengthrL   rQ   rQ   rR   rn     sÆ   

ÿÿûÿ







ÿ
ø





ÿø


ÿø

ÿü

ÿrn   c                 C   s   t | |tƒS )aÍ  
    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

    :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
    )r   r=   )Údatarë   rQ   rQ   rR   r?   š  s   r?   c           	      C   sÚ   |durt |tƒr| d¡}t |tƒsttdt|ƒƒƒ‚t | tƒr;t| dƒ�}| ¡ } W d  ƒ n1 s5w   Y  nt | tƒsIttdt| ƒƒƒ‚t	| |ƒ\}}}d}d}|r[t
|ƒ}|rat|ƒ}dd„ |D ƒ}|||fS )aø  
    Loads a .p12 or .pfx file into a PrivateKey object and one or more
    Certificates objects

    :param source:
        A byte string of file contents or a unicode string filename

    :param password:
        A byte or unicode string to decrypt the PKCS12 file. Unicode strings
        will be encoded using UTF-8.

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        oscrypto.errors.AsymmetricKeyError - when a contained key is incompatible with the OS crypto library
        OSError - when an error is returned by the OS crypto library

    :return:
        A three-element tuple containing (PrivateKey, Certificate, [Certificate, ...])
    Nr§   zH
                password must be a byte string, not %s
                rà   zR
            source must be a byte string or a unicode string, not %s
            c                 S   s   g | ]}t |ƒ‘qS rQ   )rˆ   )Ú.0ÚinforQ   rQ   rR   Ú
<listcomp>ë  s    zload_pkcs12.<locals>.<listcomp>)rÚ   r3   r¶   r4   rÛ   r   r2   râ   rã   r?   rn   rˆ   )	rä   rë   ræ   Úkey_infoÚ	cert_infoÚextra_certs_infors   ÚcertÚextra_certsrQ   rQ   rR   r<   ³  s6   


ü

ÿ€
ü
r<   c                 C   sˆ   t | ttfƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚| j}t|ƒ}t	t
d|ƒ}t
 | jtj|t|ƒ||¡}t|ƒ t|t|ƒƒS )aF  
    Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1
    v1.5 padding.

    :param certificate_or_public_key:
        A PublicKey or Certificate object

    :param data:
        A byte string, with a maximum length 11 bytes less than the key length
        (in bytes)

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the encrypted data
    ú�
            certificate_or_public_key must be an instance of the Certificate or
            PublicKey class, not %s
            ú<
            data must be a byte string, not %s
            úsize_t *)rÚ   r   rA   rÛ   r   r2   r4   Ú	byte_sizer   r   r$   ÚSecKeyEncryptrL   r%   ÚkSecPaddingPKCS1Úlenr&   r   r   )Úcertificate_or_public_keyr  Ú
key_lengthÚbufferÚoutput_lengthrq   rQ   rQ   rR   rE   ð  s.   û
üúrE   c                 C   s®   t | tƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚| j}t|ƒ}tt	d|ƒ}t
dk r1tj}ntj}t	 | j||t|ƒ||¡}t|ƒ t|t|ƒƒ}t
dk rUt||ƒ}|S )aì  
    Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding.

    :param private_key:
        A PrivateKey object

    :param ciphertext:
        A byte string of the encrypted data

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the original plaintext
    zV
            private_key must an instance of the PrivateKey class, not %s
            r  r  )r¦   é   )rÚ   r@   rÛ   r   r2   r4   r  r   r   r$   r'   r%   ÚkSecPaddingNoner  ÚSecKeyDecryptrL   r  r&   r   r   r1   )rY   Ú
ciphertextr  r  r  Úpaddingrq   ÚoutputrQ   rQ   rR   rD   &  s:   
ü
üú
rD   c                 C   ó   t | |tjƒS )aZ  
    Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1
    OAEP padding with SHA1.

    :param certificate_or_public_key:
        A PublicKey or Certificate object

    :param data:
        A byte string, with a maximum length 41 bytes (or more) less than the
        key length (in bytes)

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the encrypted data
    )Ú_encryptr$   ÚkSecPaddingOAEPKey)r  r  rQ   rQ   rR   rC   d  s   rC   c                 C   r%  )aú  
    Decrypts a byte string using an RSA private key. Uses PKCS#1 OAEP padding
    with SHA1.

    :param private_key:
        A PrivateKey object

    :param ciphertext:
        A byte string of the encrypted data

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the original plaintext
    )Ú_decryptr$   r'  )rY   r"  rQ   rQ   rR   rB   |  s   rB   c              	   C   s  t | ttfƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚|s$tdƒ‚d}d}zPt 	|¡}t
tdƒ}t | j|¡}t|ƒ |rMt |tj||¡ t|ƒ t |tj||¡ t|ƒ t ||¡}t|ƒ t |¡W |rpt |¡ |rxt |¡ S S |r€t |¡ |rˆt |¡ w w )a>  
    Encrypts plaintext using an RSA public key or certificate

    :param certificate_or_public_key:
        A Certificate or PublicKey object

    :param data:
        The plaintext - a byte string

    :param padding:
        The padding mode to use, specified as a kSecPadding*Key value

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the ciphertext
    r  r  úpadding must be specifiedNúCFErrorRef *)rÚ   r   rA   rÛ   r   r2   r4   rª   r)   rç   r   r(   r$   ÚSecEncryptTransformCreaterL   r*   ÚSecTransformSetAttributeÚkSecPaddingKeyÚkSecTransformInputAttributeNameÚSecTransformExecuterg   rm   )r  r  r#  Úcf_dataÚsec_transformÚerror_pointerr"  rQ   rQ   rR   r&  “  sd   û
ü

þüü

ÿþ
ÿr&  c              	   C   s
  t | tƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚|s"tdƒ‚d}d}zNt |¡}t	t
dƒ}t | j|¡}t|ƒ t |tj||¡ t|ƒ t |tj||¡ t|ƒ t ||¡}t|ƒ t |¡W |rlt
 |¡ |rtt
 |¡ S S |r|t
 |¡ |r„t
 |¡ w w )a  
    Decrypts RSA ciphertext using a private key

    :param private_key:
        A PrivateKey object

    :param ciphertext:
        The ciphertext - a byte string

    :param padding:
        The padding mode to use, specified as a kSecPadding*Key value

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    úY
            private_key must be an instance of the PrivateKey class, not %s
            zB
            ciphertext must be a byte string, not %s
            r)  Nr*  )rÚ   r@   rÛ   r   r2   r4   rª   r)   rç   r   r(   r$   ÚSecDecryptTransformCreaterL   r*   r,  r-  r.  r/  rg   rm   )rY   r"  r#  r0  r1  r2  Ú	plaintextrQ   rQ   rR   r(  ç  sb   
ü
ü

þüü

ÿþ
ÿr(  c                 C   ó    | j dkr	tdƒ‚t| |||ƒS )aà  
    Verifies an RSASSA-PKCS-v1.5 signature.

    When the hash_algorithm is "raw", the operation is identical to RSA
    public key decryption. That is: the data is not hashed and no ASN.1
    structure with an algorithm identifier of the hash algorithm is placed in
    the encrypted byte string.

    :param certificate_or_public_key:
        A Certificate or PublicKey instance to verify the signature with

    :param signature:
        A byte string of the signature to verify

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384", "sha512" or "raw"

    :raises:
        oscrypto.errors.SignatureError - when the signature is determined to be invalid
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library
    rV   ú*The key specified is not an RSA public key©rW   rª   Ú_verify©r  Ú	signaturer  Úhash_algorithmrQ   rQ   rR   rG   9  s   
rG   c                 C   sÜ   t | ttfƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚| j}|dkr-|dkr-tdƒ‚dddd	d
dœ 	|d¡}| j
}t|ƒ}ttd|ƒ}t | jtj|t|ƒ||¡}	t|	ƒ t|t|ƒƒ}
t||| j||
ƒsltdƒ‚dS )a¹  
    Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm
    will be mgf1 using the same hash algorithm as the signature. The salt length
    with be the length of the hash algorithm, and the trailer field with be the
    standard 0xBC byte.

    :param certificate_or_public_key:
        A Certificate or PublicKey instance to verify the signature with

    :param signature:
        A byte string of the signature to verify

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"

    :raises:
        oscrypto.errors.SignatureError - when the signature is determined to be invalid
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library
    r  r  rV   rƒ   r7  é   é   é    é0   rÙ   ©Úsha1Úsha224Úsha256Úsha384Úsha512r   r  úSignature is invalidN)rÚ   r   rA   rÛ   r   r2   r4   rW   rª   Úgetr  r   r   r$   r  rL   r%   r   r  r&   r   r   r0   rÂ   r.   )r  r;  r  r<  Úcp_algoÚhash_lengthr  r  r  rq   r5  rQ   rQ   rR   rI   [  sJ   û
üûúúÿrI   c                 C   r6  )aÌ  
    Verifies a DSA signature

    :param certificate_or_public_key:
        A Certificate or PublicKey instance to verify the signature with

    :param signature:
        A byte string of the signature to verify

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"

    :raises:
        oscrypto.errors.SignatureError - when the signature is determined to be invalid
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library
    r]   z)The key specified is not a DSA public keyr8  r:  rQ   rQ   rR   r7   ¤  ó   
r7   c                 C   r6  )aÏ  
    Verifies an ECDSA signature

    :param certificate_or_public_key:
        A Certificate or PublicKey instance to verify the signature with

    :param signature:
        A byte string of the signature to verify

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"

    :raises:
        oscrypto.errors.SignatureError - when the signature is determined to be invalid
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library
    ra   z)The key specified is not an EC public keyr8  r:  rQ   rQ   rR   r9   Á  rK  r9   c              	   C   s  t | ttfƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚t |tƒs,ttdt|ƒƒƒ‚tg d¢ƒ}| jdkr>|tdgƒO }||vrWd}| jdkrM|d7 }t	td	|t
|ƒƒƒ‚| jdkr˜|dkr˜t|ƒ| jd
 krtt	td| jt|ƒƒƒ‚t | jtj|t|ƒ|t|ƒ¡}|tjksŽ|tjkr’tdƒ‚t|ƒ dS d}d}d}	d}
zÈttdƒ}t |¡}t | j||¡}
t|ƒ tjtjtjtjtjtjdœ| }t |
tj ||¡ t|ƒ |tg d¢ƒv rødddddœ| }t !|¡}	t |
tj"|	|¡ t|ƒ | jdk�rt |
tj#tj$|¡ t|ƒ t |¡}t |
tj%||¡ t|ƒ t &|
|¡}t'|ƒ�s6t(|ƒ}t'|ƒ�s6tdƒ‚t)t *|¡ƒ}|�sDtdƒ‚W |
�rMt +|
¡ |�rUt +|¡ |�r]t +|¡ |	�rgt +|	¡ dS dS |
�rqt +|
¡ |�ryt +|¡ |�r�t +|¡ |	�rŠt +|	¡ w w )aÛ  
    Verifies an RSA, DSA or ECDSA signature

    :param certificate_or_public_key:
        A Certificate or PublicKey instance to verify the signature with

    :param signature:
        A byte string of the signature to verify

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"

    :raises:
        oscrypto.errors.SignatureError - when the signature is determined to be invalid
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library
    r  zA
            signature must be a byte string, not %s
            r  ©Úmd5rB  rC  rD  rE  rF  rV   Úrawú5"md5", "sha1", "sha224", "sha256", "sha384", "sha512"ú, "raw"úB
            hash_algorithm must be one of %s, not %s
            é   zÀ
                data must be 11 bytes shorter than the key size when
                hash_algorithm is "raw" - key size is %s bytes, but data
                is %s bytes long
                rG  Nr*  ©rC  rD  rE  rF  éà   r¢   r£   rØ   ),rÚ   r   rA   rÛ   r   r2   r4   r—   rW   rª   r«   r  r  r$   ÚSecKeyRawVerifyrL   r%   r  ÚerrSecVerifyFailedÚerrSSLCryptor.   r&   r   r(   r)   rç   ÚSecVerifyTransformCreater*   ÚkSecDigestMD5ÚkSecDigestSHA1ÚkSecDigestSHA2r,  ÚkSecDigestTypeAttributeÚcf_number_from_integerÚkSecDigestLengthAttributer-  ÚkSecPaddingPKCS1Keyr.  r/  r!   r   ÚboolÚCFBooleanGetValuerm   )r  r;  r  r<  Úvalid_hash_algorithmsÚvalid_hash_algorithms_errorrq   Úcf_signaturer0  Úcf_hash_lengthr1  r2  Úhash_constantrJ  r�   ÚerrorrQ   rQ   rR   r9  Þ  s  û
ü
ü

ûù
ú	

ýúù	üüû
üü
ü

ÿ


ÿú


ÿr9  c                 C   ó   | j dkr	tdƒ‚t| ||ƒS )a^  
    Generates an RSASSA-PKCS-v1.5 signature.

    When the hash_algorithm is "raw", the operation is identical to RSA
    private key encryption. That is: the data is not hashed and no ASN.1
    structure with an algorithm identifier of the hash algorithm is placed in
    the encrypted byte string.

    :param private_key:
        The PrivateKey to generate the signature with

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384",
        "sha512" or "raw"

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the signature
    rV   ú+The key specified is not an RSA private key©rW   rª   Ú_sign©rY   r  r<  rQ   rQ   rR   rF   ’  s   
rF   c           
      C   sÊ   t | tƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚| j}|dkr+|dkr+tdƒ‚dddd	d
dœ |d¡}t	||| j
|ƒ}| j}t|ƒ}ttd|ƒ}t | jtj|t|ƒ||¡}	t|	ƒ t|t|ƒƒS )a6  
    Generates an RSASSA-PSS signature. For the PSS padding the mask gen
    algorithm will be mgf1 using the same hash algorithm as the signature. The
    salt length with be the length of the hash algorithm, and the trailer field
    with be the standard 0xBC byte.

    :param private_key:
        The PrivateKey to generate the signature with

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or
        "sha512"

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the signature
    r3  r  rV   rƒ   ri  r=  r>  r?  r@  rÙ   rA  r   r  )rÚ   r@   rÛ   r   r2   r4   rW   rª   rH  r/   rÂ   r  r   r   r$   r!  rL   r%   r   r  r&   r   r   )
rY   r  r<  Úpk_algorJ  Úencoded_datar  r  r  rq   rQ   rQ   rR   rH   ´  sF   
ü
üûúúrH   c                 C   rh  )aI  
    Generates a DSA signature

    :param private_key:
        The PrivateKey to generate the signature with

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or
        "sha512"

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the signature
    r]   z*The key specified is not a DSA private keyrj  rl  rQ   rQ   rR   r6   ü  ó   
r6   c                 C   rh  )aL  
    Generates an ECDSA signature

    :param private_key:
        The PrivateKey to generate the signature with

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or
        "sha512"

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the signature
    ra   z*The key specified is not an EC private keyrj  rl  rQ   rQ   rR   r8     ro  r8   c              	   C   s¸  t | tƒsttdt| ƒƒƒ‚t |tƒsttdt|ƒƒƒ‚tg d¢ƒ}| jdkr.|tdgƒO }||vrGd}| jdkr=|d7 }ttd|t	|ƒƒƒ‚| jdkrŠ|dkrŠt
|ƒ| jd	 krdttd
| jt
|ƒƒƒ‚| j}t|ƒ}ttd|ƒ}t | jtj|t
|ƒ||¡}t|ƒ t|t|ƒƒS d}	d}
d}d}z§ttdƒ}t | j|¡}t|ƒ tjtjtjtjtjtjdœ| }t |tj||¡ t|ƒ |tg d¢ƒv rädddddœ| }t |¡}t |tj ||¡ t|ƒ | jdkr÷t |tj!tj"|¡ t|ƒ t #|¡}
t |tj$|
|¡ t|ƒ t %||¡}	t|ƒ t &|	¡W |�r t '|¡ |	�r(t '|	¡ |
�r0t '|
¡ |�r9t '|¡ S S |�rBt '|¡ |	�rJt '|	¡ |
�rRt '|
¡ |�r[t '|¡ w w )aX  
    Generates an RSA, DSA or ECDSA signature

    :param private_key:
        The PrivateKey to generate the signature with

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or
        "sha512"

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the signature
    zO
            private_key must be an instance of PrivateKey, not %s
            r  rL  rV   rN  rO  rP  rQ  rR  zÀ
                data must be 11 bytes shorter than the key size when
                hash_algorithm is "raw" - key size is %s bytes, but
                data is %s bytes long
                r  Nr*  rS  rT  r¢   r£   rØ   )(rÚ   r@   rÛ   r   r2   r4   r—   rW   rª   r«   r  r  r   r   r$   ÚSecKeyRawSignrL   r%   r  r&   r   r   r(   ÚSecSignTransformCreater*   rY  rZ  r[  r,  r\  r)   r]  r^  r-  r_  rç   r.  r/  rg   rm   )rY   r  r<  rb  rc  r  r  r  rq   rd  r0  re  r1  r2  rf  rJ  rQ   rQ   rR   rk  6  sî   
ü
ü

ûù
ú
úù	üüû
ü
ü
ü



ÿú


ÿrk  )NNry   )^Ú
__future__r   r   r   r   Úbase64r   r³   rÀ   r±   Ú_asn1r   rá   r	   r
   r   r   r   r   r   r   Ú_asymmetricr   r   r   r   r   r   r   r   r   Ú_errorsr   Ú_ffir   r   r   r   r   r    r!   r"   Ú	_securityr$   r%   r&   r'   Ú_core_foundationr(   r)   r*   Úutilr+   Úerrorsr,   r-   r.   Ú_pkcs1r/   r0   r1   Ú_typesr2   r3   r4   r5   Ú__all__r@   rA   r:   rÞ   r;   rˆ   r=   r>   rn   r?   r<   rE   rD   rC   rB   r&  r(  rG   rI   r7   r9   r9  rF   rH   r6   r8   rk  rQ   rQ   rQ   rR   Ú<module>   s^   ,,(u 
o 5 '
8(
|
=6>TR"I 5"H