????

Your IP : 3.16.10.2


Current Path : /lib/python3.9/site-packages/OpenSSL/__pycache__/
Upload File :
Current File : //lib/python3.9/site-packages/OpenSSL/__pycache__/crypto.cpython-39.pyc

a

�Saӛ�@sddlZddlZddlmZddlmZddlmZmZm	Z	m
Z
mZmZddl
mZmZmZddlmZmZddlmZmZddlmZmZmZ m!Z"m#Z$m%Z&m'Z(m)Z*m+Z,gd	�Z-ej.Z/ej0Z1d
Z2ej3Z4ej5Z6ej7Z8ej9Z:Gdd�de;�Z<ee e<�Z=e,e<�Z>d
d�Z?dd�Z@d^dd�ZAdd�ZBdd�ZCdd�ZDGdd�deE�ZFGdd�deE�ZGGdd�deE�ZHdd �ZId!d"�ZJGd#d$�d$eE�ZKGd%d&�d&eE�ZLGd'd(�d(eE�ZMGd)d*�d*eE�ZNGd+d,�d,eE�ZOGd-d.�d.eE�ZPGd/d0�d0e;�ZQGd1d2�d2eE�ZRd3d4�ZSd5d6�ZTd7d8�ZUd_d9d:�ZVGd;d<�d<eE�ZWGd=d>�d>eE�ZXGd?d@�d@eE�ZYGdAdB�dBeE�ZZGdCdD�dDeE�Z[GdEdF�dFeE�Z\dGdH�Z]d`dIdJ�Z^dKdL�Z_dMdN�Z`dOdP�ZadQdR�ZbdSdT�ZcdUdV�ZddWdX�Zee�feeegdYeh�ZedadZd[�Zie�feiegd\eh�Zie�j�e�k�e�ld]�dS)b�N)�	b16encode)�partial)�__eq__�__ne__�__lt__�__le__�__gt__�__ge__)�
integer_types�	text_type�PY2)�utils�x509)�dsa�rsa)	�ffi�lib�exception_from_error_queue�byte_string�native�path_string�UNSPECIFIED�text_to_bytes_and_warn�make_assert)$�FILETYPE_PEM�
FILETYPE_ASN1�
FILETYPE_TEXT�TYPE_RSA�TYPE_DSA�Error�PKey�get_elliptic_curves�get_elliptic_curve�X509Name�
X509Extension�X509Req�X509�X509StoreFlags�	X509Store�X509StoreContextError�X509StoreContext�load_certificate�dump_certificate�dump_publickey�dump_privatekey�Revoked�CRL�PKCS7�PKCS12�NetscapeSPKI�load_publickey�load_privatekey�dump_certificate_request�load_certificate_request�sign�verify�dump_crl�load_crl�load_pkcs7_data�load_pkcs12i��c@seZdZdZdS)rz7
    An error occurred in an `OpenSSL.crypto` API.
    N)�__name__�
__module__�__qualname__�__doc__�rBrB�2/usr/lib/python3.9/site-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.
    r��backend)Z,cryptography.hazmat.backends.openssl.backendrErDrBrBrC�_get_backendZsrFcCstd|f��dS)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 failureN)�RuntimeError)�whererBrBrC�_untested_errorgsrIcCsd|durt�t���}tj}n(t�d|�}t�|t|��}|fdd�}t|tj	k�t�
||�}|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.
    N�char[]cSs
t�|�S�N)�_lib�BIO_free)�bio�refrBrBrC�free�sz_new_mem_buf.<locals>.free)rL�BIO_new�	BIO_s_memrM�_ffi�newZBIO_new_mem_buf�len�_openssl_assert�NULL�gc)�bufferrNrP�datarBrBrC�_new_mem_bufps	r[cCs.t�d�}t�||�}t�|d|�dd�S)zO
    Copy the contents of an OpenSSL BIO object into a Python byte string.
    zchar**rN)rSrTrLZBIO_get_mem_datarY)rN�
result_bufferZ
buffer_lengthrBrBrC�_bio_to_string�s
r]cCs2t|t�std��t�||�}|dkr.td��dS)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)�
isinstance�bytes�	TypeErrorrLZASN1_TIME_set_string�
ValueError)�boundary�when�
set_resultrBrBrC�_set_asn1_time�s

recCs�t�d|�}t�|�dkrdSt�|�tjkr>t�t�|��St�d�}t�	||�|dtj
krltd�n6t�d|d�}t�|�}t�|�}t�|d�|SdS)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)
rS�castrL�ASN1_STRING_lengthZASN1_STRING_typeZV_ASN1_GENERALIZEDTIME�string�ASN1_STRING_datarTrgrWrIZASN1_GENERALIZEDTIME_free)Z	timestampZstring_timestampZgeneralized_timestampZstring_data�
string_resultrBrBrC�_get_asn1_time�s"
�


�

rmc@s$eZdZdd�Zdd�Zdd�ZdS)�_X509NameInvalidatorcCs
g|_dSrK)�_names��selfrBrBrC�__init__�sz_X509NameInvalidator.__init__cCs|j�|�dSrK)ro�append�rq�namerBrBrC�add�sz_X509NameInvalidator.addcCs|jD]}|`qdSrK)ro�_namertrBrBrC�clear�s
z_X509NameInvalidator.clearN)r>r?r@rrrvrxrBrBrBrCrn�srnc@sTeZdZdZdZdZdd�Zdd�Zedd	��Z	d
d�Z
dd
�Zdd�Zdd�Z
dS)r zD
    A class representing an DSA or RSA public key or key pair.
    FTcCs"t��}t�|tj�|_d|_dS)NF)rLZEVP_PKEY_newrSrX�
EVP_PKEY_free�_pkey�_initialized�rq�pkeyrBrBrCrr�sz
PKey.__init__cCsJddlm}m}t�}|jr0tt|�}|||�Stt|�}||d|�SdS)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_key�load_der_public_keyN)�,cryptography.hazmat.primitives.serializationr~rrF�_only_publicr-rr.)rqr~rrE�derrBrBrC�to_cryptography_key�s


zPKey.to_cryptography_keycCs�t|tjtjtjtjf�s"td��ddlm	}m
}m}m}t|tjtjf�rbt
t|�|j|j��S|�|j|j|��}tt|�SdS)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�PublicFormatN)r^rZRSAPublicKeyZ
RSAPrivateKeyrZDSAPublicKeyZ
DSAPrivateKeyr`r�r�r�r�r�r4r�public_bytes�DERZSubjectPublicKeyInfoZ
private_bytesZPKCS8r5)�clsZ
crypto_keyr�r�r�r�r�rBrBrC�from_cryptography_keys*��	���zPKey.from_cryptography_keyc	Cs6t|t�std��t|t�s$td��|tkr�|dkr<td��t��}t�|tj	�}t�
|tj�t��}t�
|||tj�}t|dk�t�|j|�}t|dk�n�|tk�r$t��}t|tjk�t�|tj�}t�||tjdtjtjtj�}t|dk�tt�|�dk�tt�|j|�dk�ntd��d|_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 bits�zNo such key typeTN)r^�intr`rrarL�BN_newrSrX�BN_freeZBN_set_wordZRSA_F4ZRSA_newZRSA_generate_key_exrWrVZEVP_PKEY_assign_RSArzrZDSA_newZDSA_freeZDSA_generate_parameters_exZDSA_generate_keyZEVP_PKEY_set1_DSArr{)rq�type�bitsZexponentr�resultr�resrBrBrC�generate_key/s6


�zPKey.generate_keycCsd|jrtd��t�|���tjkr*td��t�|j�}t�	|tj
�}t�|�}|dkrZdSt�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 unsupportedr�TN)
r�r`rLZ
EVP_PKEY_typer��EVP_PKEY_RSA�EVP_PKEY_get1_RSArzrSrX�RSA_freeZ
RSA_check_key�_raise_current_error)rqrr�rBrBrC�checkgs

z
PKey.checkcCst�|j�S)zT
        Returns the type of the key

        :return: The type of the key.
        )rL�EVP_PKEY_idrzrprBrBrCr��sz	PKey.typecCst�|j�S)zh
        Returns the number of bits of the key

        :return: The number of bits of the key.
        )rLZ
EVP_PKEY_bitsrzrprBrBrCr��sz	PKey.bitsN)r>r?r@rAr�r{rrr��classmethodr�r�r�r�r�rBrBrBrCr �s
*8r csdeZdZdZdZes �fdd�Zedd��Zedd��Z	ed	d
��Z
dd�Zd
d�Zdd�Z
�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|t�rtt|��|�StS)z�
            Implement cooperation with the right-hand side argument of ``!=``.

            Python 3 seems to have dropped this cooperation in this very narrow
            circumstance.
            )r^r��superr�NotImplemented)rq�other��	__class__rBrCr�s
z_EllipticCurve.__ne__cs>��tjd�}t�d|�}��||�t��fdd�|D��S)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|]}���|j�VqdSrK)�from_nid�nid)�.0�c�r�rrBrC�	<genexpr>��z7_EllipticCurve._load_elliptic_curves.<locals>.<genexpr>)ZEC_get_builtin_curvesrSrWrT�set)r�rZ
num_curvesZbuiltin_curvesrBr�rC�_load_elliptic_curves�s
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)�_curvesr�r�rBrBrC�_get_elliptic_curves�s

z#_EllipticCurve._get_elliptic_curvescCs|||t�|�|���d��S)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)rSrj�
OBJ_nid2sn�decode)r�rr�rBrBrCr��sz_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)rL�_nidru)rqrr�rurBrBrCrr�s
z_EllipticCurve.__init__cCsd|jfS)Nz
<Curve %r>)rurprBrBrC�__repr__�sz_EllipticCurve.__repr__cCs|j�|j�}t�|tj�S)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.
        )rLZEC_KEY_new_by_curve_namer�rSrXZEC_KEY_free)rq�keyrBrBrC�
_to_EC_KEY�sz_EllipticCurve._to_EC_KEY)r>r?r@rAr��_PY2rr�r�r�r�rrr�r��
__classcell__rBrBr�rCr��s	



r�cCs
t�t�S)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.
    )r�r�rLrBrBrBrCr!�sr!cCs,t�D]}|j|kr|Sqtd|��dS)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 nameN)r!rura)ruZcurverBrBrCr"
s


r"cs�eZdZdZdd�Z�fdd�Z�fdd�Zdd	�Zee�Zee	�Z	ee
�Z
ee�Zee�Zee
�Z
d
d�Zdd
�Zdd�Zdd�Z�ZS)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)rL�
X509_NAME_duprwrSrX�X509_NAME_freertrBrBrCrr5szX509Name.__init__c		s|�d�rtt|��||�St|�tur<tdt|�jf��t�	t
|��}|tjkrzz
t�Wnt
ypYn0td��tt�|j��D]J}t�|j|�}t�|�}t�|�}||kr�t�|j|�}t�|�q�q�t|t�r�|�d�}t�|j|tj|ddd�}|�st�dS)N�_z+attribute name must be string, not '%.200s'zNo such attribute�utf-8���r)�
startswithr�r#�__setattr__r��strr`r>rL�OBJ_txt2nid�_byte_string�	NID_undefr�r�AttributeError�range�X509_NAME_entry_countrw�X509_NAME_get_entry�X509_NAME_ENTRY_get_object�OBJ_obj2nidZX509_NAME_delete_entryZX509_NAME_ENTRY_freer^�
_text_type�encodeZX509_NAME_add_entry_by_NIDZ
MBSTRING_UTF8)	rqru�valuer��i�entZent_objZent_nid�
add_resultr�rBrCr�?s<

��






�zX509Name.__setattr__c	
s�t�t|��}|tjkrFz
t�Wnty4Yn0tt|��|�St�	|j
|d�}|dkrbdSt�|j
|�}t�|�}t
�d�}t�||�}t|dk�z0t
�|d|�dd��d�}Wt�|d�nt�|d�0|S)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...
        r�N�unsigned char**rr�)rLr�r�r�r�rr�r#�__getattr__ZX509_NAME_get_index_by_NIDrwr��X509_NAME_ENTRY_get_datarSrTZASN1_STRING_to_UTF8rVrYr��OPENSSL_free)	rqrur�Zentry_index�entryrZr\Zdata_lengthr�r�rBrCr�fs*



� zX509Name.__getattr__cs�fdd�}|S)Ncs(t|t�stSt�|j|j�}�|d�S�Nr)r^r#r�rLZ
X509_NAME_cmprw)rqr�r���oprBrC�f�s
zX509Name._cmp.<locals>.frB)r�r�rBr�rC�_cmp�sz
X509Name._cmpcCsBt�dd�}t�|j|t|��}t|tjk�dtt�	|��fS)z6
        String representation of an X509Name
        rJiz<X509Name object '%s'>)
rSrTrLZX509_NAME_onelinerwrUrVrW�_nativerj)rqr\Z
format_resultrBrBrCr��s��zX509Name.__repr__cCst�|j�S)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`
        )rLZX509_NAME_hashrwrprBrBrC�hash�s
z
X509Name.hashcCsNt�d�}t�|j|�}t|dk�t�|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`
        r�rN)rSrTrLZ
i2d_X509_NAMErwrVrYr�)rqr\Z
encode_resultrlrBrBrCr��s
zX509Name.derc	Cs�g}tt�|j��D]n}t�|j|�}t�|�}t�|�}t�|�}t�|�}t	�
t�|�t�|��dd�}|�
t	�|�|f�q|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)r�rLr�rwr�r�r�r�r�rSrYrkrirsrj)	rqr�r�r��fnameZfvalr�rur�rBrBrC�get_components�s



��zX509Name.get_components)r>r?r@rArrr�r�r�rrrrrr	r�r�r�r�r�rBrBr�rCr#s
'(	r#c@sdeZdZdZddd�Zedd��Zejdej	dej
d	iZd
d�Zdd
�Z
dd�Zdd�Zdd�ZdS)r$z,
    An X.509 v3 certificate extension.
    NcCs�t�d�}t�|tjtjtjtjd�t�|�|durRt|t�sJtd��|j	|_
|durtt|t�sltd��|j	|_|r�d|}t�tj|||�}|tjkr�t
�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
        zX509V3_CTX*rNzissuer must be an X509 instancez subject must be an X509 instances	critical,)rSrTrLZX509V3_set_ctxrWZX509V3_set_ctx_nodbr^r&r`�_x509�issuer_certZsubject_certZX509V3_EXT_nconfr�rX�X509_EXTENSION_free�
_extension)rq�	type_nameZcriticalr��subject�issuer�ctx�	extensionrBrBrCrr�s"




zX509Extension.__init__cCst�t�|j��SrK)rLr��X509_EXTENSION_get_objectr�rprBrBrCr�&s
�zX509Extension._nidZemailZDNSZURIc	Cs�t�dt�|j��}t�|tj�}g}tt�|��D]�}t�	||�}z|j
|j}Wn6ty�t
�}t�||�|�tt|���Yq40tt�|jjj|jjj�dd��}|�|d|�q4d�|�S)NzGENERAL_NAMES*�:z, )rSrhrLZX509V3_EXT_d2ir�rXZGENERAL_NAMES_freer�Zsk_GENERAL_NAME_numZsk_GENERAL_NAME_value�	_prefixesr��KeyErrorr[ZGENERAL_NAME_printrsr�r]rY�dZia5rZ�length�join)rq�names�partsr�ruZlabelrNr�rBrBrC�_subjectAltNameString2s$��z#X509Extension._subjectAltNameStringcCsDtj|jkr|��St�}t�||jdd�}t|dk�tt	|��S)zF
        :return: a nice text representation of the extension
        r)
rLZNID_subject_alt_namer�r�r[�X509V3_EXT_printr�rVr�r])rqrN�print_resultrBrBrC�__str__HszX509Extension.__str__cCst�|j�S)zk
        Returns the critical field of this X.509 extension.

        :return: The critical field.
        )rLZX509_EXTENSION_get_criticalr�rprBrBrC�get_criticalUszX509Extension.get_criticalcCs&t�|j�}t�|�}t�t�|��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
        )rLr�r�r�rSrjr�)rq�objr�rBrBrC�get_short_name]s
zX509Extension.get_short_namecCs@t�|j�}t�d|�}t�|�}t�|�}t�||�dd�S)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
        rfN)rL�X509_EXTENSION_get_datar�rSrhrkrirY)rqZoctet_resultrlZchar_result�
result_lengthrBrBrC�get_datals
	

zX509Extension.get_data)NN)r>r?r@rArr�propertyr�rLZ	GEN_EMAILZGEN_DNSZGEN_URIr�r�r�r�r�r�rBrBrBrCr$�s
=
�
r$c@steZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�ZdS)r%z0
    An X.509 certificate signing requests.
    cCs&t��}t�|tj�|_|�d�dSr�)rLZX509_REQ_newrSrX�
X509_REQ_free�_req�set_version)rq�reqrBrBrCrr�szX509Req.__init__cCs&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.x509r�r6rrF)rqr�r�rErBrBrC�to_cryptography�s
zX509Req.to_cryptographycCs6t|tj�std��ddlm}|�|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 requestr�r�)
r^rZCertificateSigningRequestr`r�r�r�r�r7r)r�Z
crypto_reqr�r�rBrBrC�from_cryptography�s
zX509Req.from_cryptographycCs t�|j|j�}t|dk�dS)z�
        Set the public key of the certificate signing request.

        :param pkey: The public key to use.
        :type pkey: :py:class:`PKey`

        :return: ``None``
        r�N)rLZX509_REQ_set_pubkeyr�rzrV�rqr}rdrBrBrC�
set_pubkey�s	zX509Req.set_pubkeycCsDt�t�}t�|j�|_t|jtjk�t�	|jtj
�|_d|_|S)z�
        Get the public key of the certificate signing request.

        :return: The public key.
        :rtype: :py:class:`PKey`
        T)r �__new__rLZX509_REQ_get_pubkeyr�rzrVrSrWrXryr�r|rBrBrC�
get_pubkey�s
zX509Req.get_pubkeycCst�|j|�}t|dk�dS)z�
        Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
        request.

        :param int version: The version number.
        :return: ``None``
        r�N)rLZX509_REQ_set_versionr�rV)rq�versionrdrBrBrCr��szX509Req.set_versioncCst�|j�S)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`
        )rLZX509_REQ_get_versionr�rprBrBrC�get_version�szX509Req.get_versioncCs2t�t�}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#rrLZX509_REQ_get_subject_namer�rwrVrSrW�_ownerrtrBrBrC�get_subject�s

zX509Req.get_subjectcCslt��}t|tjk�t�|tj�}|D]$}t|t�s>t	d��t�
||j�q(t�|j
|�}t|dk�dS)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 X509Extensionr�N)rLZsk_X509_EXTENSION_new_nullrVrSrWrXZsk_X509_EXTENSION_freer^r$raZsk_X509_EXTENSION_pushr�ZX509_REQ_add_extensionsr�)rq�
extensions�stack�extr�rBrBrC�add_extensions�s
zX509Req.add_extensionscCsng}t�|j�}t�|dd��}tt�|��D]:}t�t�}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�|t�tjd��S)Nr�)rLZsk_X509_EXTENSION_pop_freerSZ	addressofZ
_original_lib)�xrBrBrC�<lambda>s�z(X509Req.get_extensions.<locals>.<lambda>)rLZX509_REQ_get_extensionsr�rSrXr�Zsk_X509_EXTENSION_numr$r�X509_EXTENSION_dupZsk_X509_EXTENSION_valuer�r�rs)rqZextsZnative_exts_objr�r
r�rBrBrC�get_extensionss	�

�zX509Req.get_extensionscCs^|jrtd��|jstd��t�t|��}|tjkr<td��t�|j	|j
|�}t|dk�dS)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 part�Key is uninitialized�No such digest methodrN)r�rar{rL�EVP_get_digestbynamer�rSrWZ
X509_REQ_signr�rzrV�rqr}�digest�
digest_obj�sign_resultrBrBrCr8"s
zX509Req.signcCs4t|t�std��t�|j|j�}|dkr0t�|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)r^r r`rLZX509_REQ_verifyr�rzr�)rqr}r�rBrBrCr9:s
zX509Req.verifyN)r>r?r@rArrr�r�rrrr�rr	rrr8r9rBrBrBrCr%|s

r%c@seZdZdZdd�Zedd��Zdd�Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Zd8d9�Z d:d;�Z!d<d=�Z"d>d?�Z#d@dA�Z$dBS)Cr&z
    An X.509 certificate.
    cCs:t��}t|tjk�t�|tj�|_t�|_	t�|_
dSrK)rLZX509_newrVrSrWrX�	X509_freer�rn�_issuer_invalidator�_subject_invalidator)rqrrBrBrCrrUs
z
X509.__init__cCs.|�|�}t�|tj�|_t�|_t�|_|SrK)	rrSrXrLrr�rnrr)r�r�certrBrBrC�_from_raw_x509_ptr]s

zX509._from_raw_x509_ptrcCs&ddlm}tt|�}t�}|||�S)z�
        Export as a ``cryptography`` certificate.

        :rtype: ``cryptography.x509.Certificate``

        .. versionadded:: 17.1.0
        r)�load_der_x509_certificate)r�r!r,rrF)rqr!r�rErBrBrCr�es
zX509.to_cryptographycCs6t|tj�std��ddlm}|�|j�}tt	|�S)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 certificaterr)
r^rZCertificater`r�r�r�r�r+r)r�Zcrypto_certr�r�rBrBrCrss
zX509.from_cryptographycCs$t|t�std��t�|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)r^r�r`rLZX509_set_versionr��rqrrBrBrCr��s

zX509.set_versioncCst�|j�S)z�
        Return the version number of the certificate.

        :return: The version number of the certificate.
        :rtype: :py:class:`int`
        )rLZX509_get_versionr�rprBrBrCr�szX509.get_versioncCsFt�t�}t�|j�|_|jtjkr*t�t�	|jtj
�|_d|_|S)z{
        Get the public key of the certificate.

        :return: The public key.
        :rtype: :py:class:`PKey`
        T)r rrL�X509_get_pubkeyr�rzrSrWr�rXryr�r|rBrBrCr�s
zX509.get_pubkeycCs2t|t�std��t�|j|j�}t|dk�dS)z�
        Set the public key of the certificate.

        :param pkey: The public key.
        :type pkey: :py:class:`PKey`

        :return: :py:data:`None`
        rr�N)r^r r`rLZX509_set_pubkeyr�rzrVrrBrBrCr�s	
zX509.set_pubkeycCspt|t�std��|jr td��|js.td��t�t|��}|t	j
krNtd��t�|j|j
|�}t|dk�dS)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)r^r r`r�rar{rLrr�rSrWZ	X509_signr�rzrV)rqr}rZevp_mdrrBrBrCr8�s

z	X509.signcCs:t�|j�}t�|j�}|tjkr*td��t�t�	|��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)
rLZX509_get0_tbs_sigalgr�r��	algorithmr�rarSrjZ
OBJ_nid2ln)rqZalgorr�rBrBrC�get_signature_algorithm�s

zX509.get_signature_algorithmcCs�t�t|��}|tjkr td��t�dtj�}t�dd�}t|�|d<t�	|j
|||�}t|dk�d�dd�t�
||d�D��S)	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`
        r�unsigned char[]zunsigned int[]r�r�:cSsg|]}t|����qSrB)r�upper)r�ZchrBrBrC�
<listcomp>s�zX509.digest.<locals>.<listcomp>)rLrr�rSrWrarTZEVP_MAX_MD_SIZErUZX509_digestr�rVr�rY)rqZdigest_namerr\r�Z
digest_resultrBrBrCr�s

���zX509.digestcCst�|j�S)z�
        Return the hash of the X509 subject.

        :return: The hash of the subject.
        :rtype: :py:class:`bytes`
        )rLZX509_subject_name_hashr�rprBrBrC�subject_name_hash	szX509.subject_name_hashcCs�t|t�std��t|�dd�}t|t�s6|�d�}t�d�}t�	||�}|dtj
krzt�t�|j
�|�}|r�t�nXt�|dtj
�}t�|d�|tj
kr�t�t�|tj�}t�|j
|�}t|dk�dS)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 integer�Nr��BIGNUM**rr�)r^�_integer_typesr`�hexr_r�rSrTrL�	BN_hex2bnrWZASN1_INTEGER_set�X509_get_serialNumberr�r��BN_to_ASN1_INTEGERr�rX�ASN1_INTEGER_freeZX509_set_serialNumberrV)rq�serial�
hex_serial�
bignum_serialZsmall_serialrd�asn1_serialrBrBrC�set_serial_numbers(	



�
zX509.set_serial_numberc	Cs�t�|j�}t�|tj�}zVt�|�}z0t�|�}t|d�}|Wt�	|�Wt�
|�St�	|�0Wt�
|�nt�
|�0dS)zx
        Return the serial number of this certificate.

        :return: The serial number.
        :rtype: int
        �N)rLr0r�ZASN1_INTEGER_to_BNrSrWZ	BN_bn2hexrjr�r�r�)rqr6r5r4Zhexstring_serialr3rBrBrC�get_serial_number:s



�
�zX509.get_serial_numbercCs.t|t�std��t�|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)r^r�r`rL�X509_getm_notAfterr��X509_gmtime_adj)rq�amountZnotAfterrBrBrC�gmtime_adj_notAfterNs
zX509.gmtime_adj_notAftercCs.t|t�std��t�|j�}t�||�dS)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``
        r:N)r^r�r`rL�X509_getm_notBeforer�r<)rqr=Z	notBeforerBrBrC�gmtime_adj_notBefore\s
zX509.gmtime_adj_notBeforecCs(t|���}tj�|d�}|tj��kS)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_notAfter�datetime�strptimeZutcnow)rqZtime_stringZ	not_afterrBrBrC�has_expirediszX509.has_expiredcCst||j��SrK)rmr�)rq�whichrBrBrC�_get_boundary_timeuszX509._get_boundary_timecCs|�tj�S)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
        )rFrLr?rprBrBrC�
get_notBeforexszX509.get_notBeforecCst||j�|�SrK)rer��rqrErcrBrBrC�_set_boundary_time�szX509._set_boundary_timecCs|�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``
        )rIrLr?�rqrcrBrBrC�
set_notBefore�szX509.set_notBeforecCs|�tj�S)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
        )rFrLr;rprBrBrCrA�szX509.get_notAftercCs|�tj|�S)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``
        )rIrLr;rJrBrBrC�set_notAfter�szX509.set_notAftercCs0t�t�}||j�|_t|jtjk�||_|SrK)r#rr�rwrVrSrWr)rqrErurBrBrC�	_get_name�s

zX509._get_namecCs0t|t�std��||j|j�}t|dk�dS)Nzname must be an X509Namer�)r^r#r`r�rwrV)rqrErurdrBrBrC�	_set_name�s
zX509._set_namecCs|�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`
        )rMrLZX509_get_issuer_namerrvrtrBrBrC�
get_issuer�szX509.get_issuercCs|�tj|�|j��dS)z�
        Set the issuer of this certificate.

        :param issuer: The issuer.
        :type issuer: :py:class:`X509Name`

        :return: ``None``
        N)rNrLZX509_set_issuer_namerrx)rqr�rBrBrC�
set_issuer�s	zX509.set_issuercCs|�tj�}|j�|�|S)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`
        )rMrL�X509_get_subject_namerrvrtrBrBrCr	�szX509.get_subjectcCs|�tj|�|j��dS)z�
        Set the subject of this certificate.

        :param subject: The subject.
        :type subject: :py:class:`X509Name`

        :return: ``None``
        N)rNrLZX509_set_subject_namerrx)rqr�rBrBrC�set_subject�s	zX509.set_subjectcCst�|j�S)z�
        Get the number of extensions on this certificate.

        :return: The number of extensions.
        :rtype: :py:class:`int`

        .. versionadded:: 0.12
        )rLZX509_get_ext_countr�rprBrBrC�get_extension_count�s	zX509.get_extension_countcCs<|D]2}t|t�std��t�|j|jd�}|st�qdS)z�
        Add extensions to the certificate.

        :param extensions: The extensions to add.
        :type extensions: An iterable of :py:class:`X509Extension` objects.
        :return: ``None``
        r
r�N)r^r$rarLZX509_add_extr�r�r�)rqrr
r�rBrBrCrs
zX509.add_extensionscCsNt�t�}t�|j|�|_|jtjkr.td��t�	|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$rrLZX509_get_extr�r�rSrW�
IndexErrorrrXr�)rq�indexr
r�rBrBrC�
get_extensions
zX509.get_extensionN)%r>r?r@rArrr�r r�rr�rrrr8r%rr*r7r9r>r@rDrFrGrIrKrArLrMrNrOrPr	rRrSrrVrBrBrBrCr&PsF

		(




r&c@sLeZdZdZejZejZej	Z
ejZ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@rArLZX509_V_FLAG_CRL_CHECKZ	CRL_CHECKZX509_V_FLAG_CRL_CHECK_ALLZ
CRL_CHECK_ALLZX509_V_FLAG_IGNORE_CRITICALZIGNORE_CRITICALZX509_V_FLAG_X509_STRICTZX509_STRICTZX509_V_FLAG_ALLOW_PROXY_CERTSZALLOW_PROXY_CERTSZX509_V_FLAG_POLICY_CHECKZPOLICY_CHECKZX509_V_FLAG_EXPLICIT_POLICYZEXPLICIT_POLICYZX509_V_FLAG_INHIBIT_MAPZINHIBIT_MAPZX509_V_FLAG_NOTIFY_POLICYZ
NOTIFY_POLICYZX509_V_FLAG_CHECK_SS_SIGNATUREZCHECK_SS_SIGNATURErBrBrBrCr'+s
r'c@sBeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
d�Z	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`.
    cCst��}t�|tj�|_dSrK)rLZX509_STORE_newrSrXZX509_STORE_free�_store�rq�storerBrBrCrrPszX509Store.__init__cCs0t|t�st��t�|j|j�}t|dk�dS)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.
        r�N)r^r&r`rLZX509_STORE_add_certrWr�rV)rqrr�rBrBrC�add_certTs
zX509Store.add_certcCstt�|j|j�dk�dS)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)rVrLZX509_STORE_add_crlrW�_crl�rq�crlrBrBrC�add_crljszX509Store.add_crlcCstt�|j|�dk�dS)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)rVrLZX509_STORE_set_flagsrW)rq�flagsrBrBrC�	set_flagszszX509Store.set_flagscCsFt��}t�|tj�}t�|t�|����t	t�
|j|�dk�dS)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)rLZX509_VERIFY_PARAM_newrSrXZX509_VERIFY_PARAM_freeZX509_VERIFY_PARAM_set_time�calendarZtimegmZ	timetuplerVZX509_STORE_set1_paramrW)rqZvfy_timeZparamrBrBrC�set_time�s�zX509Store.set_timeNcCsN|durtj}nt|�}|dur(tj}nt|�}t�|j||�}|sJt�dS)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)rSrW�_path_stringrLZX509_STORE_load_locationsrWr�)rqZcafileZcapathZload_resultrBrBrC�load_locations�s�zX509Store.load_locations)N)
r>r?r@rArrrZr^r`rbrdrBrBrBrCr(Bs
r(cs eZdZdZ�fdd�Z�ZS)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|��|�||_dSrK)r�r)rr�certificate)rq�messagerer�rBrCrr�szX509StoreContextError.__init__)r>r?r@rArrr�rBrBr�rCr)�sr)c@sVeZdZdZddd�Zedd��Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Z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�|_||_||_|�|�|_	|�
�dSrK)rLZX509_STORE_CTX_newrSrXZX509_STORE_CTX_free�
_store_ctxrW�_cert�_build_certificate_stack�_chain�_init)rqrYre�chainZ	store_ctxrBrBrCrr�szX509StoreContext.__init__cCs�dd�}|dust|�dkr"tjSt��}t|tjk�t�||�}|D]N}t|t�s^t	d��tt�
|j�dk�t�||j�dkrHt�
|j�t�qH|S)NcSs8tt�|��D]}t�||�}t�|�qt�|�dSrK)r�rL�sk_X509_num�
sk_X509_valuer�sk_X509_free)�sr�rrBrBrC�cleanupsz:X509StoreContext._build_certificate_stack.<locals>.cleanuprz+One of the elements is not an X509 instance)rUrSrWrL�sk_X509_new_nullrVrXr^r&r`ZX509_up_refr��sk_X509_pushrr�)ZcertificatesrqrrrBrBrCri	s
z)X509StoreContext._build_certificate_stackcCs.t�|j|jj|jj|j�}|dkr*t�dS)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)rLZX509_STORE_CTX_initrgrWrhr�rjr��rq�retrBrBrCrk%s
�zX509StoreContext._initcCst�|j�dS)z�
        Internally cleans up the store context.

        The store context can then be reused with a new call to :meth:`_init`.
        N)rLZX509_STORE_CTX_cleanuprgrprBrBrC�_cleanup2szX509StoreContext._cleanupc
Cs\t�|j�t�|j�tt�t�t�|j����g}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.
        )
rLZX509_STORE_CTX_get_errorrgZX509_STORE_CTX_get_error_depthr�rSrjZX509_verify_cert_error_stringZX509_STORE_CTX_get_current_certZX509_dupr&r r))rq�errorsr�rh�pycertrBrBrC�_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)rWrXrBrBrC�	set_storeTs	zX509StoreContext.set_storecCs8|��|��t�|j�}|��|dkr4|���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)rvrkrL�X509_verify_certrgryrtrBrBrC�verify_certificate_sz#X509StoreContext.verify_certificatecCs�|��|��t�|j�}|dkr4|��|���t�|j�}t|tj	k�g}t
t�|��D]2}t�||�}t|tj	k�t
�|�}|�|�q`t�|�|��|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)rvrkrLr{rgryZX509_STORE_CTX_get1_chainrVrSrWr�rmrnr&r rsro)rqruZ
cert_stackr�r�rrxrBrBrC�get_verified_chainus"

z#X509StoreContext.get_verified_chain)N)
r>r?r@rArr�staticmethodrirkrvryrzr|r}rBrBrBrCr*�s


r*cCsvt|t�r|�d�}t|�}|tkr<t�|tjtjtj�}n |t	krTt�
|tj�}ntd��|tjkrlt�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
    r��3type argument must be FILETYPE_PEM or FILETYPE_ASN1)r^r�r�r[rrLZPEM_read_bio_X509rSrWrZd2i_X509_biorar�r&r )r�rYrNrrBrBrCr+�s


r+cCsnt�}|tkrt�||j�}n<|tkr6t�||j�}n$|tkrRt�||jdd�}nt	d��t
|dk�t|�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
    r�Ctype argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXTr�)r[rrLZPEM_write_bio_X509r�rZi2d_X509_biorZ
X509_print_exrarVr])r�rrN�result_coderBrBrCr,�s
�r,cCsPt�}|tkrtj}n|tkr&tj}ntd��|||j�}|dkrHt�t	|�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
    rr�)
r[rrLZPEM_write_bio_PUBKEYrZi2d_PUBKEY_biorarzr�r])r�r}rNZ	write_bior�rBrBrCr-�s
r-c		Cst�}t|t�std��|durR|dur0td��t�t|��}|tjkrXt	d��ntj}t
||�}|tkr�t�||j
|tjd|j|j�}|��nh|tkr�t�||j
�}nP|tkr�t�|j
�tjkr�td��t�t�|j
�tj�}t�||d�}nt	d��t|dk�t|�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_TEXTr�)r[r^r r`rLZEVP_get_cipherbynamer�rSrWra�_PassphraseHelperrZPEM_write_bio_PrivateKeyrz�callback�
callback_args�raise_if_problemrZi2d_PrivateKey_biorr�r�rXr�r�Z	RSA_printrVr])	r�r}Zcipher�
passphraserNZ
cipher_obj�helperr�rrBrBrCr.�sH
�


�	
�r.c@s`eZdZdZgd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dS)r/z#
    A certificate revocation.
    )sunspecifieds
keyCompromisesCACompromisesaffiliationChangeds
supersededscessationOfOperationscertificateHoldcCst��}t�|tj�|_dSrK)rLZX509_REVOKED_newrSrX�X509_REVOKED_free�_revoked)rq�revokedrBrBrCrrCszRevoked.__init__cCsft�t��tj�}t�d�}||d<t�||�}|s<td��t�t�|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``
        r,rzbad hex stringN)
rSrXrLr�r�rTr/rar1rWr2ZX509_REVOKED_set_serialNumberr�)rqZhex_strr5Z
bignum_ptrZ	bn_resultr6rBrBrC�
set_serialGs
�zRevoked.set_serialcCs@t�}t�|j�}t|tjk�t�||�}t|dk�t|�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[rLZX509_REVOKED_get0_serialNumberr�rVrSrWZi2a_ASN1_INTEGERr])rqrNZasn1_intr�rBrBrC�
get_serial_s
zRevoked.get_serialcCs^tt�|j��D]H}t�|j|�}t�|�}t�|�tjkrt�|�t�	|j|�qZqdSrK)
r�rL�X509_REVOKED_get_ext_countr��X509_REVOKED_get_extr�r��NID_crl_reasonr�ZX509_REVOKED_delete_ext)rqr�r
r�rBrBrC�_delete_reasonqs

zRevoked._delete_reasoncCs�|dur|��n�t|t�s&td��n�|���dd�}dd�|jD��|�}t�	�}t
|tjk�t�
|tj�}t�||�}t
|tjk�|��t�|jtj|dd�}t
|dk�dS)	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� r�cSsg|]}|���qSrB)�lower)r��rrBrBrCr)�r�z&Revoked.set_reason.<locals>.<listcomp>rr�)r�r^r_r`r��replace�_crl_reasonsrUrLZASN1_ENUMERATED_newrVrSrWrXZASN1_ENUMERATED_freeZASN1_ENUMERATED_setZX509_REVOKED_add1_ext_i2dr�r�)rq�reasonZreason_codeZnew_reason_extrdr�rBrBrC�
set_reasonzs 


�zRevoked.set_reasoncCs�tt�|j��D]p}t�|j|�}t�|�}t�|�tjkrt�}t�	||dd�}|stt�
|t�|��}t|dk�t
|�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)r�rLr�r�r�r�r�r�r[r�ZM_ASN1_OCTET_STRING_printr�rVr])rqr�r
r�rNr�rBrBrC�
get_reason�s

�zRevoked.get_reasoncCs|jdd�S)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)r�rprBrBrC�all_reasons�s
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``
        )rL� X509_REVOKED_get0_revocationDater�re)rqrc�dtrBrBrC�set_rev_date�szRevoked.set_rev_datecCst�|j�}t|�S)z�
        Get the revocation timestamp.

        :return: The timestamp of the revocation, as ASN.1 TIME.
        :rtype: bytes
        )rLr�r�rm)rqr�rBrBrC�get_rev_date�szRevoked.get_rev_dateN)r>r?r@rAr�rrr�r�r�r�r�r�r�r�rBrBrBrCr//s	%r/c@s|eZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zedefdd�ZdS)r0z(
    A certificate revocation list.
    cCst��}t�|tj�|_dSrK)rLZX509_CRL_newrSrX�
X509_CRL_freer[r\rBrBrCrr�szCRL.__init__cCs&ddlm}tt|�}t�}|||�S)z�
        Export as a ``cryptography`` CRL.

        :rtype: ``cryptography.x509.CertificateRevocationList``

        .. versionadded:: 17.1.0
        r)�load_der_x509_crl)r�r�r:rrF)rqr�r�rErBrBrCr��s
zCRL.to_cryptographycCs6t|tj�std��ddlm}|�|j�}tt	|�S)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 listrr)
r^rZCertificateRevocationListr`r�r�r�r�r;r)r�Z
crypto_crlr�r�rBrBrCr�s
zCRL.from_cryptographycCsng}t�|j�}tt�|��D]>}t�||�}t�|�}t�t�}t	�
|tj�|_|�
|�q|rjt|�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)rLZX509_CRL_get_REVOKEDr[r�Zsk_X509_REVOKED_numZsk_X509_REVOKED_value�Cryptography_X509_REVOKED_dupr/rrSrXr�r�rs�tuple)rq�resultsZ
revoked_stackr�r�Zrevoked_copyZpyrevrBrBrC�get_revoked	s


zCRL.get_revokedcCs8t�|j�}t|tjk�t�|j|�}t|dk�dS)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)rLr�r�rVrSrWZX509_CRL_add0_revokedr[)rqr��copyr�rBrBrC�add_revoked	szCRL.add_revokedcCsBt�t�|j��}t|tjk�t�|tj�}t	�
t	�}||_|S)zc
        Get the CRL's issuer.

        .. versionadded:: 16.1.0

        :rtype: X509Name
        )rLr�ZX509_CRL_get_issuerr[rVrSrWrXr�r#rrw)rqZ_issuerr�rBrBrCrO.	s
zCRL.get_issuercCstt�|j|�dk�dS)z�
        Set the CRL version.

        .. versionadded:: 16.1.0

        :param int version: The version of the CRL.
        :return: ``None``
        rN)rVrLZX509_CRL_set_versionr[r"rBrBrCr�=	s	zCRL.set_versioncCst||j�|�SrK)rer[rHrBrBrCrIH	szCRL._set_boundary_timecCs|�tj|�S)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``
        )rIrLZX509_CRL_get_lastUpdaterJrBrBrC�set_lastUpdateK	s
zCRL.set_lastUpdatecCs|�tj|�S)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``
        )rIrLZX509_CRL_get_nextUpdaterJrBrBrC�set_nextUpdateZ	s
zCRL.set_nextUpdatecCs\t�|�}t|tjk�t�|jt�|j��t�	|j�t�
|j|j|�}t|dk�dS)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)rLrrVrSrW�X509_CRL_set_issuer_namer[rQr�Z
X509_CRL_sort�
X509_CRL_signrz)rqr�Z
issuer_keyrrr�rBrBrCr8i	s
�zCRL.sign�dc
Cst|t�std��t|t�s$td��t|t�s6td��|turFtd��t�|�}|tj	krbt
d��t�t���}t
|tj	k�t��}t
|tj	k�t�|d�t�|j|�t�||ddd�t�|j|�t�|jt�|j��t�|j|j|�}	|	�st�t||�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 instancer�zdigest must be providedrr��<)r^r&r`r r��_UNSPECIFIEDrLrrSrWrarQrRrVZ
ASN1_TIME_newr<ZX509_CRL_set_lastUpdater[ZX509_CRL_set_nextUpdater�rQr�r�rzr�r:)
rqrr�r�ZdaysrrrNZsometimerrBrBrC�export�	s4




�z
CRL.exportN)r>r?r@rArrr�r�rr�r�rOr�rIr�r�r8rr�r�rBrBrBrCr0�s
�r0c@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)r1cCstt�|j��S)zm
        Check if this NID_pkcs7_signed object

        :return: True if the PKCS7 is of type signed
        )�boolrLZPKCS7_type_is_signed�_pkcs7rprBrBrC�type_is_signed�	szPKCS7.type_is_signedcCstt�|j��S)zt
        Check if this NID_pkcs7_enveloped object

        :returns: True if the PKCS7 is of type enveloped
        )r�rLZPKCS7_type_is_envelopedr�rprBrBrC�type_is_enveloped�	szPKCS7.type_is_envelopedcCstt�|j��S)z�
        Check if this NID_pkcs7_signedAndEnveloped object

        :returns: True if the PKCS7 is of type signedAndEnveloped
        )r�rLZ PKCS7_type_is_signedAndEnvelopedr�rprBrBrC�type_is_signedAndEnveloped�	sz PKCS7.type_is_signedAndEnvelopedcCstt�|j��S)zi
        Check if this NID_pkcs7_data object

        :return: True if the PKCS7 is of type data
        )r�rLZPKCS7_type_is_datar�rprBrBrC�type_is_data�	szPKCS7.type_is_datacCs"t�|jj�}t�|�}t�|�S)zk
        Returns the type name of the PKCS7 structure

        :return: A string with the typename
        )rLr�r�r�r�rSrj)rqr�Zstring_typerBrBrC�
get_type_name�	s
zPKCS7.get_type_nameN)r>r?r@r�r�r�r�r�rBrBrBrCr1�	s
r1c@sbeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zddd�Z
dS)r2z
    A PKCS #12 archive.
    cCsd|_d|_d|_d|_dSrK)rzrh�_cacerts�
_friendlynamerprBrBrCrr�	szPKCS12.__init__cCs|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`
        )rhrprBrBrC�get_certificate�	szPKCS12.get_certificatecCst|t�std��||_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``
        r�N)r^r&r`rh)rqrrBrBrC�set_certificate�	s	
zPKCS12.set_certificatecCs|jS)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`
        )rzrprBrBrC�get_privatekey
szPKCS12.get_privatekeycCst|t�std��||_dS)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)r^r r`rzr|rBrBrC�set_privatekey
s	
zPKCS12.set_privatekeycCs|jdurt|j�SdS)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)r�r�rprBrBrC�get_ca_certificates
s
zPKCS12.get_ca_certificatescCs>|durd|_n*t|�}|D]}t|t�std��q||_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)r��listr^r&r`)rq�cacertsrrBrBrC�set_ca_certificates(
s

�zPKCS12.set_ca_certificatescCs2|durd|_nt|t�s(td|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))r�r^r_r`rtrBrBrC�set_friendlyname=
s	
�zPKCS12.set_friendlynamecCs|jS)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`
        )r�rprBrBrC�get_friendlynameN
szPKCS12.get_friendlynameN�r�c
Cs�td|�}|jdurtj}n0t��}t�|tj�}|jD]}t�||j	�q8|durZtj}|j
}|durntj}|jdur�tj}n|jj}|jdur�tj}n|jj	}t�
|||||tjtj||d�
}|tjkr�t�t�|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:
        r�Nr)�_text_to_bytes_and_warnr�rSrWrLrrrXrorsr�r�rzrhZ
PKCS12_createZ&NID_pbe_WithSHA1And3_Key_TripleDES_CBCr��PKCS12_freer[Zi2d_PKCS12_bior])
rqr��iterZmaciterr�r�friendlynamer}�pkcs12rNrBrBrCr�W
sH




�
z
PKCS12.export)Nr�r�)r>r?r@rArrr�r�r�r�r�r�r�r�r�rBrBrBrCr2�	s	
	
	r2c@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)r3z!
    A Netscape SPKI object.
    cCst��}t�|tj�|_dSrK)rLZNETSCAPE_SPKI_newrSrXZNETSCAPE_SPKI_free�_spki)rqZspkirBrBrCrr�
szNetscapeSPKI.__init__cCs^|jrtd��|jstd��t�t|��}|tjkr<td��t�|j	|j
|�}t|dk�dS)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)r�rar{rLrr�rSrWZNETSCAPE_SPKI_signr�rzrVrrBrBrCr8�
s

�zNetscapeSPKI.signcCs"t�|j|j�}|dkrt�dS)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)rLZNETSCAPE_SPKI_verifyr�rzr�)rqr�ZanswerrBrBrCr9�
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`
        )rLZNETSCAPE_SPKI_b64_encoder�rSrjr�)rqZencodedr�rBrBrC�
b64_encode�
s

zNetscapeSPKI.b64_encodecCsDt�t�}t�|j�|_t|jtjk�t�	|jtj
�|_d|_|S)z|
        Get the public key of this certificate.

        :return: The public key.
        :rtype: :py:class:`PKey`
        T)r rrLZNETSCAPE_SPKI_get_pubkeyr�rzrVrSrWrXryr�r|rBrBrCr�
s
zNetscapeSPKI.get_pubkeycCs t�|j|j�}t|dk�dS)zv
        Set the public key of the certificate

        :param pkey: The public key
        :return: ``None``
        r�N)rLZNETSCAPE_SPKI_set_pubkeyr�rzrVrrBrBrCr�
szNetscapeSPKI.set_pubkeyN)
r>r?r@rArrr8r9r�rrrBrBrBrCr3�
sr3c@sBeZdZd
dd�Zedd��Zedd��Zefdd	�Zd
d�Z	dS)r�FcCs4|tkr|durtd��||_||_||_g|_dS)Nz0only FILETYPE_PEM key format supports encryption)rra�_passphrase�
_more_args�	_truncate�	_problems)rqr�r�Z	more_args�truncaterBrBrCrr�
s�z_PassphraseHelper.__init__cCs@|jdurtjSt|jt�s&t|j�r4t�d|j�Std��dS)NZpem_password_cb�2Last argument must be a byte string or a callable.)	r�rSrWr^r_�callabler��_read_passphraser`rprBrBrCr�s
�z_PassphraseHelper.callbackcCs8|jdurtjSt|jt�s&t|j�r,tjStd��dS)Nr�)r�rSrWr^r_r�r`rprBrBrCr�s
�z_PassphraseHelper.callback_argscCs6|jr2zt|�Wn|y$Yn0|j�d��dSr�)r��_exception_from_error_queue�pop)rqZ
exceptionTyperBrBrCr�sz"_PassphraseHelper.raise_if_problemc
Cs�z�t|j�r.|jr"|�|||�}q4|�|�}n|j}t|t�sFtd��t|�|krn|jrf|d|�}ntd��tt|��D]}|||d�||<qzt|�WSt	y�}z|j
�|�WYd}~dSd}~00dS)NzBytes expectedz+passphrase returned by callback is too longr�r)r�r�r�r^r_rarUr�r��	Exceptionr�rs)rq�buf�sizeZrwflagZuserdatar�r��erBrBrCr�!s(

�
z"_PassphraseHelper._read_passphraseN)FF)
r>r?r@rrr�r�r�rr�r�rBrBrBrCr��
s





r�cCs�t|t�r|�d�}t|�}|tkr<t�|tjtjtj�}n |t	krTt�
|tj�}ntd��|tjkrlt�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`
    r�rT)r^r�r�r[rrLZPEM_read_bio_PUBKEYrSrWrZd2i_PUBKEY_biorar�r rrXryrzr�)r�rYrN�evp_pkeyr}rBrBrCr4;s 

�

r4cCs�t|t�r|�d�}t|�}t||�}|tkrNt�|tj	|j
|j�}|��n |t
krft�|tj	�}ntd��|tj	kr~t�t�t�}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
    r�r)r^r�r�r[r�rrLZPEM_read_bio_PrivateKeyrSrWr�r�r�rZd2i_PrivateKey_biorar�r rrXryrz)r�rYr�rNr�r�r}rBrBrCr5]s"


�


r5cCsnt�}|tkrt�||j�}n<|tkr6t�||j�}n$|tkrRt�||jdd�}nt	d��t
|dk�t|�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
    rr�)r[rrLZPEM_write_bio_X509_REQr�rZi2d_X509_REQ_biorZX509_REQ_print_exrarVr])r�r�rNr�rBrBrCr6�s	�r6cCs�t|t�r|�d�}t|�}|tkr<t�|tjtjtj�}n |t	krTt�
|tj�}ntd��t|tjk�t
�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
    r�r)r^r�r�r[rrLZPEM_read_bio_X509_REQrSrWrZd2i_X509_REQ_biorarVr%rrXr�r�)r�rYrNr�Zx509reqrBrBrCr7�s	


r7c	Cs�td|�}t�t|��}|tjkr*td��t��}t�|tj	�}t�
||�t�||t|��t�
|j�}t|dk�t�d|�}t�d�}t�||||j�}t|dk�t�||d�dd�S)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
    rZrrr&zunsigned int *r�N)r�rLrr�rSrWra�Cryptography_EVP_MD_CTX_newrX�Cryptography_EVP_MD_CTX_freeZEVP_SignInitZEVP_SignUpdaterUZ
EVP_PKEY_sizerzrVrTZ
EVP_SignFinalrY)	r}rZrr�md_ctxr�Zsignature_bufferZsignature_lengthZfinal_resultrBrBrCr8�s"



�r8cCs�td|�}t�t|��}|tjkr*td��t�|j�}t	|tjk�t�
|tj�}t��}t�
|tj
�}t�||�t�||t|��t�||t|�|�}|dkr�t�dS)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
    rZrr�N)r�rLrr�rSrWrar#r�rVrXryr�r�ZEVP_VerifyInitZEVP_VerifyUpdaterUZEVP_VerifyFinalr�)rZ	signaturerZrrr}r�Z
verify_resultrBrBrCr9�s 

�r9cCsjt�}|tkrt�||j�}n8|tkr6t�||j�}n |tkrNt�||j�}nt	d��t
|dk�t|�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
    r�r�)r[rrLZPEM_write_bio_X509_CRLr[rZi2d_X509_CRL_biorZX509_CRL_printrarVr])r�r]rNrurBrBrCr:s�r:cCs�t|t�r|�d�}t|�}|tkr<t�|tjtjtj�}n |t	krTt�
|tj�}ntd��|tjkrlt�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
    r�r)r^r�r�r[rrLZPEM_read_bio_X509_CRLrSrWrZd2i_X509_CRL_biorar�r0rrXr�r[)r�rYrNr]r�rBrBrCr;s




r;cCs�t|t�r|�d�}t|�}|tkr<t�|tjtjtj�}n |t	krTt�
|tj�}ntd��|tjkrlt�t
�t
�}t�|tj�|_|S)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
    r�r)r^r�r�r[rrLZPEM_read_bio_PKCS7rSrWrZ
d2i_PKCS7_biorar�r1rrXZ
PKCS7_freer�)r�rYrNZpkcs7Zpypkcs7rBrBrCr<<s	



r<zSPKCS#7 support in pyOpenSSL is deprecated. You should use the APIs in cryptography.cCs�td|�}t|t�r|�d�}t|�}|s0tj}t�|tj�}|tjkrNt	�t�
|tj�}t�d�}t�d�}t�d�}t�
|||||�}|s�t	�t�
|dtj�}z
t	�Wnty�Yn0|dtjkr�d}nt�t�}t�
|dtj�|_|dtjk�rd}	d}
nPt�|d�}	t�d�}t�|d|�}t�||d�dd�}
|tjk�rbd}
g}
tt�|��D]&}t�||�}t�|�}|
�|��qt|
�s�d}
t�t�}||_|	|_|
|_|
|_|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
    r�r�z
EVP_PKEY**zX509**zCryptography_STACK_OF_X509**rNzint*) r�r^r�r�r[rSrWrLZd2i_PKCS12_bior�rXr�rTZPKCS12_parserorr rryrzr&r ZX509_alias_get0rYr�rmrnrsr2rhr�r�)rYr�rNZp12r}rr�Zparse_resultZpykeyrxr�Zfriendlyname_lengthZfriendlyname_bufferZ	pycacertsr�rZpycacertr�rBrBrCr=dsj









���

r=zTPKCS#12 support in pyOpenSSL is deprecated. You should use the APIs in cryptography.sutf8only)N)NN)N)N)mrarB�base64r�	functoolsr�operatorrrrrrr	Zsixr
r-rr�rr�Zcryptographyr
rZ)cryptography.hazmat.primitives.asymmetricrrZ
OpenSSL._utilrrSrrLrr�rr�rr�rrcrr�rr�rZ_make_assert�__all__ZSSL_FILETYPE_PEMrZSSL_FILETYPE_ASN1rrr�rZEVP_PKEY_DSArZEVP_PKEY_DHZTYPE_DHZEVP_PKEY_ECZTYPE_ECr�rr�rVrFrIr[r]rerm�objectrnr r�r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r�r4r5r6r7r8r9r:r;r<Z
deprecatedr>�DeprecationWarningr=ZOpenSSL_add_all_algorithmsZSSL_load_error_stringsZ ASN1_STRING_set_default_mask_ascrBrBrBrC�<module>s� ,'

	
	)
4iIU^6
@._,6ZF"
%#$�
W�