U afx@sjddlmZmZmZmZddlZddlZddlZddlZddl m Z m Z m Z m Z mZmZmZmZmZmZmZmZmZmZmZddlmZmZmZddlmZmZm Z m!Z!m"Z"ddl#m$Z$ddl%m&Z&dd l'm(Z(m)Z)m*Z*Gd d d Z+Gd d d Z,GdddZ-ddZ.ddZ/e e!ee"edZ0ddZ1ddZ2d%ddZ3d&ddZ4ddZ5dd Z6d!d"Z7d#d$Z8dS)')unicode_literalsdivisionabsolute_importprint_functionN)CertBag Certificate DSAPrivateKey ECPrivateKey EncryptedDataEncryptedPrivateKeyInfoInteger OctetStringPfxPrivateKeyInfo PublicKeyInfo RSAPrivateKey RSAPublicKey SafeContentsunarmor)pbkdf1pbkdf2 pkcs12_kdf)aes_cbc_pkcs7_decryptdes_cbc_pkcs5_decryptrc2_cbc_pkcs5_decrypt rc4_decrypttripledes_cbc_pkcs5_decrypt)constant_compare)pretty_message)byte_clsstr_cls type_namec@sLeZdZdZdZddZeddZeddZedd Z ed d Z dS) _PrivateKeyBaseNcCs|jdkr|jdjS|jdkr^|jdd}td|d|d|d |j|jdjd S|jd kr|jdj}|jdd|d<|j|d <|Sd 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_keydsaprivate_key_algorithm parametersrpqgversionr)r*r+ public_keyr%ecr.N) algorithmasn1parsedr r.unwrap)selfparamsoutputr7E/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_asymmetric.pyr3-s"      z_PrivateKeyBase.unwrapcCs|jjSzO :return: A unicode string of "rsa", "dsa" or "ec" r1r0r4r7r7r8r0Ksz_PrivateKeyBase.algorithmcCs |jjdSH :return: A unicode string of EC curve name rr1curver;r7r7r8r?Tsz_PrivateKeyBase.curvecCs|jjSzS :return: The number of bits in the key, as an integer r1bit_sizer;r7r7r8rB]sz_PrivateKeyBase.bit_sizecCs|jjSzT :return: The number of bytes in the key, as an integer r1 byte_sizer;r7r7r8rEfsz_PrivateKeyBase.byte_size) __name__ __module__ __qualname__r1 _fingerprintr3propertyr0r?rBrEr7r7r7r8r#(s   r#c@sXeZdZdZdZddZeddZeddZedd Z ed d Z ed d Z dS)_PublicKeyBaseNcCs |jdkr|jdS|jdjS)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.)r0r1r2r;r7r7r8r3us  z_PublicKeyBase.unwrapcCs|jdkrt|jd|_|jS)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)rIr1r;r7r7r8 fingerprints z_PublicKeyBase.fingerprintcCs|jjSr9r:r;r7r7r8r0sz_PublicKeyBase.algorithmcCs |jjdSr<r>r;r7r7r8r?sz_PublicKeyBase.curvecCs|jjSr@rAr;r7r7r8rBsz_PublicKeyBase.bit_sizecCs|jjSrCrDr;r7r7r8rEsz_PublicKeyBase.byte_size) rFrGrHr1rIr3rJrLr0r?rBrEr7r7r7r8rKps    rKc@s@eZdZdZeddZeddZeddZedd ZdS) _CertificateBaseNcCs|jjSr9)r.r0r;r7r7r8r0sz_CertificateBase.algorithmcCs|jjS)r=)r.r?r;r7r7r8r?sz_CertificateBase.curvecCs|jjS)zZ :return: The number of bits in the public key, as an integer )r.rBr;r7r7r8rBsz_CertificateBase.bit_sizecCs|jjS)z[ :return: The number of bytes in the public key, as an integer )r.rEr;r7r7r8rEsz_CertificateBase.byte_size) rFrGrHr1rJr0r?rBrEr7r7r7r8rMs   rMc Cs|j}|dks|dkr |djS|dkrz|dd}|dj}td|d|d |d tt|d j|j|dj|d S|d kr|dj}|dd|d<|Std |jdS)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$Z rsassa_pssr%r&r'r(rr)r*r+r,r/z#Unsupported key_info.algorithm "%s"N)r0r2r r pownative ValueError)key_infoZkey_algr5r2r7r7r8_unwrap_private_key_infos.     rRcCst|tr|dj}|jdkr:d|dj|djf}n|jdkr|dd}tt|d j|djj|d j}d |d j|d j|d j|jf}nT|jd kr|dj}|dkr||j}|jdjj}d|j d}| d}||7}t|t r| d}t |St|tr|jdkrN|dj}d|dj|djf}n~|jdkr|dj}|dd}d |d j|d j|d j|jf}n6|jd kr|dj}d|j d}| d}||7}t|t r| d}t |Sttdt|dS)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:%dmodulusZpublic_exponentr&r'r(r+r)z %d:%d:%d:%dr*r/r.Nz%s:rzutf-8r0z key_object must be an instance of the asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo classes, not %s ) isinstancerr2r0rOr rNr.r1r?encoder!hashlibsha256digestrrPrr")Z key_objectload_private_keykeyZto_hashr5r.Zpublic_key_objectr7r7r8rIsv                       rI)rc2rc4des tripledesaescCs(t|tsttdt|d}td|dk rft|\}}}|dkrRttd|dkrft |dS|dksv|dkrzt |}|j |WStk rYnXzt |}|j t |dWStk rYnX|dks|dkrzt |}|d d }|WStk rYnXtd dS) 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 certificatetbs_certificatesubject_public_key_infozQThe data specified does not appear to be a known public key or certificate format)rTr TypeErrorrr"rematch _unarmor_pemrPrwraploadrOrr)datakey_typealgopkiZrpkZ parsed_certrQr7r7r8 parse_public~sF       rqcCst|tsttdt|d}td|dk rft|\}}}|dkrRttd|dkrfttd|dksv|dkrz t |WStk rYnXttd dS) 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 r`Nrarbz The data specified does not appear to be a certificate, but rather a private key rcz The data specified does not appear to be a certificate, but rather a public key rdzU The data specified does not appear to be a known certificate format ) rTr rgrr"rhrirjrPrrl)rmrn_r7r7r8parse_certificates0  rsc Cst|tsttdt||dk rBt|tsFttdt|nd}td|dk rt||\}}}|dkrzttd|dkrttd zt |}|j |WStk rYnXz>t |}|d }|d j }t |||}t |}|j |WStk rYnXzt |} | j t | d WStk rDYnXzt |} | j t | d WStk rzYnXzt |} | j t | dWStk rYnXttddS)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 r`NH password must be a byte string, not %s rarcz The data specified does not appear to be a private key, but rather a public key rdz The data specified does not appear to be a private key, but rather a certificate encryption_algorithmencrypted_datar$r&r/zU The data specified does not appear to be a known private key format )rTr rgrr"rhrirjrPrrlrOr _decrypt_encrypted_datarrkr r ) rmpasswordrnrrrpZparsed_wrapperencryption_algorithm_inforwZdecrypted_datar2r7r7r8 parse_privatesv          r{c Cst|\}}}d}t||}|s.ttd|d}|}|tdddgkrr|d}d|t |||fS|} d }| d krd} n| d krd } d }| ||fS)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 rzRSA PRIVATE KEYzDSA PRIVATE KEYzEC PRIVATE KEYrbNzencrypted private keyzrsa public keyrcr$) rrhrirPrgroupstripsetlower_unarmor_pem_openssl_private) rmryZ object_typeheadersZ der_bytesZ type_regexZ armor_typeZ pem_headerrornr7r7r8rjvs(  rjc CsDd}d}d}d|krB|d}|ddkr>|d\}}nd}|sJ|S|r^t|d}|}ddddd d dd d d d ddddddd d d |}t||d d  }|t |kr|t|||d d  7}q|d |}dddddddddddddddddddd |} t | } | dkr8| ||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 NzDEK-Info,ZRC4ascii )z aes-128-cbczaes-128z aes-192-cbczaes-192z aes-256-cbczaes-256r\zrc4-64zrc4-40z rc2-64-cbcz rc2-40-cbczrc2-cbcr[z des-ede3-cbczdes-ede3Zdes3z des-ede-cbczdes-cbcr]rr_r\r[r^r]) findr~splitbinascii unhexlifyrUrrVmd5rXlen crypto_funcs) rrmryZenc_algoZ enc_iv_hexenc_ivr5Zenc_key_lengthenc_keyZ enc_algo_name decrypt_funcr7r7r8rs $   rcst|tsttdt||dk rBt|tsFttdt|nd}ii}t|}|d}|djdkrzttd|j }|d }|r|d d d j}d ddddddd|} t |||dj|dj| d} t t |} t | |dj| } |d dj} t| | std|D]~}|d}t|trJt|j|||nPt|tr|d}|d}|dj}t|||}t||||n ttdqt|}t}tt||@}d}d}g}t|dkr|d|}}fdd D}|||fSt|dkr@tt|d}||}tdkrpttd}|}|=tdkrttd!d"d#}|||fS)$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 r`Nrtru auth_safe content_typermzV Only password-protected PKCS12 files are currently supported mac_datamacZdigest_algorithmr0r0@)sha1sha224rWsha384sha512Z sha512_224Z sha512_256Zmac_saltZ iterationscontentrXzPassword provided is invalidencrypted_content_infoZcontent_encryption_algorithmencrypted_contentz[ Public-key-based PKCS12 files are not currently supported rrcsg|]}|kr|qSr7r7).0fcertsrLr7r8 |sz!_parse_pkcs12..cSs|jjS)N)subjectZhuman_friendly)cr7r7r8ruz_parse_pkcs12..)rZ)rTr rgrr"rrlrOrPauthenticated_safergetattrrVhmacnewcontentsrXrr_parse_safe_contentsr rxrkeyssortedlistrvalues)rmryrY private_keyspfxrrrZmac_algo key_lengthZmac_keyZhash_modZ computed_hmacZ stored_hmacZ content_inforrrzrZdecrypted_contentZkey_fingerprintsZcert_fingerprintsZcommon_fingerprintsrZcertZ other_certsZ first_keyr7rr8 _parse_pkcs12s              rc Cst|trt|}|D]}|d}t|trh|djdkr|dj}|dd}|dj|t|d<qt|tr||t||<qt|t r|d} |d j} t | | |} t| } | |t| |<qt|trt |||||qqdS) 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_valueZcert_idx509Z cert_valuererfNrvrw) rTr rrlrrOr2rIrr rxr) Z safe_contentsrrryrYZsafe_bagrrZpublic_key_inforzZencrypted_key_bytesZdecrypted_key_bytesr%r7r7r8rs(           rcCst|j}|jdkrV|jdkr*ttdt|j||j|j|j }|j }||||}n|jdkrt |j||j|j|j d}|dd}|dd}||||}nb|jdkrt |j||j|j|j d }|jd kr|||}n&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 rZrc5zc PBES2 encryption scheme utilizing RC5 encryption is not supported rrrrrrr\r|)rZencryption_cipherkdfrPrrZkdf_hmacZkdf_saltZkdf_iterationsrZ encryption_ivrrZencryption_block_size)rzrryrrr plaintextZderived_outputr7r7r8rxs^          rx)N)N)9 __future__rrrrrVrrhrZ_asn1rrr r r r r rrrrrrrrrrrrZ symmetricrrrrrutilr_errorsr_typesr r!r"r#rKrMrRrIrrqrsr{rjrrrrxr7r7r7r8s<D  HK)-e I: u 3[ 4