o
    >h)7                    @  s  U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZmZ d dlmZ d dlmZmZmZ ejdkrId dlmZ nejd	k rYed
ZdwddZnd dlmZ d dlmZmZ d dlmZmZmZmZmZ d dlm Z  d dlm!Z" d dlm#Z$ d dlm%Z& d dlm'Z( d dlm)Z* d dlm+Z, g dZ-eej.ej/ej0ej1ej2f Z3eej4ej5ej6ej7ej8f Z9ee3e9f Z:ee;ede;f f Z<e(j=Z>de?d< e(j@ZAde?d < d!ZBe(jCZDde?d"< e(jEZFde?d#< e(jGZHde?d$< e(jIZJde?d%< G d&d' d'eKZLee$eLZMe*eLZNdxdyd+d,ZOdzd/d0ZPd{d4d5ZQd|d6d7ZRd}d9d:ZSG d;d< d<ZTG d=d> d>ZUG d?d@ d@ZVedAd~dCdDZWedEddGdHZXejYG dIdJ dJZZedKG dLdM dMZ[edNG dOdP dPZ\G dQdR dRZ]G dSdT dTZ^G dUdV dVZ_G dWdX dXeKZ`G dYdZ dZZadd\d]Zbdd_d`ZcddbdcZd		dddhdiZeG djdk dkZfddmdnZg	dxddodpZhddrdsZieiZjejeiekdNeldsdt ddudvZmemZnejemekdNeldvdt dS )    )annotationsN)	b16encode)IterableSequence)partial)AnyCallableUnion)      )
deprecated)r
      TmsgstrkwargsobjectreturnCallable[[_T], _T]c                 K  s   dd S )Nc                 S  s   | S N )fr   r   n/var/www/vedio/testing/chatpythonscript.ninositsolution.com/env/lib/python3.10/site-packages/OpenSSL/crypto.py<lambda>   s    zdeprecated.<locals>.<lambda>r   )r   r   r   r   r   r      s   r   )utilsx509)dsaeced448ed25519rsa)StrOrBytesPath)byte_string)exception_from_error_queue)ffi)lib)make_assert)
path_bytes)FILETYPE_ASN1FILETYPE_PEMFILETYPE_TEXTTYPE_DSATYPE_RSAX509ErrorPKeyX509ExtensionX509NameX509Req	X509StoreX509StoreContextX509StoreContextErrorX509StoreFlagsdump_certificatedump_certificate_requestdump_privatekeydump_publickeyget_elliptic_curveget_elliptic_curvesload_certificateload_certificate_requestload_privatekeyload_publickey.intr)   r(   i  r,   r+   TYPE_DHTYPE_ECc                   @  s   e Zd ZdZdS )r.   z7
    An error occurred in an `OpenSSL.crypto` API.
    N)__name__
__module____qualname____doc__r   r   r   r   r.   t   s    r.   bufferbytes | Noner   c                 C  sf   | du rt t  }t j}ntd| }t |t| }|fd	dd}t|tj	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[]bior   refr   c                 S  s
   t | S r   )_libBIO_free)rK   rL   r   r   r   free      
z_new_mem_buf.<locals>.free)rK   r   rL   r   r   r   )rM   BIO_new	BIO_s_memrN   _ffinewBIO_new_mem_buflen_openssl_assertNULLgc)rH   rK   rO   datar   r   r   _new_mem_buf~   s   	r[   rK   bytesc                 C  s.   t d}t| |}t |d |dd S )zO
    Copy the contents of an OpenSSL BIO object into a Python byte string.
    zchar**r   N)rS   rT   rM   BIO_get_mem_datarH   )rK   result_bufferbuffer_lengthr   r   r   _bio_to_string   s   
r`   boundarywhenNonec                 C  s@   t |ts	tdt| tjk t| |}|dkrtddS )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.
    zwhen must be a byte stringr   zInvalid stringN)	
isinstancer\   	TypeErrorrW   rS   rX   rM   ASN1_TIME_set_string
ValueError)ra   rb   
set_resultr   r   r   _set_asn1_time   s   
ri   c                 C  s2   t  }t|tjk t|t j}t||  |S )a  
    Behaves like _set_asn1_time but returns a new ASN1_TIME object.

    @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.
    )rM   ASN1_TIME_newrW   rS   rX   rY   ASN1_TIME_freeri   )rb   retr   r   r   _new_asn1_time   s
   
rm   	timestampc                 C  s   t d| }t|dkrdS t|tjkrt t|S t d}t	| | t
|d t jk t d|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*r   NzASN1_GENERALIZEDTIME**)rS   castrM   ASN1_STRING_lengthASN1_STRING_typeV_ASN1_GENERALIZEDTIMEstringASN1_STRING_get0_datarT   ASN1_TIME_to_generalizedtimerW   rX   ASN1_GENERALIZEDTIME_free)rn   string_timestampgeneralized_timestampstring_datastring_resultr   r   r   _get_asn1_time   s   



r|   c                   @  s*   e Zd ZdddZdddZdd	d
ZdS )_X509NameInvalidatorr   rc   c                 C  s
   g | _ d S r   )_namesselfr   r   r   __init__   rP   z_X509NameInvalidator.__init__namer1   c                 C  s   | j | d S r   )r~   appendr   r   r   r   r   add   s   z_X509NameInvalidator.addc                 C  s   | j D ]}|`qd S r   )r~   _namer   r   r   r   clear   s   
z_X509NameInvalidator.clearNr   rc   r   r1   r   rc   )rD   rE   rF   r   r   r   r   r   r   r   r}      s    

r}   c                   @  sb   e Zd ZdZdZdZdddZdd	d
ZedddZ	dddZ
dddZd ddZd ddZdS )!r/   zD
    A class representing an DSA or RSA public key or key pair.
    FTr   rc   c                 C  s"   t  }t|t j| _d| _d S )NF)rM   EVP_PKEY_newrS   rY   EVP_PKEY_free_pkey_initializedr   pkeyr   r   r   r      s   
zPKey.__init___Keyc                 C  sN   ddl m}m} | jrtt| }tt||S t	t| }tt||d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_keyload_der_public_keyN)password)
,cryptography.hazmat.primitives.serializationr   r   _only_publicr:   r(   typingrp   r   r9   )r   r   r   derr   r   r   to_cryptography_key  s   

zPKey.to_cryptography_key
crypto_keyc                 C  s   t |tjtjtjtjtjtj	t
jt
jtjtjf
stdddlm}m}m}m} t |tjtjtj	t
jtjfrCtt||j|jS ||j|j| }tt|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
        zUnsupported key typer   )EncodingNoEncryptionPrivateFormatPublicFormat)rd   r   DSAPrivateKeyDSAPublicKeyr   EllipticCurvePrivateKeyEllipticCurvePublicKeyr   Ed25519PrivateKeyEd25519PublicKeyr   Ed448PrivateKeyEd448PublicKeyr    RSAPrivateKeyRSAPublicKeyre   r   r   r   r   r   r@   r(   public_bytesDERSubjectPublicKeyInfoprivate_bytesPKCS8r?   )clsr   r   r   r   r   r   r   r   r   from_cryptography_key  sF   

zPKey.from_cryptography_keytyperA   bitsc              	   C  s4  t |ts	tdt |tstd|tkrQ|dkrtdt }t|tj	}t
|tj t }t|||tj}t|dk t| j|}t|dk nD|tkrt }t|tjk t|tj}t||tjdtjtjtj}t|dk tt|dk tt| j|dk ntdd| _dS )	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``
        ztype must be an integerzbits must be an integerr   zInvalid number of bits   zNo such key typeTN)rd   rA   re   r,   rg   rM   BN_newrS   rY   BN_freeBN_set_wordRSA_F4RSA_newRSA_generate_key_exrX   rW   EVP_PKEY_assign_RSAr   r+   DSA_newDSA_freeDSA_generate_parameters_exDSA_generate_keyEVP_PKEY_set1_DSAr.   r   )r   r   r   exponentr    resultr   resr   r   r   generate_keyU  s6   


zPKey.generate_keyboolc                 C  sd   | j rtdt|  tjkrtdt| j}t	|tj
}t|}|dkr-dS t  dS )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.
        zpublic key onlyz'Only RSA keys can currently be checked.r   TN)r   re   rM   EVP_PKEY_typer   EVP_PKEY_RSAEVP_PKEY_get1_RSAr   rS   rY   RSA_freeRSA_check_key_raise_current_error)r   r    r   r   r   r   check  s   

z
PKey.checkc                 C     t | jS )zT
        Returns the type of the key

        :return: The type of the key.
        )rM   EVP_PKEY_idr   r   r   r   r   r        z	PKey.typec                 C  r   )zh
        Returns the number of bits of the key

        :return: The number of bits of the key.
        )rM   EVP_PKEY_bitsr   r   r   r   r   r     r   z	PKey.bitsNr   )r   r   )r   r   r   r/   )r   rA   r   rA   r   rc   r   r   r   rA   )rD   rE   rF   rG   r   r   r   r   classmethodr   r   r   r   r   r   r   r   r   r/      s    


9
8
r/   c                      sn   e Zd ZdZdZd fddZedddZedddZedddZ	dddZ
d ddZd!ddZ  ZS )"_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`
    Notherr   r   r   c                   s   t |trt |S tS )z
        Implement cooperation with the right-hand side argument of ``!=``.

        Python 3 seems to have dropped this cooperation in this very narrow
        circumstance.
        )rd   r   super__ne__NotImplementedr   r   	__class__r   r   r     s   
z_EllipticCurve.__ne__r%   set[_EllipticCurve]c                   s>    tjd}td|} || t fdd|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.
        r   zEC_builtin_curve[]c                 3  s    | ]
}  |jV  qd S r   )from_nidnid).0cr   r%   r   r   	<genexpr>  s    z7_EllipticCurve._load_elliptic_curves.<locals>.<genexpr>)EC_get_builtin_curvesrS   rX   rT   set)r   r%   
num_curvesbuiltin_curvesr   r   r   _load_elliptic_curves  s   
z$_EllipticCurve._load_elliptic_curvesc                 C  s   | j du r| || _ | j S )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   r   r   r   _get_elliptic_curves  s   

z#_EllipticCurve._get_elliptic_curvesr   rA   c                 C  s   | ||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)rS   rt   
OBJ_nid2sndecode)r   r%   r   r   r   r   r     s   z_EllipticCurve.from_nidr   r   rc   c                 C  s   || _ || _|| _dS )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   r%   r   r   r   r   r   r      s   
z_EllipticCurve.__init__c                 C  s   d| j dS )Nz<Curve >r   r   r   r   r   __repr__     z_EllipticCurve.__repr__c                 C  s   | j | j}t|t j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.
        )rM   EC_KEY_new_by_curve_namer   rS   rY   EC_KEY_free)r   keyr   r   r   
_to_EC_KEY  s   z_EllipticCurve._to_EC_KEYr   r   r   r   )r%   r   r   r   )r%   r   r   rA   r   r   )r%   r   r   rA   r   r   r   rc   r   r   r   r   )rD   rE   rF   rG   r   r   r   r   r   r   r   r   r   __classcell__r   r   r   r   r     s    	

r   zSget_elliptic_curves is deprecated. You should use the APIs in cryptography instead.r   c                   C  s
   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   rM   r   r   r   r   r<     s   
r<   zRget_elliptic_curve is deprecated. You should use the APIs in cryptography instead.r   c                 C  s(   t  D ]}|j| kr|  S qtd| )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.
    zunknown curve name)r<   r   rg   )r   curver   r   r   r;   2  s
   


r;   c                      sr   e Zd ZdZd ddZd! fd
dZd"ddZd#ddZd#ddZd$ddZ	d%ddZ
d&ddZd'ddZ  ZS )(r1   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.
    r   r   rc   c                 C  s    t |j}t|t j| _dS )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_dupr   rS   rY   X509_NAME_freer   r   r   r   r   b  s   zX509Name.__init__r   valuer   c           	   	     s  | drt ||S t|turtdt|jddtt	|}|tj
kr?zt  W td ty>   Y tdw tt| jD ]%}t| j|}t|}t|}||krlt| j|}t|  nqGt|trw|d}t| j|tj|ddd}|st  d S d S )	N_z$attribute name must be string, not 'z.200'No such attributeutf-8r   )
startswithr   __setattr__r   r   re   rD   rM   OBJ_txt2nid_byte_string	NID_undefr   r.   AttributeErrorrangeX509_NAME_entry_countr   X509_NAME_get_entryX509_NAME_ENTRY_get_objectOBJ_obj2nidX509_NAME_delete_entryX509_NAME_ENTRY_freerd   encodeX509_NAME_add_entry_by_NIDMBSTRING_UTF8)	r   r   r   r   ientent_objent_nid
add_resultr   r   r   r  l  sD   








zX509Name.__setattr__
str | Nonec           	   
   C  s   t t|}|t jkr!zt  W td ty    Y tdw t | j|d}|dkr/dS t 	| j|}t 
|}td}t ||}t|dk zt|d |dd d}W t |d  |S t |d  w )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   r   Nunsigned char**r   r   )rM   r  r  r  r   r.   r  X509_NAME_get_index_by_NIDr   r  X509_NAME_ENTRY_get_datarS   rT   ASN1_STRING_to_UTF8rW   rH   r   OPENSSL_free)	r   r   r   entry_indexentryrZ   r^   data_lengthr   r   r   r   __getattr__  s0   


zX509Name.__getattr__r   r   c                 C  s"   t |tstS t| j|jdkS Nr   rd   r1   r   rM   X509_NAME_cmpr   r   r   r   r   __eq__     
zX509Name.__eq__c                 C  s"   t |tstS t| j|jdk S r  r   r   r   r   r   __lt__  r#  zX509Name.__lt__c                 C  sD   t dd}t| j|t|}t|t jk dt 	|
dS )z6
        String representation of an X509Name
        rJ   i   z<X509Name object '{}'>r   )rS   rT   rM   X509_NAME_oneliner   rV   rW   rX   formatrt   r   )r   r^   format_resultr   r   r   r     s   zX509Name.__repr__rA   c                 C  r   )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`
        )rM   X509_NAME_hashr   r   r   r   r   hash     
zX509Name.hashr\   c                 C  sN   t d}t| j|}t|dk t |d |dd }t|d  |S )z
        Return the DER encoding of this name.

        :return: The DER encoded form of this name.
        :rtype: :py:class:`bytes`
        r  r   N)rS   rT   rM   i2d_X509_NAMEr   rW   rH   r  )r   r^   encode_resultr{   r   r   r   r     s   
zX509Name.derlist[tuple[bytes, bytes]]c           	      C  s   g }t t| jD ]7}t| j|}t|}t|}t|}t|}t	
t|t|dd }|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  rM   r  r   r  r	  r  r
  r   rS   rH   ru   rq   r   rt   )	r   r   r  r  fnamefvalr   r   r   r   r   r   get_components  s   



zX509Name.get_componentsr   )r   r   r   r   r   rc   )r   r   r   r  r   r   r   r   r\   )r   r-  )rD   rE   rF   rG   r   r  r  r"  r$  r   r)  r   r0  r   r   r   r   r   r1   H  s    


'
(



r1   zZX509Extension support in pyOpenSSL is deprecated. You should use the APIs in cryptography.c                   @  s   e Zd ZU dZ		d"d#ddZed$ddZejdej	dej
diZded< d%ddZd%ddZd&ddZd'ddZd'd d!ZdS )(r0   zu
    An X.509 v3 certificate extension.

    .. deprecated:: 23.3.0
       Use cryptography's X509 APIs instead.
    N	type_namer\   criticalr   r   subjectX509 | Noneissuerr   rc   c                 C  s   t d}t|t jt jt jt jd t| |dur)t|ts%td|j	|_
|dur:t|ts6td|j	|_|r@d| }tt j|||}|t jkrQt  t |tj| _dS )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 OpenSSL textual representation of the extension's
            value.
        :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*r   Nzissuer must be an X509 instancez subject must be an X509 instances	   critical,)rS   rT   rM   X509V3_set_ctxrX   X509V3_set_ctx_nodbrd   r-   re   _x509issuer_certsubject_certX509V3_EXT_nconfr   rY   X509_EXTENSION_free
_extension)r   r2  r3  r   r4  r6  ctx	extensionr   r   r   r     s"   




zX509Extension.__init__r   c                 C  s   t t | jS r   )rM   r
  X509_EXTENSION_get_objectr>  r   r   r   r   r   \  s   
zX509Extension._nidemailDNSURIztyping.ClassVar[dict[int, str]]	_prefixesr   c              	   C  s   t dt| j}t |tj}g }tt|D ]I}t	||}z| j
|j }W n tyF   t }t|| |t|d Y qw t |jjj|jjjd d  d}||d |  qd|S )NzGENERAL_NAMES*r   :z, )rS   rp   rM   X509V3_EXT_d2ir>  rY   GENERAL_NAMES_freer  sk_GENERAL_NAME_numsk_GENERAL_NAME_valuerE  r   KeyErrorr[   GENERAL_NAME_printr   r`   r   rH   dia5rZ   lengthjoin)r   namespartsr  r   labelrK   r   r   r   r   _subjectAltNameStringh  s*   
z#X509Extension._subjectAltNameStringc                 C  sF   t j| jkr
|  S t }t || jdd}t|dk t|	dS )zF
        :return: a nice text representation of the extension
        r   r   )
rM   NID_subject_alt_namer   rT  r[   X509V3_EXT_printr>  rW   r`   r   )r   rK   print_resultr   r   r   __str__~  s   zX509Extension.__str__c                 C  r   )zk
        Returns the critical field of this X.509 extension.

        :return: The critical field.
        )rM   X509_EXTENSION_get_criticalr>  r   r   r   r   get_critical  r   zX509Extension.get_criticalc                 C  s8   t | j}t |}t |}|tjkrt|S d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
        s   UNDEF)rM   rA  r>  r
  r   rS   rX   rt   )r   objr   bufr   r   r   get_short_name  s   



zX509Extension.get_short_namec                 C  s@   t | j}td|}t |}t |}t||dd 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
        ro   N)rM   X509_EXTENSION_get_datar>  rS   rp   ru   rq   rH   )r   octet_resultr{   char_resultresult_lengthr   r   r   get_data  s
   	

zX509Extension.get_dataNN)r2  r\   r3  r   r   r\   r4  r5  r6  r5  r   rc   r   r   r   r1  )rD   rE   rF   rG   r   propertyr   rM   	GEN_EMAILGEN_DNSGEN_URIrE  __annotations__rT  rX  rZ  r]  rb  r   r   r   r   r0     s    
 E



r0   zPCSR support in pyOpenSSL is deprecated. You should use the APIs in cryptography.c                   @  s   e Zd ZdZd*ddZd+ddZed,d
dZd-ddZd.ddZ	d/ddZ
d0ddZd1ddZd2ddZd3d d!Zd4d$d%Zd5d'd(Zd)S )6r2   z
    An X.509 certificate signing requests.

    .. deprecated:: 24.2.0
       Use `cryptography.x509.CertificateSigningRequest` instead.
    r   rc   c                 C  s&   t  }t|t j| _| d d S r  )rM   X509_REQ_newrS   rY   X509_REQ_free_reqset_version)r   reqr   r   r   r     s   zX509Req.__init__x509.CertificateSigningRequestc                 C     ddl m} tt| }||S )z
        Export as a ``cryptography`` certificate signing request.

        :rtype: ``cryptography.x509.CertificateSigningRequest``

        .. versionadded:: 17.1.0
        r   )load_der_x509_csr)cryptography.x509rp  "_dump_certificate_request_internalr(   )r   rp  r   r   r   r   to_cryptography  s   
zX509Req.to_cryptography
crypto_reqc                 C  6   t |tjs
tdddlm} ||j}tt	|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   )
rd   r   CertificateSigningRequestre   r   r   r   r   "_load_certificate_request_internalr(   )r   rt  r   r   r   r   r   from_cryptography  s
   
zX509Req.from_cryptographyr   r/   c                 C  s    t | j|j}t|dk dS )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)rM   X509_REQ_set_pubkeyrk  r   rW   r   r   rh   r   r   r   
set_pubkey  s   	zX509Req.set_pubkeyc                 C  sD   t t }t| j|_t|jtjk t	|jtj
|_d|_|S )z
        Get the public key of the certificate signing request.

        :return: The public key.
        :rtype: :py:class:`PKey`
        T)r/   __new__rM   X509_REQ_get_pubkeyrk  r   rW   rS   rX   rY   r   r   r   r   r   r   
get_pubkey  s   
zX509Req.get_pubkeyversionrA   c                 C  s@   t |ts	td|dkrtdt| j|}t|dk dS )z
        Set the version subfield (RFC 2986, section 4.1) of the certificate
        request.

        :param int version: The version number.
        :return: ``None``
        zversion must be an intr   z9Invalid version. The only valid version for X509Req is 0.r   N)rd   rA   re   rg   rM   X509_REQ_set_versionrk  rW   )r   r  rh   r   r   r   rl  	  s   
zX509Req.set_versionc                 C  r   )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`
        )rM   X509_REQ_get_versionrk  r   r   r   r   get_version  s   zX509Req.get_versionr1   c                 C  s2   t t }t| j|_t|jtjk | |_	|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`
        )
r1   r}  rM   X509_REQ_get_subject_namerk  r   rW   rS   rX   _ownerr   r   r   r   get_subject$  s
   
zX509Req.get_subject
extensionsIterable[X509Extension]c                 C  s|   t jdtdd t }t|tjk t|tj	}|D ]}t
|ts'tdt||j qt| j|}t|dk dS )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``
        This API is deprecated and will be removed in a future version of pyOpenSSL. You should use pyca/cryptography's X.509 APIs instead.   
stacklevel+One of the elements is not an X509Extensionr   N)warningswarnDeprecationWarningrM   sk_X509_EXTENSION_new_nullrW   rS   rX   rY   sk_X509_EXTENSION_freerd   r0   rg   sk_X509_EXTENSION_pushr>  X509_REQ_add_extensionsrk  )r   r  stackextr  r   r   r   add_extensions:  s   

zX509Req.add_extensionslist[X509Extension]c                 C  s~   t jdtdd g }t| j}t|dd }tt	|D ]}t
t
}tt||}t|tj|_|| 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
        r  r  r  c                 S  s   t | tt jdS )Nr=  )rM   sk_X509_EXTENSION_pop_freerS   	addressof_original_lib)xr   r   r   r   r  s    z(X509Req.get_extensions.<locals>.<lambda>)r  r  r  rM   X509_REQ_get_extensionsrk  rS   rY   r  sk_X509_EXTENSION_numr0   r}  X509_EXTENSION_dupsk_X509_EXTENSION_valuer=  r>  r   )r   extsnative_exts_objr  r  r@  r   r   r   get_extensions[  s&   	


zX509Req.get_extensionsdigestr   c                 C  s^   |j rtd|jstdtt|}|tjkrtdt| j	|j
|}t|dk dS )aa  
        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:`"sha256"`.
        :type digest: :py:class:`str`
        :return: ``None``
        zKey has only public partKey is uninitializedNo such digest methodr   N)r   rg   r   rM   EVP_get_digestbynamer  rS   rX   X509_REQ_signrk  r   rW   )r   r   r  
digest_objsign_resultr   r   r   sign  s   
zX509Req.signr   c                 C  s4   t |ts	tdt| j|j}|dkrt  |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   )rd   r/   re   rM   X509_REQ_verifyrk  r   r   )r   r   r   r   r   r   verify  s   
zX509Req.verifyNr   )r   rn  )rt  rn  r   r2   r   r/   r   rc   r   r/   r  rA   r   rc   r   r   r1   r  r  r   rc   )r   r  r   r/   r  r   r   rc   )r   r/   r   r   )rD   rE   rF   rG   r   rs  r   ry  r|  r  rl  r  r  r  r  r  r  r   r   r   r   r2     s    









!
&r2   c                   @  sX  e Zd ZdZd`ddZedadd	ZdbddZedcddZddddZ	deddZ
dfddZdgddZdhddZdid!d"Zdjd$d%Zded&d'Zdkd)d*Zded+d,Zdld.d/Zdld0d1Zdmd3d4Zdnd7d8Zdod9d:Zdpd=d>Zdqd?d@ZdodAdBZdqdCdDZdrdFdGZdsdIdJZdtdKdLZdudNdOZdtdPdQZ dvdSdTZ!dedUdVZ"dwdYdZZ#dxd]d^Z$d_S )yr-   z
    An X.509 certificate.
    r   rc   c                 C  s:   t  }t|tjk t|t j| _t | _	t | _
d S r   )rM   X509_newrW   rS   rX   rY   	X509_freer9  r}   _issuer_invalidator_subject_invalidator)r   r   r   r   r   r     s
   zX509.__init__r   r   c                 C  s.   |  | }t|tj|_t |_t |_|S r   )	r}  rS   rY   rM   r  r9  r}   r  r  )r   r   certr   r   r   _from_raw_x509_ptr  s
   
zX509._from_raw_x509_ptrx509.Certificatec                 C  ro  )z
        Export as a ``cryptography`` certificate.

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

        .. versionadded:: 17.1.0
        r   )load_der_x509_certificate)rq  r  r7   r(   )r   r  r   r   r   r   rs    s   
zX509.to_cryptographycrypto_certc                 C  ru  )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
        zMust be a certificater   rv  )
rd   r   Certificatere   r   r   r   r   r=   r(   )r   r  r   r   r   r   r   ry    s
   
zX509.from_cryptographyr  rA   c                 C  s,   t |ts	tdtt| j|dk dS )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``
        zversion must be an integerr   N)rd   rA   re   rW   rM   X509_set_versionr9  )r   r  r   r   r   rl    s   

zX509.set_versionc                 C  r   )z
        Return the version number of the certificate.

        :return: The version number of the certificate.
        :rtype: :py:class:`int`
        )rM   X509_get_versionr9  r   r   r   r   r       zX509.get_versionr/   c                 C  sF   t t }t| j|_|jtjkrt  t	|jtj
|_d|_|S )z{
        Get the public key of the certificate.

        :return: The public key.
        :rtype: :py:class:`PKey`
        T)r/   r}  rM   X509_get_pubkeyr9  r   rS   rX   r   rY   r   r   r   r   r   r   r    s   
zX509.get_pubkeyr   c                 C  s2   t |ts	tdt| j|j}t|dk dS )z
        Set the public key of the certificate.

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

        :return: :py:data:`None`
        r  r   N)rd   r/   re   rM   X509_set_pubkeyr9  r   rW   r{  r   r   r   r|    s   
	zX509.set_pubkeyr  r   c                 C  sp   t |ts	td|jrtd|jstdtt|}|t	j
kr'tdt| j|j|}t|dk dS )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:`str`

        :return: :py:data:`None`
        r  zKey only has public partr  r  r   N)rd   r/   re   r   rg   r   rM   r  r  rS   rX   	X509_signr9  r   rW   )r   r   r  evp_mdr  r   r   r   r    s   

z	X509.signr\   c                 C  sZ   t | j}td}t |tjtj| t |d }|t jkr%t	d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
        zASN1_OBJECT **r   zUndefined signature algorithm)rM   X509_get0_tbs_sigalgr9  rS   rT   X509_ALGOR_get0rX   r
  r  rg   rt   
OBJ_nid2ln)r   sig_algalgr   r   r   r   get_signature_algorithm7  s   

zX509.get_signature_algorithmdigest_namec                 C  s   t t|}|tjkrtdtdt j}tdd}t||d< t 	| j
|||}t|dk ddd t||d D S )	a5  
        Return the digest of the X509 object.

        :param digest_name: The name of the digest algorithm to use.
        :type digest_name: :py:class:`str`

        :return: The digest of the object, formatted as
            :py:const:`b":"`-delimited hex pairs.
        :rtype: :py:class:`bytes`
        r  zunsigned char[]zunsigned int[]r   r      :c                 S  s   g | ]}t | qS r   )r   upper)r   chr   r   r   
<listcomp>c  s    
zX509.digest.<locals>.<listcomp>)rM   r  r  rS   rX   rg   rT   EVP_MAX_MD_SIZErV   X509_digestr9  rW   rP  rH   )r   r  r  r^   ra  digest_resultr   r   r   r  J  s   

zX509.digestc                 C  r   )z
        Return the hash of the X509 subject.

        :return: The hash of the subject.
        :rtype: :py:class:`int`
        )rM   X509_subject_name_hashr9  r   r   r   r   subject_name_hashi  r  zX509.subject_name_hashserialc                 C  s   t |ts	tdt|dd }|d}td}t||}t	|tj
k t|d tj
}t|d  t	|tj
k t|tj}t| j|}t	|dk dS )z
        Set the serial number of the certificate.

        :param serial: The new serial number.
        :type serial: :py:class:`int`

        :return: :py:data`None`
        zserial must be an integerr  Nr   zBIGNUM**r   r   )rd   rA   re   hexr  rS   rT   rM   	BN_hex2bnrW   rX   BN_to_ASN1_INTEGERr   rY   ASN1_INTEGER_freeX509_set_serialNumberr9  )r   r  
hex_serialhex_serial_bytesbignum_serialr   asn1_serialrh   r   r   r   set_serial_numberr  s   
	

zX509.set_serial_numberc              	   C  sp   t | j}t |tj}z$t |}zt|}t|d}|W t 	| W t 
| S t 	| w t 
| w )zx
        Return the serial number of this certificate.

        :return: The serial number.
        :rtype: int
           )rM   X509_get_serialNumberr9  ASN1_INTEGER_to_BNrS   rX   	BN_bn2hexrt   rA   r  r   )r   r  r  r  hexstring_serialr  r   r   r   get_serial_number  s   


zX509.get_serial_numberamountc                 C  .   t |ts	tdt| j}t|| dS )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)rd   rA   re   rM   X509_getm_notAfterr9  X509_gmtime_adj)r   r  notAfterr   r   r   gmtime_adj_notAfter  s   
zX509.gmtime_adj_notAfterc                 C  r  )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)rd   rA   re   rM   X509_getm_notBeforer9  r  )r   r  	notBeforer   r   r   gmtime_adj_notBefore  s   
zX509.gmtime_adj_notBeforer   c                 C  sT   |   }|du rtd|d}tj|d}tjj}tj|jdd}||k S )z
        Check whether the certificate has expired.

        :return: ``True`` if the certificate has expired, ``False`` otherwise.
        :rtype: bool
        NzUnable to determine notAfterr   z%Y%m%d%H%M%SZ)tzinfo)	get_notAfterrg   r   datetimestrptimetimezoneutcnowreplace)r   
time_bytestime_string	not_afterUTCutcnowr   r   r   has_expired  s   
zX509.has_expiredwhichrI   c                 C  s   t || jS r   )r|   r9  )r   r  r   r   r   _get_boundary_time  r   zX509._get_boundary_timec                 C     |  tj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
        )r   rM   r  r   r   r   r   get_notBefore     zX509.get_notBeforeCallable[..., Any]rb   c                 C  s   t || j|S r   )ri   r9  )r   r  rb   r   r   r   _set_boundary_time  s   zX509._set_boundary_timec                 C     |  tj|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``
        )r  rM   r  r   rb   r   r   r   set_notBefore     zX509.set_notBeforec                 C  r  )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
        )r   rM   r  r   r   r   r   r    r  zX509.get_notAfterc                 C  r  )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``
        )r  rM   r  r  r   r   r   set_notAfter  r	  zX509.set_notAfterr1   c                 C  s0   t t }|| j|_t|jtjk | |_|S r   )r1   r}  r9  r   rW   rS   rX   r  )r   r  r   r   r   r   	_get_name
  s
   
zX509._get_namer   c                 C  s0   t |ts	td|| j|j}t|dk d S )Nzname must be an X509Namer   )rd   r1   re   r9  r   rW   )r   r  r   rh   r   r   r   	_set_name  s   
zX509._set_namec                 C     |  tj}| 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`
        )r  rM   X509_get_issuer_namer  r   r   r   r   r   
get_issuer     zX509.get_issuerr6  c                 C     |  tj| | j  dS )z
        Set the issuer of this certificate.

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

        :return: ``None``
        N)r  rM   X509_set_issuer_namer  r   )r   r6  r   r   r   
set_issuer+     	zX509.set_issuerc                 C  r  )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`
        )r  rM   X509_get_subject_namer  r   r   r   r   r   r  7  r  zX509.get_subjectr4  c                 C  r  )z
        Set the subject of this certificate.

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

        :return: ``None``
        N)r  rM   X509_set_subject_namer  r   )r   r4  r   r   r   set_subjectG  r  zX509.set_subjectc                 C  r   )z
        Get the number of extensions on this certificate.

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

        .. versionadded:: 0.12
        )rM   X509_get_ext_countr9  r   r   r   r   get_extension_countS  s   	zX509.get_extension_countr  r  c                 C  sN   t jdtdd |D ]}t|tstdt| j|j	d}t
|dk q
dS )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  r  r  r   r   N)r  r  r  rd   r0   rg   rM   X509_add_extr9  r>  rW   )r   r  r  r  r   r   r   r  ^  s   

zX509.add_extensionsindexr0   c                 C  s^   t jdtdd tt}t| j||_|jt	j
krtdt|j}t	|tj|_|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
        r  r  r  zextension index out of bounds)r  r  r  r0   r}  rM   X509_get_extr9  r>  rS   rX   
IndexErrorr  rY   r=  )r   r  r  r@  r   r   r   get_extensionw  s   

zX509.get_extensionNr   )r   r   r   r-   )r   r  )r  r  r   r-   r  r   r  r  r  r1  )r  r   r   r\   )r  rA   r   rc   )r  rA   r   rc   r   )r  r   r   rI   )r   rI   )r  r  rb   r\   r   rc   )rb   r\   r   rc   )r  r   r   r1   )r  r   r   r1   r   rc   r  )r6  r1   r   rc   )r4  r1   r   rc   r  )r  rA   r   r0   )%rD   rE   rF   rG   r   r   r  rs  ry  rl  r  r  r|  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r
  r  r  r  r  r  r  r  r  r  r   r   r   r   r-     sH    




	





	

















r-   c                   @  s   e Zd ZU dZejZded< ejZ	ded< ej
Zded< ejZded< ejZded< ejZded< ejZded	< ejZded
< ejZded< ejZded< dS )r6   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
    rA   	CRL_CHECKCRL_CHECK_ALLIGNORE_CRITICALX509_STRICTALLOW_PROXY_CERTSPOLICY_CHECKEXPLICIT_POLICYINHIBIT_MAPCHECK_SS_SIGNATUREPARTIAL_CHAINN)rD   rE   rF   rG   rM   X509_V_FLAG_CRL_CHECKr  rh  X509_V_FLAG_CRL_CHECK_ALLr   X509_V_FLAG_IGNORE_CRITICALr!  X509_V_FLAG_X509_STRICTr"  X509_V_FLAG_ALLOW_PROXY_CERTSr#  X509_V_FLAG_POLICY_CHECKr$  X509_V_FLAG_EXPLICIT_POLICYr%  X509_V_FLAG_INHIBIT_MAPr&  X509_V_FLAG_CHECK_SS_SIGNATUREr'  X509_V_FLAG_PARTIAL_CHAINr(  r   r   r   r   r6     s   
 
r6   c                   @  sP   e Zd ZdZdddZddd	ZdddZdddZd ddZ	d!d"ddZ	dS )#r3   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`.
    r   rc   c                 C  s   t  }t|t j| _d S r   )rM   X509_STORE_newrS   rY   X509_STORE_free_storer   storer   r   r   r     s   zX509Store.__init__r  r-   c                 C  s0   t |tst t| j|j}t|dk dS )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)rd   r-   re   rM   X509_STORE_add_certr5  r9  rW   )r   r  r   r   r   r   add_cert  s   
zX509Store.add_certcrlx509.CertificateRevocationListc                 C  sv   t |tjr*ddlm} t||j}t	|t
j}t|t
jk t
|tj}ntdtt| j|dk dS )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: The certificate revocation list to add to this store.
        :type crl: ``cryptography.x509.CertificateRevocationList``
        :return: ``None`` if the certificate revocation list was added
            successfully.
        r   rv  z?CRL must be of type cryptography.x509.CertificateRevocationListN)rd   r   CertificateRevocationListr   r   r[   r   r   rM   d2i_X509_CRL_biorS   rX   rW   rY   X509_CRL_freere   X509_STORE_add_crlr5  )r   r:  r   rK   openssl_crlr   r   r   add_crl  s   zX509Store.add_crlflagsrA   c                 C  s   t t| j|dk dS )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.
        r   N)rW   rM   X509_STORE_set_flagsr5  )r   rB  r   r   r   	set_flags  s   zX509Store.set_flagsvfy_timedatetime.datetimec                 C  sF   t  }t|t j}t |t|  t	t 
| j|dk dS )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.
        r   N)rM   X509_VERIFY_PARAM_newrS   rY   X509_VERIFY_PARAM_freeX509_VERIFY_PARAM_set_timecalendartimegm	timetuplerW   X509_STORE_set1_paramr5  )r   rE  paramr   r   r   set_time  s   zX509Store.set_timeNcafileStrOrBytesPath | Nonecapathc                 C  sR   |du rt j}nt|}|du rt j}nt|}t| j||}|s't  dS dS )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)rS   rX   _path_bytesrM   X509_STORE_load_locationsr5  r   )r   rP  rR  load_resultr   r   r   load_locations&  s   #
zX509Store.load_locationsr   )r  r-   r   rc   )r:  r;  r   rc   )rB  rA   r   rc   )rE  rF  r   rc   r   )rP  rQ  rR  rQ  r   rc   )
rD   rE   rF   rG   r   r9  rA  rD  rO  rV  r   r   r   r   r3     s    




r3   c                      s"   e Zd ZdZd fd
dZ  ZS )r5   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`
    messager   errors	list[Any]certificater-   r   rc   c                   s   t  | || _|| _d S r   )r   r   rX  rZ  )r   rW  rX  rZ  r   r   r   r   c  s   
zX509StoreContextError.__init__)rW  r   rX  rY  rZ  r-   r   rc   )rD   rE   rF   rG   r   r   r   r   r   r   r5   Z  s    r5   c                   @  sb   e Zd ZdZ	ddddZed ddZed!ddZd"ddZd#ddZ	d$ddZ
d%ddZdS )&r4   a9  
    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`.

    :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`
    Nr7  r3   rZ  r-   chainSequence[X509] | Noner   rc   c                 C  s   || _ || _| || _d S r   )r5  _cert_build_certificate_stack_chain)r   r7  rZ  r[  r   r   r   r   {  s   zX509StoreContext.__init__certificatesc                 C  s   d	dd}| d u st | dkrtjS t }t|tjk t||}| D ]'}t|ts0t	dtt
|jdk t||jdkrLt|j t  q%|S )
Nsr   r   rc   c                 S  s8   t t| D ]}t| |}t| qt|  d S r   )r  rM   sk_X509_numsk_X509_valuer  sk_X509_free)ra  r  r  r   r   r   cleanup  s   z:X509StoreContext._build_certificate_stack.<locals>.cleanupr   z+One of the elements is not an X509 instance)ra  r   r   rc   )rV   rS   rX   rM   sk_X509_new_nullrW   rY   rd   r-   re   X509_up_refr9  sk_X509_pushr  r   )r`  re  r  r  r   r   r   r^    s   

z)X509StoreContext._build_certificate_stack	store_ctxr   r5   c                 C  s\   t tt| d}t| t| |g}t| }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.
        r   )rS   rt   rM   X509_verify_cert_error_stringX509_STORE_CTX_get_errorr   X509_STORE_CTX_get_error_depthX509_STORE_CTX_get_current_certX509_dupr-   r  r5   )ri  rW  rX  r9  r]  pycertr   r   r   _exception_from_context  s   	


z(X509StoreContext._exception_from_contextc                 C  sj   t  }t|tjk t|t j}t || jj| j	j
| j}t|dk t |}|dkr3| ||S )a3  
        Verifies the certificate and runs an X509_STORE_CTX containing the
        results.

        :raises X509StoreContextError: If an error occurred when validating a
          certificate in the context. Sets ``certificate`` attribute to
          indicate which certificate caused the error.
        r   r   )rM   X509_STORE_CTX_newrW   rS   rX   rY   X509_STORE_CTX_freeX509_STORE_CTX_initr5  r]  r9  r_  X509_verify_certrp  )r   ri  rl   r   r   r   _verify_certificate  s   	

z$X509StoreContext._verify_certificatec                 C  s
   || _ dS )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)r5  r6  r   r   r   	set_store  s   
	zX509StoreContext.set_storec                 C  s   |    dS )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.
        N)ru  r   r   r   r   verify_certificate  r*  z#X509StoreContext.verify_certificate
list[X509]c                 C  st   |   }t|}t|tjk g }tt|D ]}t||}t|tj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
        )ru  rM   X509_STORE_CTX_get1_chainrW   rS   rX   r  rb  rc  r-   r  r   rd  )r   ri  
cert_stackr   r  r  ro  r   r   r   get_verified_chain  s   


z#X509StoreContext.get_verified_chainr   )r7  r3   rZ  r-   r[  r\  r   rc   )r`  r\  r   rc   )ri  r   r   r5   r   )r7  r3   r   rc   r   )r   rx  )rD   rE   rF   rG   r   staticmethodr^  rp  ru  rv  rw  r{  r   r   r   r   r4   k  s    



r4   r   c                 C  sv   t |tr
|d}t|}| tkrt|tjtjtj}n| t	kr*t
|tj}ntd|tjkr6t  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)rd   r   r  r[   r)   rM   PEM_read_bio_X509rS   rX   r(   d2i_X509_biorg   r   r-   r  )r   rH   rK   r   r   r   r   r=   	  s   



r=   r  c                 C  sn   t  }| tkrt||j}n| tkrt||j}n| tkr)t||jdd}nt	dt
|dk 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[   r)   rM   PEM_write_bio_X509r9  r(   i2d_X509_bior*   X509_print_exrg   rW   r`   )r   r  rK   result_coder   r   r   r7   &  s   
r7   r   c                 C  sP   t  }| tkrtj}n| tkrtj}ntd|||j}|dkr$t  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
    r}  r   )
r[   r)   rM   PEM_write_bio_PUBKEYr(   i2d_PUBKEY_biorg   r   r   r`   )r   r   rK   	write_bior  r   r   r   r:   B  s   
r:   cipherr  
passphrasePassphraseCallableT | Nonec           	   	   C  s  t  }t|tstd|dur)|du rtdtt|}|tjkr(t	dntj}t
| |}| tkrIt||j|tjd|j|j}|  n4| tkrUt||j}n(| tkryt|jtjkrftdtt|jtj}t||d}nt	dt|dk 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
    zpkey must be a PKeyNzDif a value is given for cipher one must also be given for passphrasezInvalid cipher namer   z-Only RSA keys are supported for FILETYPE_TEXTr  )r[   rd   r/   re   rM   EVP_get_cipherbynamer  rS   rX   rg   _PassphraseHelperr)   PEM_write_bio_PrivateKeyr   callbackcallback_argsraise_if_problemr(   i2d_PrivateKey_bior*   r   r   rY   r   r   	RSA_printrW   r`   )	r   r   r  r  rK   
cipher_objhelperr  r    r   r   r   r9   [  sJ   



	r9   c                   @  sP   e Zd Z		ddddZedddZedddZefd ddZd!ddZ	dS )"r  Fr   rA   r  r  	more_argsr   truncater   rc   c                 C  s4   |t kr|d urtd|| _|| _|| _g | _d S )Nz0only FILETYPE_PEM key format supports encryption)r)   rg   _passphrase
_more_args	_truncate	_problems)r   r   r  r  r  r   r   r   r     s   
z_PassphraseHelper.__init__r   c                 C  s<   | j d u rtjS t| j tst| j rtd| jS td)Npem_password_cb2Last argument must be a byte string or a callable.)	r  rS   rX   rd   r\   callabler  _read_passphrasere   r   r   r   r   r    s   
z_PassphraseHelper.callbackc                 C  s4   | j d u rtjS t| j tst| j rtjS td)Nr  )r  rS   rX   rd   r\   r  re   r   r   r   r   r    s   
z_PassphraseHelper.callback_argsexceptionTypetype[Exception]c                 C  s6   | j rzt| W n	 |y   Y nw | j dd S r  )r  _exception_from_error_queuepop)r   r  r   r   r   r    s   z"_PassphraseHelper.raise_if_problemr\  sizerwflaguserdatac              
   C  s   zUt | jr| jr| |||}n| |}n
| jd usJ | j}t|ts*tdt||kr>| jr:|d | }ntdtt|D ]}|||d  ||< qDt|W S  t	yn } z| j
| W Y d }~dS d }~ww )NzBytes expectedz+passphrase returned by callback is too longr   r   )r  r  r  rd   r\   rg   rV   r  r  	Exceptionr  r   )r   r\  r  r  r  r   r  er   r   r   r    s.   


z"_PassphraseHelper._read_passphraseN)FF)
r   rA   r  r  r  r   r  r   r   rc   r   )r  r  r   rc   )
r\  r   r  rA   r  r   r  r   r   rA   )
rD   rE   rF   r   rd  r  r  r.   r  r  r   r   r   r   r    s    


r  str | bytesc                 C  s   t |tr
|d}t|}| tkrt|tjtjtj}n| t	kr*t
|tj}ntd|tjkr6t  tt}t|tj|_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   r}  T)rd   r   r  r[   r)   rM   PEM_read_bio_PUBKEYrS   rX   r(   d2i_PUBKEY_biorg   r   r/   r}  rY   r   r   r   )r   rH   rK   evp_pkeyr   r   r   r   r@     s    



r@   c                 C  s   t |tr
|d}t|}t| |}| tkr't|tj	|j
|j}|  n| tkr3t|tj	}ntd|tj	kr?t  tt}t|tj|_|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}  )rd   r   r  r[   r  r)   rM   PEM_read_bio_PrivateKeyrS   rX   r  r  r  r(   d2i_PrivateKey_biorg   r   r/   r}  rY   r   r   )r   rH   r  rK   r  r  r   r   r   r   r?   	  s"   





r?   rm  c                 C  sn   t  }| tkrt||j}n| tkrt||j}n| tkr)t||jdd}nt	dt
|dk t|S )av  
    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


    .. deprecated:: 24.2.0
       Use `cryptography.x509.CertificateSigningRequest` instead.
    r   r  )r[   r)   rM   PEM_write_bio_X509_REQrk  r(   i2d_X509_REQ_bior*   X509_REQ_print_exrg   rW   r`   )r   rm  rK   r  r   r   r   r8   9	  s   r8   r   c                 C  s   t |tr
|d}t|}| tkrt|tjtjtj}n| t	kr*t
|tj}ntdt|tjk tt}t|tj|_|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

    .. deprecated:: 24.2.0
       Use `cryptography.x509.load_der_x509_csr` or
       `cryptography.x509.load_pem_x509_csr` instead.
    r   r}  )rd   r   r  r[   r)   rM   PEM_read_bio_X509_REQrS   rX   r(   d2i_X509_REQ_biorg   rW   r2   r}  rY   rj  rk  )r   rH   rK   rm  x509reqr   r   r   r>   g	  s   


r>   )r   r   r   r   r   r   r   )rH   rI   r   r   )rK   r   r   r\   )ra   r   rb   r\   r   rc   )rb   r\   r   r   )rn   r   r   rI   )r   r   )r   r   r   r   )r   rA   rH   r\   r   r-   )r   rA   r  r-   r   r\   )r   rA   r   r/   r   r\   rc  )
r   rA   r   r/   r  r  r  r  r   r\   )r   rA   rH   r  r   r/   )r   rA   rH   r  r  r  r   r/   )r   rA   rm  r2   r   r\   )r   rA   rH   r\   r   r2   )o
__future__r   rJ  r  	functoolssysr   r  base64r   collections.abcr   r   r   r   r   r	   version_infor   TypeVar_Ttyping_extensionscryptographyr   r   )cryptography.hazmat.primitives.asymmetricr   r   r   r   r    OpenSSL._utilr!   r"   r  r#   r  r$   rS   r%   rM   r&   _make_assertr'   rS  __all__r   r   r   r   r   _PrivateKeyr   r   r   r   r   
_PublicKeyr   r\   PassphraseCallableTSSL_FILETYPE_PEMr)   rh  SSL_FILETYPE_ASN1r(   r*   r   r,   EVP_PKEY_DSAr+   EVP_PKEY_DHrB   EVP_PKEY_ECrC   r  r.   r   rW   r[   r`   ri   rm   r|   r}   r/   r   r<   r;   total_orderingr1   r0   r2   r-   r6   r3   r5   r4   r=   r7   r:   r9   r  r@   r?   r8   rr  rD   r  r>   rx  r   r   r   r   <module>   s    





	

 Bg C + s   m + 


E
N%
) 
 
