o Saӛ@sddlZddlZddlmZddlmZddlmZmZm Z m Z m Z m Z ddl mZmZmZddlmZmZddlmZmZddlmZmZmZ m!Z"m#Z$m%Z&m'Z(m)Z*m+Z,gd Z-ej.Z/ej0Z1d Z2ej3Z4ej5Z6ej7Z8ej9Z:Gd d d e;Zd dZ?ddZ@d^ddZAddZBddZCddZDGdddeEZFGdddeEZGGdddeEZHdd ZId!d"ZJGd#d$d$eEZKGd%d&d&eEZLGd'd(d(eEZMGd)d*d*eEZNGd+d,d,eEZOGd-d.d.eEZPGd/d0d0e;ZQGd1d2d2eEZRd3d4ZSd5d6ZTd7d8ZUd_d9d:ZVGd;d<dd>eEZXGd?d@d@eEZYGdAdBdBeEZZGdCdDdDeEZ[GdEdFdFeEZ\dGdHZ]d^dIdJZ^dKdLZ_dMdNZ`dOdPZadQdRZbdSdTZcdUdVZddWdXZeefeeegdYehZed^dZd[Ziefeiegd\ehZiejekeld]dS)`N) b16encode)partial)__eq____ne____lt____le____gt____ge__) integer_types text_typePY2)utilsx509)dsarsa) ffilibexception_from_error_queue byte_stringnative path_string UNSPECIFIEDtext_to_bytes_and_warn make_assert)$ FILETYPE_PEM FILETYPE_ASN1 FILETYPE_TEXTTYPE_RSATYPE_DSAErrorPKeyget_elliptic_curvesget_elliptic_curveX509Name X509ExtensionX509ReqX509X509StoreFlags X509StoreX509StoreContextErrorX509StoreContextload_certificatedump_certificatedump_publickeydump_privatekeyRevokedCRLPKCS7PKCS12 NetscapeSPKIload_publickeyload_privatekeydump_certificate_requestload_certificate_requestsignverifydump_crlload_crlload_pkcs7_data load_pkcs12ic@seZdZdZdS)rz7 An error occurred in an `OpenSSL.crypto` API. N)__name__ __module__ __qualname____doc__rBrB0/usr/lib/python3/dist-packages/OpenSSL/crypto.pyrPsrcCsddlm}|S)ap Importing the backend from cryptography has the side effect of activating the osrandom engine. This mutates the global state of OpenSSL in the process and causes issues for various programs that use subinterpreters or embed Python. By putting the import in this function we can avoid triggering this side effect unless _get_backend is called. rbackend),cryptography.hazmat.backends.openssl.backendrErDrBrBrC _get_backendZs rGcCstd|f)z An OpenSSL API failed somehow. Additionally, the failure which was encountered isn't one that's exercised by the test suite so future behavior of pyOpenSSL is now somewhat less predictable. zUnknown %s failure) RuntimeError)whererBrBrC_untested_errorgsrJcCsd|durtt}tj}ntd|}t|t|}|fdd}t|tj kt ||}|S)z Allocate a new OpenSSL memory BIO. Arrange for the garbage collector to clean it up automatically. :param buffer: None or some bytes to use to put into the BIO so that they can be read out. Nchar[]cSs t|SN)_libBIO_free)biorefrBrBrCfree z_new_mem_buf..free) rMBIO_new BIO_s_memrN_ffinewBIO_new_mem_buflen_openssl_assertNULLgc)bufferrOrQdatarBrBrC _new_mem_bufps    r^cCs.td}t||}t|d|ddS)zO Copy the contents of an OpenSSL BIO object into a Python byte string. zchar**rN)rUrVrMBIO_get_mem_datar\)rO result_buffer buffer_lengthrBrBrC_bio_to_strings  rbcCs2t|ts tdt||}|dkrtddS)a The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} is not a L{bytes} string. @raise ValueError: If C{when} does not represent a time in the required format. @raise RuntimeError: If the time value cannot be set for some other (unspecified) reason. zwhen must be a byte stringrzInvalid stringN) isinstancebytes TypeErrorrMASN1_TIME_set_string ValueError)boundarywhen set_resultrBrBrC_set_asn1_times  rkcCstd|}t|dkrdSt|tjkrtt|Std}t |||dtj kr7t ddStd|d}t|}t|}t |d|S)a] Retrieve the time value of an ASN1 time object. @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to that type) from which the time value will be retrieved. @return: The time value from C{timestamp} as a L{bytes} string in a certain format. Or C{None} if the object contains no time value. ASN1_STRING*rNzASN1_GENERALIZEDTIME**ASN1_TIME_to_generalizedtime) rUcastrMASN1_STRING_lengthASN1_STRING_typeV_ASN1_GENERALIZEDTIMEstringASN1_STRING_datarVrmrZrJASN1_GENERALIZEDTIME_free) timestampstring_timestampgeneralized_timestamp string_data string_resultrBrBrC_get_asn1_times      rzc@s$eZdZddZddZddZdS)_X509NameInvalidatorcCs g|_dSrL)_namesselfrBrBrC__init__rRz_X509NameInvalidator.__init__cCs|j|dSrL)r|appendr~namerBrBrCaddz_X509NameInvalidator.addcCs|jD]}|`qdSrL)r|_namerrBrBrCclears z_X509NameInvalidator.clearN)r>r?r@rrrrBrBrBrCr{s r{c@sTeZdZdZdZdZddZddZedd Z d d Z d d Z ddZ ddZ dS)r zD A class representing an DSA or RSA public key or key pair. FTcCs"t}t|tj|_d|_dS)NF)rM EVP_PKEY_newrUr[ EVP_PKEY_free_pkey _initializedr~pkeyrBrBrCrs z PKey.__init__cCsFddlm}m}t}|jrtt|}|||Stt|}||d|S)a Export as a ``cryptography`` key. :rtype: One of ``cryptography``'s `key interfaces`_. .. _key interfaces: https://cryptography.io/en/latest/hazmat/ primitives/asymmetric/rsa/#key-interfaces .. versionadded:: 16.1.0 r)load_der_private_keyload_der_public_keyN),cryptography.hazmat.primitives.serializationrrrG _only_publicr-rr.)r~rrrEderrBrBrCto_cryptography_keys     zPKey.to_cryptography_keycCst|tjtjtjtjfstdddlm }m }m }m }t|tjtjfr1t t||j|jS||j|j|}tt|S)z Construct based on a ``cryptography`` *crypto_key*. :param crypto_key: A ``cryptography`` key. :type crypto_key: One of ``cryptography``'s `key interfaces`_. :rtype: PKey .. versionadded:: 16.1.0 zUnsupported key typer)Encoding NoEncryption PrivateFormat PublicFormat)rcr RSAPublicKey RSAPrivateKeyr DSAPublicKey DSAPrivateKeyrerrrrrr4r public_bytesDERSubjectPublicKeyInfo private_bytesPKCS8r5)cls crypto_keyrrrrrrBrBrCfrom_cryptography_keys*    zPKey.from_cryptography_keyc Cs4t|ts tdt|tstd|tkrQ|dkrtdt}t|tj }t |tj t }t |||tj}t|dkt|j|}t|dknD|tkrt}t|tjkt|tj}t||tjdtjtjtj}t|dktt|dktt|j|dkntdd|_dS) a3 Generate a key pair of the given type, with the given number of bits. This generates a key "into" the this object. :param type: The key type. :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA` :param bits: The number of bits. :type bits: :py:data:`int` ``>= 0`` :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't of the appropriate type. :raises ValueError: If the number of bits isn't an integer of the appropriate size. :return: ``None`` type must be an integerzbits must be an integerrzInvalid number of bitszNo such key typeTN)rcintrerrgrMBN_newrUr[BN_free BN_set_wordRSA_F4RSA_newRSA_generate_key_exrZrYEVP_PKEY_assign_RSArrDSA_newDSA_freeDSA_generate_parameters_exDSA_generate_keyEVP_PKEY_set1_DSArr)r~typebitsexponentrresultrresrBrBrC generate_key/s6     zPKey.generate_keycCsd|jrtdt|tjkrtdt|j}t |tj }t |}|dkr-dSt dS)ax Check the consistency of an RSA private key. This is the Python equivalent of OpenSSL's ``RSA_check_key``. :return: ``True`` if key is consistent. :raise OpenSSL.crypto.Error: if the key is inconsistent. :raise TypeError: if the key is of a type which cannot be checked. Only RSA keys can currently be checked. zpublic key onlyzkey type unsupportedrTN) rrerM EVP_PKEY_typer EVP_PKEY_RSAEVP_PKEY_get1_RSArrUr[RSA_free RSA_check_key_raise_current_error)r~rrrBrBrCcheckgs    z PKey.checkcC t|jS)zT Returns the type of the key :return: The type of the key. )rM EVP_PKEY_idrr}rBrBrCr z PKey.typecCr)zh Returns the number of bits of the key :return: The number of bits of the key. )rM EVP_PKEY_bitsrr}rBrBrCrrz PKey.bitsN)r>r?r@rArrrr classmethodrrrrrrBrBrBrCr s *8 r csdeZdZdZdZesfddZeddZeddZ ed d Z d d Z d dZ ddZ ZS)_EllipticCurveaZ A representation of a supported elliptic curve. @cvar _curves: :py:obj:`None` until an attempt is made to load the curves. Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve` instances each of which represents one curve supported by the system. @type _curves: :py:type:`NoneType` or :py:type:`set` Ncst|tr tt||StS)z Implement cooperation with the right-hand side argument of ``!=``. Python 3 seems to have dropped this cooperation in this very narrow circumstance. )rcrsuperrNotImplemented)r~other __class__rBrCrs z_EllipticCurve.__ne__cs>tjd}td|}||tfdd|DS)z Get the curves supported by OpenSSL. :param lib: The OpenSSL library binding object. :return: A :py:type:`set` of ``cls`` instances giving the names of the elliptic curves the underlying library supports. rzEC_builtin_curve[]c3s|] }|jVqdSrL)from_nidnid).0crrrBrC sz7_EllipticCurve._load_elliptic_curves..)EC_get_builtin_curvesrUrZrVset)rr num_curvesbuiltin_curvesrBrrC_load_elliptic_curvess  z$_EllipticCurve._load_elliptic_curvescCs|jdur |||_|jS)a Get, cache, and return the curves supported by OpenSSL. :param lib: The OpenSSL library binding object. :return: A :py:type:`set` of ``cls`` instances giving the names of the elliptic curves the underlying library supports. N)_curvesrrrBrBrC_get_elliptic_curvess z#_EllipticCurve._get_elliptic_curvescCs|||t||dS)a Instantiate a new :py:class:`_EllipticCurve` associated with the given OpenSSL NID. :param lib: The OpenSSL library binding object. :param nid: The OpenSSL NID the resulting curve object will represent. This must be a curve NID (and not, for example, a hash NID) or subsequent operations will fail in unpredictable ways. :type nid: :py:class:`int` :return: The curve object. ascii)rUrr OBJ_nid2sndecode)rrrrBrBrCrsz_EllipticCurve.from_nidcCs||_||_||_dS)a :param _lib: The :py:mod:`cryptography` binding instance used to interface with OpenSSL. :param _nid: The OpenSSL NID identifying the curve this object represents. :type _nid: :py:class:`int` :param name: The OpenSSL short name identifying the curve this object represents. :type name: :py:class:`unicode` N)rM_nidr)r~rrrrBrBrCrs  z_EllipticCurve.__init__cCs d|jfS)Nz )rr}rBrBrC__repr__s z_EllipticCurve.__repr__cCs|j|j}t|tjS)z Create a new OpenSSL EC_KEY structure initialized to use this curve. The structure is automatically garbage collected when the Python object is garbage collected. )rMEC_KEY_new_by_curve_namerrUr[ EC_KEY_free)r~keyrBrBrC _to_EC_KEYsz_EllipticCurve._to_EC_KEY)r>r?r@rAr_PY2rrrrrrrr __classcell__rBrBrrCrs     rcCs ttS)a Return a set of objects representing the elliptic curves supported in the OpenSSL build in use. The curve objects have a :py:class:`unicode` ``name`` attribute by which they identify themselves. The curve objects are useful as values for the argument accepted by :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be used for ECDHE key exchange. )rrrMrBrBrBrCr!s r!cCs(tD] }|j|kr|Sqtd|)aT Return a single curve object selected by name. See :py:func:`get_elliptic_curves` for information about curve objects. :param name: The OpenSSL short name identifying the curve object to retrieve. :type name: :py:class:`unicode` If the named curve is not supported then :py:class:`ValueError` is raised. zunknown curve name)r!rrg)rcurverBrBrCr" s  r"cseZdZdZddZfddZfddZdd ZeeZee Z ee Z ee Z ee Z ee Z d d Zd d ZddZddZZS)r#a An X.509 Distinguished Name. :ivar countryName: The country of the entity. :ivar C: Alias for :py:attr:`countryName`. :ivar stateOrProvinceName: The state or province of the entity. :ivar ST: Alias for :py:attr:`stateOrProvinceName`. :ivar localityName: The locality of the entity. :ivar L: Alias for :py:attr:`localityName`. :ivar organizationName: The organization name of the entity. :ivar O: Alias for :py:attr:`organizationName`. :ivar organizationalUnitName: The organizational unit of the entity. :ivar OU: Alias for :py:attr:`organizationalUnitName` :ivar commonName: The common name of the entity. :ivar CN: Alias for :py:attr:`commonName`. :ivar emailAddress: The e-mail address of the entity. cCs t|j}t|tj|_dS)z Create a new X509Name, copying the given X509Name instance. :param name: The name to copy. :type name: :py:class:`X509Name` N)rM X509_NAME_duprrUr[X509_NAME_freerrBrBrCr5s zX509Name.__init__c s|drtt|||St|turtdt|jft t |}|tj kr?zt Wtdt y>Ytdwtt|jD]%}t|j|}t|}t|}||krlt|j|}t|nqGt|trw|d}t|j|tj|ddd}|st dSdS)N_z+attribute name must be string, not '%.200s'zNo such attributeutf-8r) startswithrr# __setattr__rstrrer>rM OBJ_txt2nid _byte_string NID_undefrrAttributeErrorrangeX509_NAME_entry_countrX509_NAME_get_entryX509_NAME_ENTRY_get_object OBJ_obj2nidX509_NAME_delete_entryX509_NAME_ENTRY_freerc _text_typeencodeX509_NAME_add_entry_by_NID MBSTRING_UTF8) r~rvaluerientent_objent_nid add_resultrrBrCr?sD           zX509Name.__setattr__c stt|}|tjkr#ztWn tyYnwtt||St |j |d}|dkr1dSt |j |}t |}t d}t||}t|dkzt |d|ddd}Wt|d|St|dw)a  Find attribute. An X509Name object has the following attributes: countryName (alias C), stateOrProvince (alias ST), locality (alias L), organization (alias O), organizationalUnit (alias OU), commonName (alias CN) and more... rNunsigned char**rr)rMrrrrrrr# __getattr__X509_NAME_get_index_by_NIDrrX509_NAME_ENTRY_get_datarUrVASN1_STRING_to_UTF8rYr\r OPENSSL_free) r~rr entry_indexentryr]r` data_lengthrrrBrCrfs.       zX509Name.__getattr__csfdd}|S)Ncs(t|tstSt|j|j}|dSNr)rcr#rrM X509_NAME_cmpr)r~rroprBrCfs  zX509Name._cmp..frB)r r rBr rC_cmps z X509Name._cmpcCsBtdd}t|j|t|}t|tjkdtt |fS)z6 String representation of an X509Name rKiz) rUrVrMX509_NAME_onelinerrXrYrZ_nativerr)r~r` format_resultrBrBrCrs   zX509Name.__repr__cCr)a& Return an integer representation of the first four bytes of the MD5 digest of the DER representation of the name. This is the Python equivalent of OpenSSL's ``X509_NAME_hash``. :return: The (integer) hash of this name. :rtype: :py:class:`int` )rMX509_NAME_hashrr}rBrBrChashs z X509Name.hashcCsNtd}t|j|}t|dkt|d|dd}t|d|S)z Return the DER encoding of this name. :return: The DER encoded form of this name. :rtype: :py:class:`bytes` rrN)rUrVrM i2d_X509_NAMErrYr\r)r~r` encode_resultryrBrBrCrs  z X509Name.derc Csg}tt|jD]7}t|j|}t|}t|}t|}t|}t t |t |dd}| t ||fq |S)z Returns the components of this name, as a sequence of 2-tuples. :return: The components of this name. :rtype: :py:class:`list` of ``name, value`` tuples. N)rrMrrrrrrrrUr\rsrorrr) r~rrrfnamefvalrrrrBrBrCget_componentss    zX509Name.get_components)r>r?r@rArrrrrrrrrr rrrrrrBrBrrCr#s  '(  r#c@sdeZdZdZdddZeddZejdej dej d iZ d d Z d d Z ddZddZddZdS)r$z, An X.509 v3 certificate extension. NcCstd}t|tjtjtjtjdt||dur)t|ts%td|j |_ |dur:t|ts6td|j |_ |r@d|}t tj|||}|tjkrQt t|tj|_dS)a Initializes an X509 extension. :param type_name: The name of the type of extension_ to create. :type type_name: :py:data:`bytes` :param bool critical: A flag indicating whether this is a critical extension. :param value: The value of the extension. :type value: :py:data:`bytes` :param subject: Optional X509 certificate to use as subject. :type subject: :py:class:`X509` :param issuer: Optional X509 certificate to use as issuer. :type issuer: :py:class:`X509` .. _extension: https://www.openssl.org/docs/manmaster/man5/ x509v3_config.html#STANDARD-EXTENSIONS z X509V3_CTX*rNzissuer must be an X509 instancez subject must be an X509 instances critical,)rUrVrMX509V3_set_ctxrZX509V3_set_ctx_nodbrcr&re_x509 issuer_cert subject_certX509V3_EXT_nconfrr[X509_EXTENSION_free _extension)r~ type_namecriticalrsubjectissuerctx extensionrBrBrCrs"     zX509Extension.__init__cCstt|jSrL)rMrX509_EXTENSION_get_objectr r}rBrBrCr&s zX509Extension._nidemailDNSURIc Cstdt|j}t|tj}g}tt|D]G}t ||}z|j |j }Wnt yEt }t|||tt|Yqwtt|jjj|jjjdd}||d|qd|S)NzGENERAL_NAMES*:z, )rUrnrMX509V3_EXT_d2ir r[GENERAL_NAMES_freersk_GENERAL_NAME_numsk_GENERAL_NAME_value _prefixesrKeyErrorr^GENERAL_NAME_printrrrbr\dia5r]lengthjoin)r~namespartsrrlabelrOrrBrBrC_subjectAltNameString2s&     z#X509Extension._subjectAltNameStringcCsDtj|jkr |St}t||jdd}t|dktt |S)zF :return: a nice text representation of the extension r) rMNID_subject_alt_namerr:r^X509V3_EXT_printr rYrrb)r~rO print_resultrBrBrC__str__Hs   zX509Extension.__str__cCr)zk Returns the critical field of this X.509 extension. :return: The critical field. )rMX509_EXTENSION_get_criticalr r}rBrBrC get_criticalUrzX509Extension.get_criticalcCs&t|j}t|}tt|S)z Returns the short type name of this X.509 extension. The result is a byte string such as :py:const:`b"basicConstraints"`. :return: The short type name. :rtype: :py:data:`bytes` .. versionadded:: 0.12 )rMr'r rrUrrr)r~objrrBrBrCget_short_name]s zX509Extension.get_short_namecCs@t|j}td|}t|}t|}t||ddS)z Returns the data of the X509 extension, encoded as ASN.1. :return: The ASN.1 encoded data of this X509 extension. :rtype: :py:data:`bytes` .. versionadded:: 0.12 rlN)rMX509_EXTENSION_get_datar rUrnrsror\)r~ octet_resultry char_result result_lengthrBrBrCget_datals   zX509Extension.get_dataNN)r>r?r@rArpropertyrrM GEN_EMAILGEN_DNSGEN_URIr0r:r>r@rBrGrBrBrBrCr$s =   r$c@steZdZdZddZddZeddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZdS)r%z0 An X.509 certificate signing requests. cCs&t}t|tj|_|ddSr )rM X509_REQ_newrUr[ X509_REQ_free_req set_version)r~reqrBrBrCrszX509Req.__init__cC&ddlm}tt|}t}|||S)z Export as a ``cryptography`` certificate signing request. :rtype: ``cryptography.x509.CertificateSigningRequest`` .. versionadded:: 17.1.0 r)load_der_x509_csr)cryptography.x509rSr6rrG)r~rSrrErBrBrCto_cryptography   zX509Req.to_cryptographycC6t|tjs tdddlm}||j}tt |S)a Construct based on a ``cryptography`` *crypto_req*. :param crypto_req: A ``cryptography`` X.509 certificate signing request :type crypto_req: ``cryptography.x509.CertificateSigningRequest`` :rtype: X509Req .. versionadded:: 17.1.0 z%Must be a certificate signing requestrr) rcrCertificateSigningRequestrerrrrr7r)r crypto_reqrrrBrBrCfrom_cryptography    zX509Req.from_cryptographycC t|j|j}t|dkdS)z Set the public key of the certificate signing request. :param pkey: The public key to use. :type pkey: :py:class:`PKey` :return: ``None`` rN)rMX509_REQ_set_pubkeyrOrrYr~rrjrBrBrC set_pubkeys zX509Req.set_pubkeycCDtt}t|j|_t|jtjkt |jtj |_d|_ |S)z Get the public key of the certificate signing request. :return: The public key. :rtype: :py:class:`PKey` T) r __new__rMX509_REQ_get_pubkeyrOrrYrUrZr[rrrrBrBrC get_pubkey zX509Req.get_pubkeycCst|j|}t|dkdS)z Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate request. :param int version: The version number. :return: ``None`` rN)rMX509_REQ_set_versionrOrY)r~versionrjrBrBrCrPszX509Req.set_versioncCr)z Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate request. :return: The value of the version subfield. :rtype: :py:class:`int` )rMX509_REQ_get_versionrOr}rBrBrC get_versions zX509Req.get_versioncCs2tt}t|j|_t|jtjk||_ |S)a Return the subject of this certificate signing request. This creates a new :class:`X509Name` that wraps the underlying subject name field on the certificate signing request. Modifying it will modify the underlying signing request, and will have the effect of modifying any other :class:`X509Name` that refers to this subject. :return: The subject of this certificate signing request. :rtype: :class:`X509Name` ) r#rbrMX509_REQ_get_subject_namerOrrYrUrZ_ownerrrBrBrC get_subjects zX509Req.get_subjectcCslt}t|tjkt|tj}|D]}t|tst dt ||j qt |j |}t|dkdS)z Add extensions to the certificate signing request. :param extensions: The X.509 extensions to add. :type extensions: iterable of :py:class:`X509Extension` :return: ``None`` +One of the elements is not an X509ExtensionrN)rMsk_X509_EXTENSION_new_nullrYrUrZr[sk_X509_EXTENSION_freercr$rgsk_X509_EXTENSION_pushr X509_REQ_add_extensionsrO)r~ extensionsstackextrrBrBrCadd_extensionss zX509Req.add_extensionscCsng}t|j}t|dd}tt|D]}tt}t t ||}t|tj |_ | |q|S)z Get X.509 extensions in the certificate signing request. :return: The X.509 extensions in this request. :rtype: :py:class:`list` of :py:class:`X509Extension` objects. .. versionadded:: 0.15 cSst|ttjdS)Nr)rMsk_X509_EXTENSION_pop_freerU addressof _original_lib)xrBrBrCs z(X509Req.get_extensions..)rMX509_REQ_get_extensionsrOrUr[rsk_X509_EXTENSION_numr$rbX509_EXTENSION_dupsk_X509_EXTENSION_valuerr r)r~extsnative_exts_objrrtr&rBrBrCget_extensionss    zX509Req.get_extensionscC^|jrtd|jstdtt|}|tjkrtdt|j |j |}t |dkdS)ad Sign the certificate signing request with this key and digest type. :param pkey: The key pair to sign with. :type pkey: :py:class:`PKey` :param digest: The name of the message digest to use for the signature, e.g. :py:data:`b"sha256"`. :type digest: :py:class:`bytes` :return: ``None`` Key has only public partKey is uninitializedNo such digest methodrN) rrgrrMEVP_get_digestbynamerrUrZ X509_REQ_signrOrrYr~rdigest digest_obj sign_resultrBrBrCr8"s  z X509Req.signcCs4t|ts tdt|j|j}|dkrt|S)a@ Verifies the signature on this certificate signing request. :param PKey key: A public key. :return: ``True`` if the signature is correct. :rtype: bool :raises OpenSSL.crypto.Error: If the signature is invalid or there is a problem verifying the signature. pkey must be a PKey instancer)rcr rerMX509_REQ_verifyrOrr)r~rrrBrBrCr9:s zX509Req.verifyN)r>r?r@rArrUrr[r`rdrPrirlrurr8r9rBrBrBrCr%|s     r%c@seZdZdZddZeddZddZedd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Z d:d;Z!dd?Z#d@dAZ$dBS)Cr&z An X.509 certificate. cCs:t}t|tjkt|tj|_t|_ t|_ dSrL) rMX509_newrYrUrZr[ X509_freerr{_issuer_invalidator_subject_invalidator)r~rrBrBrCrUs  z X509.__init__cCs.||}t|tj|_t|_t|_|SrL) rbrUr[rMrrr{rr)rrcertrBrBrC_from_raw_x509_ptr]s zX509._from_raw_x509_ptrcCrR)z Export as a ``cryptography`` certificate. :rtype: ``cryptography.x509.Certificate`` .. versionadded:: 17.1.0 r)load_der_x509_certificate)rTrr,rrG)r~rrrErBrBrCrUes   zX509.to_cryptographycCrW)z Construct based on a ``cryptography`` *crypto_cert*. :param crypto_key: A ``cryptography`` X.509 certificate. :type crypto_key: ``cryptography.x509.Certificate`` :rtype: X509 .. versionadded:: 17.1.0 zMust be a certificaterrX) rcr Certificatererrrrr+r)r crypto_certrrrBrBrCr[sr\zX509.from_cryptographycCs$t|ts tdt|j|dS)a  Set the version number of the certificate. Note that the version value is zero-based, eg. a value of 0 is V1. :param version: The version number of the certificate. :type version: :py:class:`int` :return: ``None`` zversion must be an integerN)rcrrerMX509_set_versionrr~rgrBrBrCrPs zX509.set_versioncCr)z Return the version number of the certificate. :return: The version number of the certificate. :rtype: :py:class:`int` )rMX509_get_versionrr}rBrBrCri zX509.get_versioncCsFtt}t|j|_|jtjkrtt |jtj |_d|_ |S)z{ Get the public key of the certificate. :return: The public key. :rtype: :py:class:`PKey` T) r rbrMX509_get_pubkeyrrrUrZrr[rrrrBrBrCrds  zX509.get_pubkeycCs2t|ts tdt|j|j}t|dkdS)z Set the public key of the certificate. :param pkey: The public key. :type pkey: :py:class:`PKey` :return: :py:data:`None` rrN)rcr rerMX509_set_pubkeyrrrYr_rBrBrCr`s zX509.set_pubkeycCspt|ts td|jrtd|jstdtt|}|t j kr'tdt |j |j |}t|dkdS)a Sign the certificate with this key and digest type. :param pkey: The key to sign with. :type pkey: :py:class:`PKey` :param digest: The name of the message digest to use. :type digest: :py:class:`bytes` :return: :py:data:`None` rzKey only has public partrrrN)rcr rerrgrrMrrrUrZ X509_signrrrY)r~rrevp_mdrrBrBrCr8s  z X509.signcCs:t|j}t|j}|tjkrtdtt |S)z Return the signature algorithm used in the certificate. :return: The name of the algorithm. :rtype: :py:class:`bytes` :raises ValueError: If the signature algorithm is undefined. .. versionadded:: 0.13 zUndefined signature algorithm) rMX509_get0_tbs_sigalgrr algorithmrrgrUrr OBJ_nid2ln)r~algorrrBrBrCget_signature_algorithms  zX509.get_signature_algorithmcCstt|}|tjkrtdtdtj}tdd}t||d<t |j |||}t |dkd ddt ||dDS) a7 Return the digest of the X509 object. :param digest_name: The name of the digest algorithm to use. :type digest_name: :py:class:`bytes` :return: The digest of the object, formatted as :py:const:`b":"`-delimited hex pairs. :rtype: :py:class:`bytes` runsigned char[]zunsigned int[]rr:cSsg|]}t|qSrB)rupper)rchrBrBrC s zX509.digest..)rMrrrUrZrgrVEVP_MAX_MD_SIZErX X509_digestrrYr6r\)r~ digest_namerr`rF digest_resultrBrBrCrs     z X509.digestcCr)z Return the hash of the X509 subject. :return: The hash of the subject. :rtype: :py:class:`bytes` )rMX509_subject_name_hashrr}rBrBrCsubject_name_hash rzX509.subject_name_hashcCst|ts tdt|dd}t|ts|d}td}t ||}|dtj kr@t t |j |}|r>tdSdSt|dtj }t|d|tj krXtt|tj}t|j |}t|dkdS)z Set the serial number of the certificate. :param serial: The new serial number. :type serial: :py:class:`int` :return: :py:data`None` zserial must be an integerNrBIGNUM**rr)rc_integer_typesrehexrdrrUrVrM BN_hex2bnrZASN1_INTEGER_setX509_get_serialNumberrrBN_to_ASN1_INTEGERrr[ASN1_INTEGER_freeX509_set_serialNumberrY)r~serial hex_serial bignum_serial small_serialrj asn1_serialrBrBrCset_serial_numbers*        zX509.set_serial_numberc Cspt|j}t|tj}z$t|}zt|}t|d}|Wt |Wt |St |wt |w)zx Return the serial number of this certificate. :return: The serial number. :rtype: int ) rMrrASN1_INTEGER_to_BNrUrZ BN_bn2hexrrrrr)r~rrrhexstring_serialrrBrBrCget_serial_number:s       zX509.get_serial_numbercC.t|ts tdt|j}t||dS)z Adjust the time stamp on which the certificate stops being valid. :param int amount: The number of seconds by which to adjust the timestamp. :return: ``None`` amount must be an integerN)rcrrerMX509_getm_notAfterrX509_gmtime_adj)r~amountnotAfterrBrBrCgmtime_adj_notAfterNs  zX509.gmtime_adj_notAftercCr)z Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None`` rN)rcrrerMX509_getm_notBeforerr)r~r notBeforerBrBrCgmtime_adj_notBefore\s  zX509.gmtime_adj_notBeforecCs(t|}tj|d}|tjkS)z Check whether the certificate has expired. :return: ``True`` if the certificate has expired, ``False`` otherwise. :rtype: bool z %Y%m%d%H%M%SZ)r get_notAfterdatetimestrptimeutcnow)r~ time_string not_afterrBrBrC has_expiredis zX509.has_expiredcCst||jSrL)rzr)r~whichrBrBrC_get_boundary_timeuszX509._get_boundary_timecC |tjS)a  Get the timestamp at which the certificate starts being valid. The timestamp is formatted as an ASN.1 TIME:: YYYYMMDDhhmmssZ :return: A timestamp string, or ``None`` if there is none. :rtype: bytes or NoneType )rrMrr}rBrBrC get_notBeforex zX509.get_notBeforecCt||j|SrL)rkrr~rrirBrBrC_set_boundary_timerzX509._set_boundary_timecC|tj|S)z Set the timestamp at which the certificate starts being valid. The timestamp is formatted as an ASN.1 TIME:: YYYYMMDDhhmmssZ :param bytes when: A timestamp string. :return: ``None`` )rrMrr~rirBrBrC set_notBefore zX509.set_notBeforecCr)a  Get the timestamp at which the certificate stops being valid. The timestamp is formatted as an ASN.1 TIME:: YYYYMMDDhhmmssZ :return: A timestamp string, or ``None`` if there is none. :rtype: bytes or NoneType )rrMrr}rBrBrCrrzX509.get_notAftercCr)z Set the timestamp at which the certificate stops being valid. The timestamp is formatted as an ASN.1 TIME:: YYYYMMDDhhmmssZ :param bytes when: A timestamp string. :return: ``None`` )rrMrrrBrBrC set_notAfterrzX509.set_notAftercCs0tt}||j|_t|jtjk||_|SrL)r#rbrrrYrUrZrk)r~rrrBrBrC _get_names  zX509._get_namecCs0t|ts td||j|j}t|dkdS)Nzname must be an X509Namer)rcr#rerrrY)r~rrrjrBrBrC _set_names zX509._set_namecC|tj}|j||S)a Return the issuer of this certificate. This creates a new :class:`X509Name` that wraps the underlying issuer name field on the certificate. Modifying it will modify the underlying certificate, and will have the effect of modifying any other :class:`X509Name` that refers to this issuer. :return: The issuer of this certificate. :rtype: :class:`X509Name` )rrMX509_get_issuer_namerrrrBrBrC get_issuer zX509.get_issuercC|tj||jdS)z Set the issuer of this certificate. :param issuer: The issuer. :type issuer: :py:class:`X509Name` :return: ``None`` N)rrMX509_set_issuer_namerr)r~r$rBrBrC set_issuer zX509.set_issuercCr)a Return the subject of this certificate. This creates a new :class:`X509Name` that wraps the underlying subject name field on the certificate. Modifying it will modify the underlying certificate, and will have the effect of modifying any other :class:`X509Name` that refers to this subject. :return: The subject of this certificate. :rtype: :class:`X509Name` )rrMX509_get_subject_namerrrrBrBrCrlrzX509.get_subjectcCr)z Set the subject of this certificate. :param subject: The subject. :type subject: :py:class:`X509Name` :return: ``None`` N)rrMX509_set_subject_namerr)r~r#rBrBrC set_subjectrzX509.set_subjectcCr)z Get the number of extensions on this certificate. :return: The number of extensions. :rtype: :py:class:`int` .. versionadded:: 0.12 )rMX509_get_ext_countrr}rBrBrCget_extension_counts zX509.get_extension_countcCs<|D]}t|ts tdt|j|jd}|stqdS)z Add extensions to the certificate. :param extensions: The extensions to add. :type extensions: An iterable of :py:class:`X509Extension` objects. :return: ``None`` rmrN)rcr$rgrM X509_add_extrr r)r~rrrtrrBrBrCrus zX509.add_extensionscCsNtt}t|j||_|jtjkrtdt |j}t |tj |_|S)a Get a specific extension of the certificate by index. Extensions on a certificate are kept in order. The index parameter selects which extension will be returned. :param int index: The index of the extension to retrieve. :return: The extension at the specified index. :rtype: :py:class:`X509Extension` :raises IndexError: If the extension index was out of bounds. .. versionadded:: 0.12 zextension index out of bounds) r$rbrM X509_get_extrr rUrZ IndexErrorr}r[r)r~indexrtr&rBrBrC get_extensions   zX509.get_extensionN)%r>r?r@rArrrrUr[rPrirdr`r8rrrrrrrrrrrrrrrrrrrlrrrurrBrBrBrCr&PsH    (          r&c@sLeZdZdZejZejZej Z ej Z ej ZejZejZejZejZejZdS)r'a  Flags for X509 verification, used to change the behavior of :class:`X509Store`. See `OpenSSL Verification Flags`_ for details. .. _OpenSSL Verification Flags: https://www.openssl.org/docs/manmaster/man3/X509_VERIFY_PARAM_set_flags.html N)r>r?r@rArMX509_V_FLAG_CRL_CHECK CRL_CHECKX509_V_FLAG_CRL_CHECK_ALL CRL_CHECK_ALLX509_V_FLAG_IGNORE_CRITICALIGNORE_CRITICALX509_V_FLAG_X509_STRICT X509_STRICTX509_V_FLAG_ALLOW_PROXY_CERTSALLOW_PROXY_CERTSX509_V_FLAG_POLICY_CHECK POLICY_CHECKX509_V_FLAG_EXPLICIT_POLICYEXPLICIT_POLICYX509_V_FLAG_INHIBIT_MAP INHIBIT_MAPX509_V_FLAG_NOTIFY_POLICY NOTIFY_POLICYX509_V_FLAG_CHECK_SS_SIGNATURECHECK_SS_SIGNATURErBrBrBrCr'+s  r'c@sBeZdZdZddZddZddZdd Zd d Zdd dZ d S)r(a An X.509 store. An X.509 store is used to describe a context in which to verify a certificate. A description of a context may include a set of certificates to trust, a set of certificate revocation lists, verification flags and more. An X.509 store, being only a description, cannot be used by itself to verify a certificate. To carry out the actual verification process, see :class:`X509StoreContext`. cCt}t|tj|_dSrL)rMX509_STORE_newrUr[X509_STORE_free_storer~storerBrBrCrPzX509Store.__init__cCs0t|tstt|j|j}t|dkdS)a Adds a trusted certificate to this store. Adding a certificate with this method adds this certificate as a *trusted* certificate. :param X509 cert: The certificate to add to this store. :raises TypeError: If the certificate is not an :class:`X509`. :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your certificate. :return: ``None`` if the certificate was added successfully. rN)rcr&rerMX509_STORE_add_certr rrY)r~rrrBrBrCadd_certTs zX509Store.add_certcCstt|j|jdkdS)a Add a certificate revocation list to this store. The certificate revocation lists added to a store will only be used if the associated flags are configured to check certificate revocation lists. .. versionadded:: 16.1.0 :param CRL crl: The certificate revocation list to add to this store. :return: ``None`` if the certificate revocation list was added successfully. rN)rYrMX509_STORE_add_crlr _crlr~crlrBrBrCadd_crljszX509Store.add_crlcCtt|j|dkdS)a Set verification flags to this store. Verification flags can be combined by oring them together. .. note:: Setting a verification flag sometimes requires clients to add additional information to the store, otherwise a suitable error will be raised. For example, in setting flags to enable CRL checking a suitable CRL must be added to the store otherwise an error will be raised. .. versionadded:: 16.1.0 :param int flags: The verification flags to set on this store. See :class:`X509StoreFlags` for available constants. :return: ``None`` if the verification flags were successfully set. rN)rYrMX509_STORE_set_flagsr )r~flagsrBrBrC set_flagszszX509Store.set_flagscCsFt}t|tj}t|t|t t |j |dkdS)a Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param datetime vfy_time: The verification time to set on this store. :return: ``None`` if the verification time was successfully set. rN) rMX509_VERIFY_PARAM_newrUr[X509_VERIFY_PARAM_freeX509_VERIFY_PARAM_set_timecalendartimegm timetuplerYX509_STORE_set1_paramr )r~vfy_timeparamrBrBrCset_times zX509Store.set_timeNcCsR|durtj}nt|}|durtj}nt|}t|j||}|s'tdSdS)a Let X509Store know where we can find trusted certificates for the certificate chain. Note that the certificates have to be in PEM format. If *capath* is passed, it must be a directory prepared using the ``c_rehash`` tool included with OpenSSL. Either, but not both, of *cafile* or *capath* may be ``None``. .. note:: Both *cafile* and *capath* may be set simultaneously. Call this method multiple times to add more than one location. For example, CA certificates, and certificate revocation list bundles may be passed in *cafile* in subsequent calls to this method. .. versionadded:: 20.0 :param cafile: In which file we can find the certificates (``bytes`` or ``unicode``). :param capath: In which directory we can find the certificates (``bytes`` or ``unicode``). :return: ``None`` if the locations were set successfully. :raises OpenSSL.crypto.Error: If both *cafile* and *capath* is ``None`` or the locations could not be set for any reason. N)rUrZ _path_stringrMX509_STORE_load_locationsr r)r~cafilecapath load_resultrBrBrCload_locationss zX509Store.load_locationsrL) r>r?r@rArrrrr%r+rBrBrBrCr(Bs r(cs eZdZdZfddZZS)r)z An exception raised when an error occurred while verifying a certificate using `OpenSSL.X509StoreContext.verify_certificate`. :ivar certificate: The certificate which caused verificate failure. :type certificate: :class:`X509` cstt||||_dSrL)rr)r certificate)r~messager,rrBrCrs zX509StoreContextError.__init__)r>r?r@rArrrBrBrrCr)sr)c@sVeZdZdZdddZeddZddZd d Zd d Z d dZ ddZ ddZ dS)r*a An X.509 store context. An X.509 store context is used to carry out the actual verification process of a certificate in a described context. For describing such a context, see :class:`X509Store`. :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this instance. It is dynamically allocated and automatically garbage collected. :ivar _store: See the ``store`` ``__init__`` parameter. :ivar _cert: See the ``certificate`` ``__init__`` parameter. :ivar _chain: See the ``chain`` ``__init__`` parameter. :param X509Store store: The certificates which will be trusted for the purposes of any verifications. :param X509 certificate: The certificate to be verified. :param chain: List of untrusted certificates that may be used for building the certificate chain. May be ``None``. :type chain: :class:`list` of :class:`X509` NcCs<t}t|tj|_||_||_|||_ | dSrL) rMX509_STORE_CTX_newrUr[X509_STORE_CTX_free _store_ctxr _cert_build_certificate_stack_chain_init)r~rr,chain store_ctxrBrBrCrs   zX509StoreContext.__init__cCsdd}|dust|dkrtjSt}t|tjkt||}|D]'}t|ts/t dtt |j dkt ||j dkrKt |j tq$|S)NcSs8tt|D] }t||}t|qt|dSrL)rrM sk_X509_num sk_X509_valuer sk_X509_free)srryrBrBrCcleanup s  z:X509StoreContext._build_certificate_stack..cleanuprz+One of the elements is not an X509 instance)rXrUrZrMsk_X509_new_nullrYr[rcr&re X509_up_refr sk_X509_pushrr) certificatesr;rsrrBrBrCr2 s   z)X509StoreContext._build_certificate_stackcCs2t|j|jj|jj|j}|dkrtdSdS)z Set up the store context for a subsequent verification operation. Calling this method more than once without first calling :meth:`_cleanup` will leak memory. rN)rMX509_STORE_CTX_initr0r r1rr3rr~retrBrBrCr4%s  zX509StoreContext._initcCst|jdS)z Internally cleans up the store context. The store context can then be reused with a new call to :meth:`_init`. N)rMX509_STORE_CTX_cleanupr0r}rBrBrC_cleanup2zX509StoreContext._cleanupc Cs\t|jt|jtttt|jg}t|j}t |}t |}t ||S)z Convert an OpenSSL native context error failure into a Python exception. When a call to native OpenSSL X509_verify_cert fails, additional information about the failure can be obtained from the store context. ) rMX509_STORE_CTX_get_errorr0X509_STORE_CTX_get_error_depthrrUrrX509_verify_cert_error_stringX509_STORE_CTX_get_current_certX509_dupr&rr))r~errorsrr1pycertrBrBrC_exception_from_context:s     z(X509StoreContext._exception_from_contextcCs ||_dS)z Set the context's X.509 store. .. versionadded:: 0.15 :param X509Store store: The store description which will be used for the purposes of any *future* verifications. N)r rrBrBrC set_storeTs zX509StoreContext.set_storecCs8||t|j}||dkr|dS)a" Verify a certificate in a context. .. versionadded:: 0.15 :raises X509StoreContextError: If an error occurred when validating a certificate in the context. Sets ``certificate`` attribute to indicate which certificate caused the error. rN)rDr4rMX509_verify_certr0rMrArBrBrCverify_certificate_s z#X509StoreContext.verify_certificatecCs||t|j}|dkr||t|j}t|tj kg}t t |D]}t ||}t|tj kt |}||q0t|||S)aR Verify a certificate in a context and return the complete validated chain. :raises X509StoreContextError: If an error occurred when validating a certificate in the context. Sets ``certificate`` attribute to indicate which certificate caused the error. .. versionadded:: 20.0 r)rDr4rMrOr0rMX509_STORE_CTX_get1_chainrYrUrZrr7r8r&rrr9)r~rB cert_stackrrrrLrBrBrCget_verified_chainus"      z#X509StoreContext.get_verified_chainrL) r>r?r@rAr staticmethodr2r4rDrMrNrPrSrBrBrBrCr*s    r*cCsvt|tr |d}t|}|tkrt|tjtjtj}n|t kr*t |tj}nt d|tjkr6t t |S)a Load a certificate (X509) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param bytes buffer: The buffer the certificate is stored in :return: The X509 object r3type argument must be FILETYPE_PEM or FILETYPE_ASN1)rcrrr^rrMPEM_read_bio_X509rUrZr d2i_X509_biorgrr&r)rr\rOrrBrBrCr+s   r+cCsnt}|tkrt||j}n|tkrt||j}n|tkr)t||jdd}nt dt |dkt |S)a Dump the certificate *cert* into a buffer string encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT) :param cert: The certificate to dump :return: The buffer with the dumped certificate in rCtype argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXTr) r^rrMPEM_write_bio_X509rr i2d_X509_bior X509_print_exrgrYrb)rrrO result_coderBrBrCr,s  r,cCsPt}|tkr tj}n |tkrtj}ntd|||j}|dkr$tt |S)z Dump a public key to a buffer. :param type: The file type (one of :data:`FILETYPE_PEM` or :data:`FILETYPE_ASN1`). :param PKey pkey: The public key to dump :return: The buffer with the dumped key in it. :rtype: bytes rUr) r^rrMPEM_write_bio_PUBKEYri2d_PUBKEY_biorgrrrb)rrrO write_bior\rBrBrCr-s  r-c Cst}t|ts td|dur)|durtdtt|}|tjkr(t dntj}t ||}|t krIt ||j |tjd|j|j}|n4|tkrUt||j }n(|tkryt|j tjkrftdtt|j tj}t||d}nt dt|dkt|S)a Dump the private key *pkey* into a buffer string encoded with the type *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it using *cipher* and *passphrase*. :param type: The file type (one of :const:`FILETYPE_PEM`, :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`) :param PKey pkey: The PKey to dump :param cipher: (optional) if encrypted PEM format, the cipher to use :param passphrase: (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase. :return: The buffer with the dumped key in :rtype: bytes zpkey must be a PKeyNzDif a value is given for cipher one must also be given for passphrasezInvalid cipher namerz-Only RSA keys are supported for FILETYPE_TEXTrX)r^rcr rerMEVP_get_cipherbynamerrUrZrg_PassphraseHelperrPEM_write_bio_PrivateKeyrcallback callback_argsraise_if_problemri2d_PrivateKey_biorrrr[rr RSA_printrYrb) rrcipher passphraserO cipher_objhelperr\rrBrBrCr.sJ     r.c@s`eZdZdZgdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ dS)r/z# A certificate revocation. )s unspecifieds keyCompromises CACompromisesaffiliationChangeds supersededscessationOfOperationscertificateHoldcCr rL)rMX509_REVOKED_newrUr[X509_REVOKED_free_revoked)r~revokedrBrBrCrCrzRevoked.__init__cCsftttj}td}||d<t||}|stdtt|tj tj }t |j |dS)z Set the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :param bytes hex_str: The new serial number. :return: ``None`` rrzbad hex stringN) rUr[rMrrrVrrgrrZrX509_REVOKED_set_serialNumberrn)r~hex_strr bignum_ptr bn_resultrrBrBrC set_serialGs   zRevoked.set_serialcCs@t}t|j}t|tjkt||}t|dkt|S)z Get the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :return: The serial number. :rtype: bytes r) r^rMX509_REVOKED_get0_serialNumberrnrYrUrZi2a_ASN1_INTEGERrb)r~rOasn1_intrrBrBrC get_serial_s    zRevoked.get_serialcCs`tt|jD]%}t|j|}t|}t|tjkr-t|t |j|dSqdSrL) rrMX509_REVOKED_get_ext_countrnX509_REVOKED_get_extr'rNID_crl_reasonrX509_REVOKED_delete_ext)r~rrtrArBrBrC_delete_reasonqs  zRevoked._delete_reasoncCs|dur |dSt|tstd|dd}dd|jD|}t }t |t j kt |tj}t||}t |t j k|t|jtj|dd}t |dkdS) a Set the reason of this revocation. If :data:`reason` is ``None``, delete the reason instead. :param reason: The reason string. :type reason: :class:`bytes` or :class:`NoneType` :return: ``None`` .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons which you might pass to this method. Nz$reason must be None or a byte string cSsg|]}|qSrB)lower)rrrBrBrCrsz&Revoked.set_reason..rr)r}rcrdrerreplace _crl_reasonsrrMASN1_ENUMERATED_newrYrUrZr[ASN1_ENUMERATED_freeASN1_ENUMERATED_setX509_REVOKED_add1_ext_i2drnr{)r~reason reason_codenew_reason_extrjrrBrBrC set_reasonzs    zRevoked.set_reasoncCstt|jD]8}t|j|}t|}t|tjkr@t}t ||dd}|s:t |t |}t |dkt |SqdS)a  Get the reason of this revocation. :return: The reason, or ``None`` if there is none. :rtype: bytes or NoneType .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons this method might return. rN)rrMryrnrzr'rr{r^r<M_ASN1_OCTET_STRING_printrCrYrb)r~rrtrArOr=rBrBrC get_reasons     zRevoked.get_reasoncCs|jddS)a Return a list of all the supported reason strings. This list is a copy; modifying it does not change the supported reason strings. :return: A list of reason strings. :rtype: :class:`list` of :class:`bytes` N)rr}rBrBrC all_reasonss zRevoked.all_reasonscCst|j}t||S)z Set the revocation timestamp. :param bytes when: The timestamp of the revocation, as ASN.1 TIME. :return: ``None`` )rM X509_REVOKED_get0_revocationDaternrk)r~ridtrBrBrC set_rev_dates  zRevoked.set_rev_datecCst|j}t|S)z Get the revocation timestamp. :return: The timestamp of the revocation, as ASN.1 TIME. :rtype: bytes )rMrrnrz)r~rrBrBrC get_rev_dates zRevoked.get_rev_dateN)r>r?r@rArrrtrxr}rrrrrrBrBrBrCr//s  % r/c@s|eZdZdZddZddZeddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZedefddZdS)r0z( A certificate revocation list. cCr rL)rM X509_CRL_newrUr[ X509_CRL_freerrrBrBrCrrz CRL.__init__cCrR)z Export as a ``cryptography`` CRL. :rtype: ``cryptography.x509.CertificateRevocationList`` .. versionadded:: 17.1.0 r)load_der_x509_crl)rTrr:rrG)r~rrrErBrBrCrUrVzCRL.to_cryptographycCrW)a Construct based on a ``cryptography`` *crypto_crl*. :param crypto_crl: A ``cryptography`` certificate revocation list :type crypto_crl: ``cryptography.x509.CertificateRevocationList`` :rtype: CRL .. versionadded:: 17.1.0 z%Must be a certificate revocation listrrX) rcrCertificateRevocationListrerrrrr;r)r crypto_crlrrrBrBrCr[r\zCRL.from_cryptographycCsng}t|j}tt|D]}t||}t|}tt}t |tj |_ | |q|r5t|SdS)aA Return the revocations in this certificate revocation list. These revocations will be provided by value, not by reference. That means it's okay to mutate them: it won't affect this CRL. :return: The revocations in this CRL. :rtype: :class:`tuple` of :class:`Revocation` N)rMX509_CRL_get_REVOKEDrrsk_X509_REVOKED_numsk_X509_REVOKED_valueCryptography_X509_REVOKED_dupr/rbrUr[rmrnrtuple)r~results revoked_stackrro revoked_copypyrevrBrBrC get_revoked s     zCRL.get_revokedcCs8t|j}t|tjkt|j|}t|dkdS)a9 Add a revoked (by value not reference) to the CRL structure This revocation will be added by value, not by reference. That means it's okay to mutate it after adding: it won't affect this CRL. :param Revoked revoked: The new revocation. :return: ``None`` rN)rMrrnrYrUrZX509_CRL_add0_revokedr)r~rocopyrrBrBrC add_revoked s zCRL.add_revokedcCsBtt|j}t|tjkt|tj}t t }||_ |S)zc Get the CRL's issuer. .. versionadded:: 16.1.0 :rtype: X509Name ) rMrX509_CRL_get_issuerrrYrUrZr[rr#rbr)r~_issuerr$rBrBrCr. s  zCRL.get_issuercCr)z Set the CRL version. .. versionadded:: 16.1.0 :param int version: The version of the CRL. :return: ``None`` rN)rYrMX509_CRL_set_versionrrrBrBrCrP= s zCRL.set_versioncCrrL)rkrrrBrBrCrH rzCRL._set_boundary_timecCr)z Set when the CRL was last updated. The timestamp is formatted as an ASN.1 TIME:: YYYYMMDDhhmmssZ .. versionadded:: 16.1.0 :param bytes when: A timestamp string. :return: ``None`` )rrMX509_CRL_get_lastUpdaterrBrBrCset_lastUpdateK  zCRL.set_lastUpdatecCr)z Set when the CRL will next be updated. The timestamp is formatted as an ASN.1 TIME:: YYYYMMDDhhmmssZ .. versionadded:: 16.1.0 :param bytes when: A timestamp string. :return: ``None`` )rrMX509_CRL_get_nextUpdaterrBrBrCset_nextUpdateZ rzCRL.set_nextUpdatecCs\t|}t|tjkt|jt|jt |jt |j|j |}t|dkdS)a; Sign the CRL. Signing a CRL enables clients to associate the CRL itself with an issuer. Before a CRL is meaningful to other OpenSSL functions, it must be signed by an issuer. This method implicitly sets the issuer's name based on the issuer certificate and private key used to sign the CRL. .. versionadded:: 16.1.0 :param X509 issuer_cert: The issuer's certificate. :param PKey issuer_key: The issuer's private key. :param bytes digest: The digest method to sign the CRL with. rN) rMrrYrUrZX509_CRL_set_issuer_namerrr X509_CRL_sort X509_CRL_signr)r~r issuer_keyrrrrBrBrCr8i s  zCRL.signdc Cst|ts tdt|tstdt|tstd|tur#tdt|}|tj kr1t dt t }t |tj kt}t |tj kt|dt|j|t||dddt|j|t|jt|jt|j|j|} | stt||S) a Export the CRL as a string. :param X509 cert: The certificate used to sign the CRL. :param PKey key: The key used to sign the CRL. :param int type: The export format, either :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`. :param int days: The number of days until the next update of this CRL. :param bytes digest: The name of the message digest to use (eg ``b"sha256"``). :rtype: bytes cert must be an X509 instancezkey must be a PKey instancerzdigest must be providedrr<)rcr&rer r _UNSPECIFIEDrMrrUrZrgrSrTrY ASN1_TIME_newrX509_CRL_set_lastUpdaterX509_CRL_set_nextUpdaterrrrrrr:) r~rrrdaysrrrOsometimerrBrBrCexport s4       z CRL.exportN)r>r?r@rArrUrr[rrrrPrrrr8rrrrBrBrBrCr0s   r0c@s4eZdZddZddZddZddZd d Zd S) r1cCtt|jS)zm Check if this NID_pkcs7_signed object :return: True if the PKCS7 is of type signed )boolrMPKCS7_type_is_signed_pkcs7r}rBrBrCtype_is_signed rEzPKCS7.type_is_signedcCr)zt Check if this NID_pkcs7_enveloped object :returns: True if the PKCS7 is of type enveloped )rrMPKCS7_type_is_envelopedrr}rBrBrCtype_is_enveloped rEzPKCS7.type_is_envelopedcCr)z Check if this NID_pkcs7_signedAndEnveloped object :returns: True if the PKCS7 is of type signedAndEnveloped )rrM PKCS7_type_is_signedAndEnvelopedrr}rBrBrCtype_is_signedAndEnveloped rEz PKCS7.type_is_signedAndEnvelopedcCr)zi Check if this NID_pkcs7_data object :return: True if the PKCS7 is of type data )rrMPKCS7_type_is_datarr}rBrBrC type_is_data rEzPKCS7.type_is_datacCs"t|jj}t|}t|S)zk Returns the type name of the PKCS7 structure :return: A string with the typename )rMrrrrrUrr)r~r string_typerBrBrC get_type_name s  zPKCS7.get_type_nameN)r>r?r@rrrrrrBrBrBrCr1 s  r1c@sbeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ dddZ dS)r2z A PKCS #12 archive. cCsd|_d|_d|_d|_dSrL)rr1_cacerts _friendlynamer}rBrBrCr s zPKCS12.__init__cC|jS)z Get the certificate in the PKCS #12 structure. :return: The certificate, or :py:const:`None` if there is none. :rtype: :py:class:`X509` or :py:const:`None` )r1r}rBrBrCget_certificate zPKCS12.get_certificatecCt|ts td||_dS)z Set the certificate in the PKCS #12 structure. :param cert: The new certificate, or :py:const:`None` to unset it. :type cert: :py:class:`X509` or :py:const:`None` :return: ``None`` rN)rcr&rer1)r~rrBrBrCset_certificate   zPKCS12.set_certificatecCr)z Get the private key in the PKCS #12 structure. :return: The private key, or :py:const:`None` if there is none. :rtype: :py:class:`PKey` )rr}rBrBrCget_privatekey rzPKCS12.get_privatekeycCr)z Set the certificate portion of the PKCS #12 structure. :param pkey: The new private key, or :py:const:`None` to unset it. :type pkey: :py:class:`PKey` or :py:const:`None` :return: ``None`` rN)rcr rerrrBrBrCset_privatekey rzPKCS12.set_privatekeycCs|jdur t|jSdS)a Get the CA certificates in the PKCS #12 structure. :return: A tuple with the CA certificates in the chain, or :py:const:`None` if there are none. :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None` N)rrr}rBrBrCget_ca_certificates s  zPKCS12.get_ca_certificatescCs@|dur d|_dSt|}|D] }t|tstdq||_dS)a Replace or set the CA certificates within the PKCS12 object. :param cacerts: The new CA certificates, or :py:const:`None` to unset them. :type cacerts: An iterable of :py:class:`X509` or :py:const:`None` :return: ``None`` Nz)iterable must only contain X509 instances)rlistrcr&re)r~cacertsrrBrBrCset_ca_certificates( s   zPKCS12.set_ca_certificatescCs2|durd|_n t|tstd|f||_dS)z Set the friendly name in the PKCS #12 structure. :param name: The new friendly name, or :py:const:`None` to unset. :type name: :py:class:`bytes` or :py:const:`None` :return: ``None`` Nz+name must be a byte string or None (not %r))rrcrdrerrBrBrCset_friendlyname= s   zPKCS12.set_friendlynamecCr)z Get the friendly name in the PKCS# 12 structure. :returns: The friendly name, or :py:const:`None` if there is none. :rtype: :py:class:`bytes` or :py:const:`None` )rr}rBrBrCget_friendlynameN rzPKCS12.get_friendlynameNrc Cstd|}|jdurtj}nt}t|tj}|jD] }t||j q|dur-tj}|j }|dur7tj}|j dur@tj}n|j j }|j durMtj}n|j j }t |||||tjtj||d }|tjkritt|tj}t} t| |t| S)a Dump a PKCS12 object as a string. For more information, see the :c:func:`PKCS12_create` man page. :param passphrase: The passphrase used to encrypt the structure. Unlike some other passphrase arguments, this *must* be a string, not a callback. :type passphrase: :py:data:`bytes` :param iter: Number of times to repeat the encryption step. :type iter: :py:data:`int` :param maciter: Number of times to repeat the MAC step. :type maciter: :py:data:`int` :return: The string representation of the PKCS #12 structure. :rtype: riNr)_text_to_bytes_and_warnrrUrZrMr<r[r9r>rrrr1 PKCS12_create&NID_pbe_WithSHA1And3_Key_TripleDES_CBCr PKCS12_freer^i2d_PKCS12_biorb) r~riitermaciterrr friendlynamerpkcs12rOrBrBrCrW sH       z PKCS12.export)Nrr)r>r?r@rArrrrrrrrrrrBrBrBrCr2 s      r2c@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)r3z! A Netscape SPKI object. cCr rL)rMNETSCAPE_SPKI_newrUr[NETSCAPE_SPKI_free_spki)r~spkirBrBrCr rzNetscapeSPKI.__init__cCr)a Sign the certificate request with this key and digest type. :param pkey: The private key to sign with. :type pkey: :py:class:`PKey` :param digest: The message digest to use. :type digest: :py:class:`bytes` :return: ``None`` rrrrN) rrgrrMrrrUrZNETSCAPE_SPKI_signrrrYrrBrBrCr8 s   zNetscapeSPKI.signcCs"t|j|j}|dkrtdS)aY Verifies a signature on a certificate request. :param PKey key: The public key that signature is supposedly from. :return: ``True`` if the signature is correct. :rtype: bool :raises OpenSSL.crypto.Error: If the signature is invalid, or there was a problem verifying the signature. rT)rMNETSCAPE_SPKI_verifyrrr)r~ranswerrBrBrCr9 s zNetscapeSPKI.verifycCs$t|j}t|}t||S)z Generate a base64 encoded representation of this SPKI object. :return: The base64 encoded string. :rtype: :py:class:`bytes` )rMNETSCAPE_SPKI_b64_encoderrUrrr)r~encodedrrBrBrC b64_encode s   zNetscapeSPKI.b64_encodecCra)z| Get the public key of this certificate. :return: The public key. :rtype: :py:class:`PKey` T) r rbrMNETSCAPE_SPKI_get_pubkeyrrrYrUrZr[rrrrBrBrCrd rezNetscapeSPKI.get_pubkeycCr])zv Set the public key of the certificate :param pkey: The public key :return: ``None`` rN)rMNETSCAPE_SPKI_set_pubkeyrrrYr_rBrBrCr` szNetscapeSPKI.set_pubkeyN) r>r?r@rArr8r9rrdr`rBrBrBrCr3 s r3c@sBeZdZd ddZeddZeddZefdd Zd d Z d S)raFcCs4|tkr |dur td||_||_||_g|_dS)Nz0only FILETYPE_PEM key format supports encryption)rrg _passphrase _more_args _truncate _problems)r~rri more_argstruncaterBrBrCr s z_PassphraseHelper.__init__cCs<|jdurtjSt|jtst|jrtd|jStd)Npem_password_cb2Last argument must be a byte string or a callable.) rrUrZrcrdcallablerc_read_passphraserer}rBrBrCrc s z_PassphraseHelper.callbackcCs4|jdurtjSt|jtst|jrtjStd)Nr)rrUrZrcrdrrer}rBrBrCrd s z_PassphraseHelper.callback_argscCs6|jrzt|Wn |yYnw|jddSr )r_exception_from_error_queuepop)r~ exceptionTyperBrBrCre s   z"_PassphraseHelper.raise_if_problemc CszNt|jr|jr||||}n ||}n|j}t|ts#tdt||kr7|jr3|d|}ntdtt|D] }|||d||<q=t|WSt yg}z |j |WYd}~dSd}~ww)NzBytes expectedz+passphrase returned by callback is too longrr) rrrrcrdrgrXrr Exceptionrr)r~bufsizerwflaguserdatarrerBrBrCr! s,      z"_PassphraseHelper._read_passphraseN)FF) r>r?r@rrIrcrdrrerrBrBrBrCra s    racCst|tr |d}t|}|tkrt|tjtjtj}n|t kr*t |tj}nt d|tjkr6t t t }t|tj|_d|_|S)a< Load a public key from a buffer. :param type: The file type (one of :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`). :param buffer: The buffer the key is stored in. :type buffer: A Python string object, either unicode or bytestring. :return: The PKey object. :rtype: :class:`PKey` rrUT)rcrrr^rrMPEM_read_bio_PUBKEYrUrZrd2i_PUBKEY_biorgrr rbr[rrr)rr\rOevp_pkeyrrBrBrCr4; s   r4cCst|tr |d}t|}t||}|tkr't|tj |j |j }| n|t kr3t|tj }ntd|tj kr?ttt}t|tj|_|S)a Load a private key (PKey) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the key is stored in :param passphrase: (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase. :return: The PKey object rrU)rcrrr^rarrMPEM_read_bio_PrivateKeyrUrZrcrdrerd2i_PrivateKey_biorgrr rbr[rr)rr\rirOrkrrrBrBrCr5] s"     r5cCsnt}|tkrt||j}n|tkrt||j}n|tkr)t||jdd}nt dt |dkt |S)a Dump the certificate request *req* into a buffer string encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param req: The certificate request to dump :return: The buffer with the dumped certificate request in rrX) r^rrMPEM_write_bio_X509_REQrOri2d_X509_REQ_biorX509_REQ_print_exrgrYrb)rrQrOr\rBrBrCr6 s  r6cCst|tr |d}t|}|tkrt|tjtjtj}n|t kr*t |tj}nt dt |tjkt t }t|tj|_|S)a Load a certificate request (X509Req) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the certificate request is stored in :return: The X509Req object rrU)rcrrr^rrMPEM_read_bio_X509_REQrUrZrd2i_X509_REQ_biorgrYr%rbr[rNrO)rr\rOrQx509reqrBrBrCr7 s  r7c Cstd|}tt|}|tjkrtdt}t|tj }t ||t ||t |t |j}t|dktd|}td}t||||j}t|dkt||dddS)z Sign a data string using the given key and message digest. :param pkey: PKey to sign with :param data: data to be signed :param digest: message digest to use :return: signature .. versionadded:: 0.11 r]rrrzunsigned int *rN)rrMrrrUrZrgCryptography_EVP_MD_CTX_newr[Cryptography_EVP_MD_CTX_free EVP_SignInitEVP_SignUpdaterX EVP_PKEY_sizerrYrV EVP_SignFinalr\) rr]rrmd_ctxr5signature_buffersignature_length final_resultrBrBrCr8 s"         r8cCstd|}tt|}|tjkrtdt|j}t |tjkt |tj }t }t |tj }t||t||t|t||t||}|dkrVtdSdS)a Verify the signature for a data string. :param cert: signing certificate (X509 object) corresponding to the private key which generated the signature. :param signature: signature returned by sign function :param data: data to be verified :param digest: message digest to use :return: ``None`` if the signature is correct, raise exception otherwise. .. versionadded:: 0.11 r]rrN)rrMrrrUrZrgrrrYr[rr rEVP_VerifyInitEVP_VerifyUpdaterXEVP_VerifyFinalr)r signaturer]rrrr verify_resultrBrBrCr9 s"      r9cCsjt}|tkrt||j}n|tkrt||j}n|tkr't||j}nt dt |dkt |S)a Dump a certificate revocation list to a buffer. :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or ``FILETYPE_TEXT``). :param CRL crl: The CRL to dump. :return: The buffer with the CRL. :rtype: bytes rXr) r^rrMPEM_write_bio_X509_CRLrri2d_X509_CRL_biorX509_CRL_printrgrYrb)rrrOrBrBrBrCr: s  r:cCt|tr |d}t|}|tkrt|tjtjtj}n|t kr*t |tj}nt d|tjkr6t t t }t|tj|_|S)a Load Certificate Revocation List (CRL) data from a string *buffer*. *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the CRL is stored in :return: The PKey object rrU)rcrrr^rrMPEM_read_bio_X509_CRLrUrZrd2i_X509_CRL_biorgrr0rbr[rr)rr\rOrrrBrBrCr; s   r;cCr)z Load pkcs7 data from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1) :param buffer: The buffer with the pkcs7 data. :return: The PKCS7 object rrU)rcrrr^rrMPEM_read_bio_PKCS7rUrZr d2i_PKCS7_biorgrr1rbr[ PKCS7_freer)rr\rOpkcs7pypkcs7rBrBrCr<< s   r<zSPKCS#7 support in pyOpenSSL is deprecated. You should use the APIs in cryptography.cCstd|}t|tr|d}t|}|stj}t|tj}|tjkr't t |tj }t d}t d}t d}t |||||}|sKt t |dtj}zt Wn tybYnw|dtjkrmd}ntt}t |dtj|_|dtjkrd} d} n't|d} t d} t|d| } t| | ddd} | tjkrd} g} tt|D]}t||}t|}| |q| sd} tt}||_| |_| |_| |_|S) a Load pkcs12 data from the string *buffer*. If the pkcs12 structure is encrypted, a *passphrase* must be included. The MAC is always checked and thus required. See also the man page for the C function :py:func:`PKCS12_parse`. :param buffer: The buffer the certificate is stored in :param passphrase: (Optional) The password to decrypt the PKCS12 lump :returns: The PKCS12 object rirz EVP_PKEY**zX509**zCryptography_STACK_OF_X509**rNzint*) rrcrrr^rUrZrMd2i_PKCS12_biorr[rrV PKCS12_parser9rr rbrrr&rX509_alias_get0r\rr7r8rr2r1rr)r\rirOp12rrr parse_resultpykeyrLrfriendlyname_lengthfriendlyname_buffer pycacertsrrpycacertrrBrBrCr=d sl               r=zTPKCS#12 support in pyOpenSSL is deprecated. You should use the APIs in cryptography.sutf8onlyrLrH)mrrbase64r functoolsroperatorrrrrrr sixr rr rr r cryptographyr r)cryptography.hazmat.primitives.asymmetricrr OpenSSL._utilrrUrrMrrrrrrrr&rrrrr _make_assert__all__SSL_FILETYPE_PEMrSSL_FILETYPE_ASN1rrrr EVP_PKEY_DSAr EVP_PKEY_DHTYPE_DH EVP_PKEY_ECTYPE_ECrrrrYrGrJr^rbrkrzobjectr{r rr!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3rar4r5r6r7r8r9r:r;r< deprecatedr>DeprecationWarningr=OpenSSL_add_all_algorithmsSSL_load_error_strings ASN1_STRING_set_default_mask_ascrBrBrBrCs   , '   ) 4iIU^6 @._,6ZF "%#$ W