def createCertRequest(pkey, digest="<STR_LIT>", **name):

req = crypto.X509Req()<EOL>subj = req.get_subject()<EOL>for key, value in name.items():<EOL><INDENT>setattr(subj, key, value)<EOL><DEDENT>req.set_pubkey(pkey)<EOL>req.sign(pkey, digest)<EOL>return req<EOL>

Create a certificate request.

Arguments: pkey   - The key to associate with the request
           digest - Digestion method to use for signing, default is sha256
           **name - The name of the subject of the request, possible
                    arguments are:
                      C     - Country name
                      ST    - State or province name
                      L     - Locality name
                      O     - Organization name
                      OU    - Organizational unit name
                      CN    - Common name
                      emailAddress - E-mail address
Returns:   The certificate request in an X509Req object


def createCertificate(req, issuerCertKey, serial, validityPeriod,<EOL>digest="<STR_LIT>"):

issuerCert, issuerKey = issuerCertKey<EOL>notBefore, notAfter = validityPeriod<EOL>cert = crypto.X509()<EOL>cert.set_serial_number(serial)<EOL>cert.gmtime_adj_notBefore(notBefore)<EOL>cert.gmtime_adj_notAfter(notAfter)<EOL>cert.set_issuer(issuerCert.get_subject())<EOL>cert.set_subject(req.get_subject())<EOL>cert.set_pubkey(req.get_pubkey())<EOL>cert.sign(issuerKey, digest)<EOL>return cert<EOL>

Generate a certificate given a certificate request.

Arguments: req        - Certificate request to use
           issuerCert - The certificate of the issuer
           issuerKey  - The private key of the issuer
           serial     - Serial number for the certificate
           notBefore  - Timestamp (relative to now) when the certificate
                        starts being valid
           notAfter   - Timestamp (relative to now) when the certificate
                        stops being valid
           digest     - Digest method to use for signing, default is sha256
Returns:   The signed certificate in an X509 object


self.__dict__["<STR_LIT>"] = conn<EOL>

Connection is not yet a new-style class,
so I'm making a proxy instead of subclassing.


self.__dict__["<STR_LIT>"].shutdown()<EOL>

SimpleXMLRpcServer.doPOST calls shutdown(1),
and Connection.shutdown() doesn't take
an argument. So we just discard the argument.


c, a = self.__dict__["<STR_LIT>"].accept()<EOL>return (SSLWrapper(c), a)<EOL>

This is the other part of the shutdown() workaround.
Since servers create new sockets, we have to infect
them with our magic. :)


self.connection = self.request  <EOL>self.rfile = socket._fileobject(self.request, "<STR_LIT:rb>", self.rbufsize)<EOL>self.wfile = socket._fileobject(self.request, "<STR_LIT:wb>", self.wbufsize)<EOL>

We need to use socket._fileobject Because SSL.Connection
doesn't have a 'dup'. Not exactly sure WHY this is, but
this is backed up by comments in socket.py and SSL/connection.c


self.funcs = {}<EOL>self.logRequests = logRequests<EOL>self.instance = None<EOL>SecureTCPServer.__init__(self, addr, requestHandler)<EOL>

This is the exact same code as SimpleXMLRPCServer.__init__
except it calls SecureTCPServer.__init__ instead of plain
old TCPServer.__init__


for i in range(self.iterations):<EOL><INDENT>cert = X509()<EOL>try:<EOL><INDENT>cert.get_pubkey()<EOL><DEDENT>except Error:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

Call the method repeatedly such that it will raise an exception.


small = range(<NUM_LIT:3>)<EOL>for i in range(self.iterations):<EOL><INDENT>key = PKey()<EOL>key.generate_key(TYPE_DSA, <NUM_LIT>)<EOL>for i in small:<EOL><INDENT>cert = X509()<EOL>cert.set_pubkey(key)<EOL>for i in small:<EOL><INDENT>cert.get_pubkey()<EOL><DEDENT><DEDENT><DEDENT>

Call the method repeatedly such that it will return a PKey object.


for i in range(self.iterations * <NUM_LIT:10>):<EOL><INDENT>load_privatekey(<EOL>FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: "<STR_LIT>")<EOL><DEDENT>

Call the function with an encrypted PEM and a passphrase callback.


for i in range(self.iterations * <NUM_LIT:10>):<EOL><INDENT>try:<EOL><INDENT>load_privatekey(<EOL>FILETYPE_PEM, self.ENCRYPTED_PEM,<EOL>lambda *args: "<STR_LIT>")<EOL><DEDENT>except Error:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

Call the function with an encrypted PEM and a passphrase callback which
returns the wrong passphrase.


for i in range(self.iterations * <NUM_LIT:10>):<EOL><INDENT>try:<EOL><INDENT>load_privatekey(<EOL>FILETYPE_PEM, self.ENCRYPTED_PEM,<EOL>lambda *args: {})<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

Call the function with an encrypted PEM and a passphrase callback which
returns a non-string.


for i in range(self.iterations * <NUM_LIT:200>):<EOL><INDENT>CRL().add_revoked(Revoked())<EOL><DEDENT>

Call the add_revoked method repeatedly on an empty CRL.


crl = CRL()<EOL>for i in range(<NUM_LIT:100>):<EOL><INDENT>crl.add_revoked(Revoked())<EOL><DEDENT>for i in range(self.iterations):<EOL><INDENT>crl.get_revoked()<EOL><DEDENT>

Create a CRL object with 100 Revoked objects, then call the
get_revoked method repeatedly.


for i in range(self.iterations * <NUM_LIT:100>):<EOL><INDENT>revoked_copy = _X509_REVOKED_dup(Revoked()._revoked)<EOL>_lib.X509_REVOKED_free(revoked_copy)<EOL><DEDENT>

Copy an empty Revoked object repeatedly. The copy is not garbage
collected, therefore it needs to be manually freed.


curves = get_elliptic_curves()<EOL>if curves:<EOL><INDENT>curve = next(iter(curves))<EOL>for i in range(self.iterations * <NUM_LIT:1000>):<EOL><INDENT>curve._to_EC_KEY()<EOL><DEDENT><DEDENT>

Repeatedly create an EC_KEY* from an :py:obj:`_EllipticCurve`.  The
structure should be automatically garbage collected.


if not charp:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return native(ffi.string(charp))<EOL>

Get a native string type representing of the given CFFI ``char*`` object.

:param charp: A C-style string represented using CFFI.

:return: :class:`str`


errors = []<EOL>while True:<EOL><INDENT>error = lib.ERR_get_error()<EOL>if error == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>errors.append((<EOL>text(lib.ERR_lib_error_string(error)),<EOL>text(lib.ERR_func_error_string(error)),<EOL>text(lib.ERR_reason_error_string(error))))<EOL><DEDENT>raise exception_type(errors)<EOL>

Convert an OpenSSL library failure into a Python exception.

When a call to the native OpenSSL library fails, this is usually signalled
by the return value, and an error code is stored in an error queue
associated with the current thread. The err library provides functions to
obtain these error codes and textual error messages.


def openssl_assert(ok):<EOL><INDENT>"""<STR_LIT>"""<EOL>if ok is not True:<EOL><INDENT>exception_from_error_queue(error)<EOL><DEDENT><DEDENT>return openssl_assert<EOL>

Create an assert function that uses :func:`exception_from_error_queue` to
raise an exception wrapped by *error*.


if not isinstance(s, (binary_type, text_type)):<EOL><INDENT>raise TypeError("<STR_LIT>" % s)<EOL><DEDENT>if PY3:<EOL><INDENT>if isinstance(s, binary_type):<EOL><INDENT>return s.decode("<STR_LIT:utf-8>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(s, text_type):<EOL><INDENT>return s.encode("<STR_LIT:utf-8>")<EOL><DEDENT><DEDENT>return s<EOL>

Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.

:raise UnicodeError: The input string is not UTF-8 decodeable.

:raise TypeError: The input is neither :py:class:`bytes` nor
    :py:class:`unicode`.


if isinstance(s, binary_type):<EOL><INDENT>return s<EOL><DEDENT>elif isinstance(s, text_type):<EOL><INDENT>return s.encode(sys.getfilesystemencoding())<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>

Convert a Python string to a :py:class:`bytes` string identifying the same
path and which can be passed into an OpenSSL API accepting a filename.

:param s: An instance of :py:class:`bytes` or :py:class:`unicode`.

:return: An instance of :py:class:`bytes`.


if isinstance(obj, text_type):<EOL><INDENT>warnings.warn(<EOL>_TEXT_WARNING.format(label),<EOL>category=DeprecationWarning,<EOL>stacklevel=<NUM_LIT:3><EOL>)<EOL>return obj.encode('<STR_LIT:utf-8>')<EOL><DEDENT>return obj<EOL>

If ``obj`` is text, emit a warning that it should be bytes instead and try
to convert it to bytes automatically.

:param str label: The name of the parameter from which ``obj`` was taken
    (so a developer can easily find the source of the problem and correct
    it).

:return: If ``obj`` is the text string type, a ``bytes`` object giving the
    UTF-8 encoding of that text is returned.  Otherwise, ``obj`` itself is
    returned.


return _ffi.string(_lib.SSLeay_version(type))<EOL>

Return a string describing the version of OpenSSL in use.

:param type: One of the :const:`SSLEAY_` constants defined in this module.


def _requires_decorator(func):<EOL><INDENT>if not flag:<EOL><INDENT>@wraps(func)<EOL>def explode(*args, **kwargs):<EOL><INDENT>raise NotImplementedError(error)<EOL><DEDENT>return explode<EOL><DEDENT>else:<EOL><INDENT>return func<EOL><DEDENT><DEDENT>return _requires_decorator<EOL>

Builds a decorator that ensures that functions that rely on OpenSSL
functions that are not present in this build raise NotImplementedError,
rather than AttributeError coming out of cryptography.

:param flag: A cryptography flag that guards the functions, e.g.
    ``Cryptography_HAS_NEXTPROTONEG``.
:param error: The string to be used in the exception if the flag is false.


if self._problems:<EOL><INDENT>try:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>except Error:<EOL><INDENT>pass<EOL><DEDENT>raise self._problems.pop(<NUM_LIT:0>)<EOL><DEDENT>

Raise an exception from the OpenSSL error queue or that was previously
captured whe running a callback.


def load_verify_locations(self, cafile, capath=None):

if cafile is None:<EOL><INDENT>cafile = _ffi.NULL<EOL><DEDENT>else:<EOL><INDENT>cafile = _path_string(cafile)<EOL><DEDENT>if capath is None:<EOL><INDENT>capath = _ffi.NULL<EOL><DEDENT>else:<EOL><INDENT>capath = _path_string(capath)<EOL><DEDENT>load_result = _lib.SSL_CTX_load_verify_locations(<EOL>self._context, cafile, capath<EOL>)<EOL>if not load_result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>

Let SSL 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
*pemfile* or *capath* may be :data:`None`.

: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


def set_passwd_cb(self, callback, userdata=None):

if not callable(callback):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._passphrase_helper = self._wrap_callback(callback)<EOL>self._passphrase_callback = self._passphrase_helper.callback<EOL>_lib.SSL_CTX_set_default_passwd_cb(<EOL>self._context, self._passphrase_callback)<EOL>self._passphrase_userdata = userdata<EOL>

Set the passphrase callback.  This function will be called
when a private key with a passphrase is loaded.

:param callback: The Python callback to use.  This must accept three
    positional arguments.  First, an integer giving the maximum length
    of the passphrase it may return.  If the returned passphrase is
    longer than this, it will be truncated.  Second, a boolean value
    which will be true if the user should be prompted for the
    passphrase twice and the callback should verify that the two values
    supplied are equal. Third, the value given as the *userdata*
    parameter to :meth:`set_passwd_cb`.  The *callback* must return
    a byte string. If an error occurs, *callback* should return a false
    value (e.g. an empty string).
:param userdata: (optional) A Python object which will be given as
                 argument to the callback
:return: None


<EOL>set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)<EOL>_openssl_assert(set_result == <NUM_LIT:1>)<EOL>dir_env_var = _ffi.string(<EOL>_lib.X509_get_default_cert_dir_env()<EOL>).decode("<STR_LIT:ascii>")<EOL>file_env_var = _ffi.string(<EOL>_lib.X509_get_default_cert_file_env()<EOL>).decode("<STR_LIT:ascii>")<EOL>if not self._check_env_vars_set(dir_env_var, file_env_var):<EOL><INDENT>default_dir = _ffi.string(_lib.X509_get_default_cert_dir())<EOL>default_file = _ffi.string(_lib.X509_get_default_cert_file())<EOL>if (<EOL>default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and<EOL>default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE<EOL>):<EOL><INDENT>self._fallback_default_verify_paths(<EOL>_CERTIFICATE_FILE_LOCATIONS,<EOL>_CERTIFICATE_PATH_LOCATIONS<EOL>)<EOL><DEDENT><DEDENT>

Specify that the platform provided CA certificates are to be used for
verification purposes. This method has some caveats related to the
binary wheels that cryptography (pyOpenSSL's primary dependency) ships:

*   macOS will only load certificates using this method if the user has
    the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
    in the default location.
*   Windows will not work.
*   manylinux1 cryptography wheels will work on most common Linux
    distributions in pyOpenSSL 17.1.0 and above.  pyOpenSSL detects the
    manylinux1 wheel and attempts to load roots via a fallback path.

:return: None


def _check_env_vars_set(self, dir_env_var, file_env_var):

return (<EOL>os.environ.get(file_env_var) is not None or<EOL>os.environ.get(dir_env_var) is not None<EOL>)<EOL>

Check to see if the default cert dir/file environment vars are present.

:return: bool


def _fallback_default_verify_paths(self, file_path, dir_path):

for cafile in file_path:<EOL><INDENT>if os.path.isfile(cafile):<EOL><INDENT>self.load_verify_locations(cafile)<EOL>break<EOL><DEDENT><DEDENT>for capath in dir_path:<EOL><INDENT>if os.path.isdir(capath):<EOL><INDENT>self.load_verify_locations(None, capath)<EOL>break<EOL><DEDENT><DEDENT>

Default verify paths are based on the compiled version of OpenSSL.
However, when pyca/cryptography is compiled as a manylinux1 wheel
that compiled location can potentially be wrong. So, like Go, we
will try a predefined set of paths and attempt to load roots
from there.

:return: None


certfile = _path_string(certfile)<EOL>result = _lib.SSL_CTX_use_certificate_chain_file(<EOL>self._context, certfile<EOL>)<EOL>if not result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>

Load a certificate chain from a file.

:param certfile: The name of the certificate chain file (``bytes`` or
    ``unicode``).  Must be PEM encoded.

:return: None


def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):

certfile = _path_string(certfile)<EOL>if not isinstance(filetype, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>use_result = _lib.SSL_CTX_use_certificate_file(<EOL>self._context, certfile, filetype<EOL>)<EOL>if not use_result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>

Load a certificate from a file

:param certfile: The name of the certificate file (``bytes`` or
    ``unicode``).
:param filetype: (optional) The encoding of the file, which is either
    :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`.  The default is
    :const:`FILETYPE_PEM`.

:return: None


if not isinstance(cert, X509):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)<EOL>if not use_result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>

Load a certificate from a X509 object

:param cert: The X509 object
:return: None


if not isinstance(certobj, X509):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>copy = _lib.X509_dup(certobj._x509)<EOL>add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)<EOL>if not add_result:<EOL><INDENT>_lib.X509_free(copy)<EOL>_raise_current_error()<EOL><DEDENT>

Add certificate to chain

:param certobj: The X509 certificate object to add to the chain
:return: None


def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):

keyfile = _path_string(keyfile)<EOL>if filetype is _UNSPECIFIED:<EOL><INDENT>filetype = FILETYPE_PEM<EOL><DEDENT>elif not isinstance(filetype, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>use_result = _lib.SSL_CTX_use_PrivateKey_file(<EOL>self._context, keyfile, filetype)<EOL>if not use_result:<EOL><INDENT>self._raise_passphrase_exception()<EOL><DEDENT>

Load a private key from a file

:param keyfile: The name of the key file (``bytes`` or ``unicode``)
:param filetype: (optional) The encoding of the file, which is either
    :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`.  The default is
    :const:`FILETYPE_PEM`.

:return: None


if not isinstance(pkey, PKey):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)<EOL>if not use_result:<EOL><INDENT>self._raise_passphrase_exception()<EOL><DEDENT>

Load a private key from a PKey object

:param pkey: The PKey object
:return: None


if not _lib.SSL_CTX_check_private_key(self._context):<EOL><INDENT>_raise_current_error()<EOL><DEDENT>

Check if the private key (loaded with :meth:`use_privatekey`) matches
the certificate (loaded with :meth:`use_certificate`)

:return: :data:`None` (raises :exc:`Error` if something's wrong)


ca_list = _lib.SSL_load_client_CA_file(<EOL>_text_to_bytes_and_warn("<STR_LIT>", cafile)<EOL>)<EOL>_openssl_assert(ca_list != _ffi.NULL)<EOL>_lib.SSL_CTX_set_client_CA_list(self._context, ca_list)<EOL>

Load the trusted certificates that will be sent to the client.  Does
not actually imply any of the certificates are trusted; that must be
configured separately.

:param bytes cafile: The path to a certificates file in PEM format.
:return: None


buf = _text_to_bytes_and_warn("<STR_LIT>", buf)<EOL>_openssl_assert(<EOL>_lib.SSL_CTX_set_session_id_context(<EOL>self._context,<EOL>buf,<EOL>len(buf),<EOL>) == <NUM_LIT:1><EOL>)<EOL>

Set the session id to *buf* within which a session can be reused for
this Context object.  This is needed when doing session resumption,
because there is no way for a stored session to know which Context
object it is associated with.

:param bytes buf: The session id.

:returns: None


if not isinstance(mode, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)<EOL>

Set the behavior of the session cache used by all connections using
this Context.  The previously set mode is returned.  See
:const:`SESS_CACHE_*` for details about particular modes.

:param mode: One or more of the SESS_CACHE_* flags (combine using
    bitwise or)
:returns: The previously set caching mode.

.. versionadded:: 0.14


return _lib.SSL_CTX_get_session_cache_mode(self._context)<EOL>

Get the current session cache mode.

:returns: The currently used cache mode.

.. versionadded:: 0.14


if not isinstance(mode, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not callable(callback):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._verify_helper = _VerifyHelper(callback)<EOL>self._verify_callback = self._verify_helper.callback<EOL>_lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)<EOL>

et the verification flags for this Context object to *mode* and specify
that *callback* should be used for verification callbacks.

:param mode: The verify mode, this should be one of
    :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
    :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
    :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
    :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
:param callback: The Python callback to use.  This should take five
    arguments: A Connection object, an X509 object, and three integer
    variables, which are in turn potential error number, error depth
    and return code. *callback* should return True if verification
    passes and False otherwise.
:return: None

See SSL_CTX_set_verify(3SSL) for further details.


if not isinstance(depth, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_lib.SSL_CTX_set_verify_depth(self._context, depth)<EOL>

Set the maximum depth for the certificate chain verification that shall
be allowed for this Context object.

:param depth: An integer specifying the verify depth
:return: None


return _lib.SSL_CTX_get_verify_mode(self._context)<EOL>

Retrieve the Context object's verify mode, as set by
:meth:`set_verify`.

:return: The verify mode


return _lib.SSL_CTX_get_verify_depth(self._context)<EOL>

Retrieve the Context object's verify depth, as set by
:meth:`set_verify_depth`.

:return: The verify depth


dhfile = _path_string(dhfile)<EOL>bio = _lib.BIO_new_file(dhfile, b"<STR_LIT:r>")<EOL>if bio == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>bio = _ffi.gc(bio, _lib.BIO_free)<EOL>dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)<EOL>dh = _ffi.gc(dh, _lib.DH_free)<EOL>_lib.SSL_CTX_set_tmp_dh(self._context, dh)<EOL>

Load parameters for Ephemeral Diffie-Hellman

:param dhfile: The file to load EDH parameters from (``bytes`` or
    ``unicode``).

:return: None


_lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())<EOL>

Select a curve to use for ECDHE key exchange.

:param curve: A curve object to use as returned by either
    :meth:`OpenSSL.crypto.get_elliptic_curve` or
    :meth:`OpenSSL.crypto.get_elliptic_curves`.

:return: None


cipher_list = _text_to_bytes_and_warn("<STR_LIT>", cipher_list)<EOL>if not isinstance(cipher_list, bytes):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_openssl_assert(<EOL>_lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == <NUM_LIT:1><EOL>)<EOL>tmpconn = Connection(self, None)<EOL>if (<EOL>tmpconn.get_cipher_list() == [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>]<EOL>):<EOL><INDENT>raise Error(<EOL>[<EOL>(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>),<EOL>],<EOL>)<EOL><DEDENT>

Set the list of ciphers to be used in this context.

See the OpenSSL manual for more information (e.g.
:manpage:`ciphers(1)`).

:param bytes cipher_list: An OpenSSL cipher string.
:return: None


name_stack = _lib.sk_X509_NAME_new_null()<EOL>_openssl_assert(name_stack != _ffi.NULL)<EOL>try:<EOL><INDENT>for ca_name in certificate_authorities:<EOL><INDENT>if not isinstance(ca_name, X509Name):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (<EOL>type(ca_name).__name__,<EOL>)<EOL>)<EOL><DEDENT>copy = _lib.X509_NAME_dup(ca_name._name)<EOL>_openssl_assert(copy != _ffi.NULL)<EOL>push_result = _lib.sk_X509_NAME_push(name_stack, copy)<EOL>if not push_result:<EOL><INDENT>_lib.X509_NAME_free(copy)<EOL>_raise_current_error()<EOL><DEDENT><DEDENT><DEDENT>except Exception:<EOL><INDENT>_lib.sk_X509_NAME_free(name_stack)<EOL>raise<EOL><DEDENT>_lib.SSL_CTX_set_client_CA_list(self._context, name_stack)<EOL>

Set the list of preferred client certificate signers for this server
context.

This list of certificate authorities will be sent to the client when
the server requests a client certificate.

:param certificate_authorities: a sequence of X509Names.
:return: None

.. versionadded:: 0.10


if not isinstance(certificate_authority, X509):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>add_result = _lib.SSL_CTX_add_client_CA(<EOL>self._context, certificate_authority._x509)<EOL>_openssl_assert(add_result == <NUM_LIT:1>)<EOL>

Add the CA certificate to the list of preferred signers for this
context.

The list of certificate authorities will be sent to the client when the
server requests a client certificate.

:param certificate_authority: certificate authority's X509 certificate.
:return: None

.. versionadded:: 0.10


if not isinstance(timeout, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return _lib.SSL_CTX_set_timeout(self._context, timeout)<EOL>

Set the timeout for newly created sessions for this Context object to
*timeout*.  The default value is 300 seconds. See the OpenSSL manual
for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).

:param timeout: The timeout in (whole) seconds
:return: The previous session timeout


return _lib.SSL_CTX_get_timeout(self._context)<EOL>

Retrieve session timeout, as set by :meth:`set_timeout`. The default
is 300 seconds.

:return: The session timeout


@wraps(callback)<EOL>def wrapper(ssl, where, return_code):<EOL><INDENT>callback(Connection._reverse_mapping[ssl], where, return_code)<EOL><DEDENT>self._info_callback = _ffi.callback(<EOL>"<STR_LIT>", wrapper)<EOL>_lib.SSL_CTX_set_info_callback(self._context, self._info_callback)<EOL>

Set the information callback to *callback*. This function will be
called from time to time during SSL handshakes.

:param callback: The Python callback to use.  This should take three
    arguments: a Connection object and two integers.  The first integer
    specifies where in the SSL handshake the function was called, and
    the other the return code from a (possibly failed) internal
    function call.
:return: None


return self._app_data<EOL>

Get the application data (supplied via :meth:`set_app_data()`)

:return: The application data


self._app_data = data<EOL>

Set the application data (will be returned from get_app_data())

:param data: Any Python object
:return: None


store = _lib.SSL_CTX_get_cert_store(self._context)<EOL>if store == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>pystore = X509Store.__new__(X509Store)<EOL>pystore._store = store<EOL>return pystore<EOL>

Get the certificate store for the context.  This can be used to add
"trusted" certificates without using the
:meth:`load_verify_locations` method.

:return: A X509Store object or None if it does not have one.


if not isinstance(options, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return _lib.SSL_CTX_set_options(self._context, options)<EOL>

Add options. Options set before are not cleared!
This method should be used with the :const:`OP_*` constants.

:param options: The options to add.
:return: The new option bitmask.


if not isinstance(mode, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return _lib.SSL_CTX_set_mode(self._context, mode)<EOL>

Add modes via bitmask. Modes set before are not cleared!  This method
should be used with the :const:`MODE_*` constants.

:param mode: The mode to add.
:return: The new mode bitmask.


@wraps(callback)<EOL>def wrapper(ssl, alert, arg):<EOL><INDENT>callback(Connection._reverse_mapping[ssl])<EOL>return <NUM_LIT:0><EOL><DEDENT>self._tlsext_servername_callback = _ffi.callback(<EOL>"<STR_LIT>", wrapper)<EOL>_lib.SSL_CTX_set_tlsext_servername_callback(<EOL>self._context, self._tlsext_servername_callback)<EOL>

Specify a callback function to be called when clients specify a server
name.

:param callback: The callback function.  It will be invoked with one
    argument, the Connection instance.

.. versionadded:: 0.13


if not isinstance(profiles, bytes):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_openssl_assert(<EOL>_lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == <NUM_LIT:0><EOL>)<EOL>

Enable support for negotiating SRTP keying material.

:param bytes profiles: A colon delimited list of protection profile
    names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
:return: None


_warn_npn()<EOL>self._npn_advertise_helper = _NpnAdvertiseHelper(callback)<EOL>self._npn_advertise_callback = self._npn_advertise_helper.callback<EOL>_lib.SSL_CTX_set_next_protos_advertised_cb(<EOL>self._context, self._npn_advertise_callback, _ffi.NULL)<EOL>

Specify a callback function that will be called when offering `Next
Protocol Negotiation
<https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.

:param callback: The callback function.  It will be invoked with one
    argument, the :class:`Connection` instance.  It should return a
    list of bytestrings representing the advertised protocols, like
    ``[b'http/1.1', b'spdy/2']``.

.. versionadded:: 0.15


_warn_npn()<EOL>self._npn_select_helper = _NpnSelectHelper(callback)<EOL>self._npn_select_callback = self._npn_select_helper.callback<EOL>_lib.SSL_CTX_set_next_proto_select_cb(<EOL>self._context, self._npn_select_callback, _ffi.NULL)<EOL>

Specify a callback function that will be called when a server offers
Next Protocol Negotiation options.

:param callback: The callback function.  It will be invoked with two
    arguments: the Connection, and a list of offered protocols as
    bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``.  It should return
    one of those bytestrings, the chosen protocol.

.. versionadded:: 0.15


<EOL>protostr = b'<STR_LIT>'.join(<EOL>chain.from_iterable((int2byte(len(p)), p) for p in protos)<EOL>)<EOL>input_str = _ffi.new("<STR_LIT>", protostr)<EOL>_lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))<EOL>

Specify the protocols that the client is prepared to speak after the
TLS connection has been negotiated using Application Layer Protocol
Negotiation.

:param protos: A list of the protocols to be offered to the server.
    This list should be a Python list of bytestrings representing the
    protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.


self._alpn_select_helper = _ALPNSelectHelper(callback)<EOL>self._alpn_select_callback = self._alpn_select_helper.callback<EOL>_lib.SSL_CTX_set_alpn_select_cb(<EOL>self._context, self._alpn_select_callback, _ffi.NULL)<EOL>

Specify a callback function that will be called on the server when a
client offers protocols using ALPN.

:param callback: The callback function.  It will be invoked with two
    arguments: the Connection, and a list of offered protocols as
    bytestrings, e.g ``[b'http/1.1', b'spdy/2']``.  It should return
    one of those bytestrings, the chosen protocol.


def _set_ocsp_callback(self, helper, data):

self._ocsp_helper = helper<EOL>self._ocsp_callback = helper.callback<EOL>if data is None:<EOL><INDENT>self._ocsp_data = _ffi.NULL<EOL><DEDENT>else:<EOL><INDENT>self._ocsp_data = _ffi.new_handle(data)<EOL><DEDENT>rc = _lib.SSL_CTX_set_tlsext_status_cb(<EOL>self._context, self._ocsp_callback<EOL>)<EOL>_openssl_assert(rc == <NUM_LIT:1>)<EOL>rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)<EOL>_openssl_assert(rc == <NUM_LIT:1>)<EOL>

This internal helper does the common work for
``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
almost all of it.


def set_ocsp_server_callback(self, callback, data=None):

helper = _OCSPServerCallbackHelper(callback)<EOL>self._set_ocsp_callback(helper, data)<EOL>

Set a callback to provide OCSP data to be stapled to the TLS handshake
on the server side.

:param callback: The callback function. It will be invoked with two
    arguments: the Connection, and the optional arbitrary data you have
    provided. The callback must return a bytestring that contains the
    OCSP data to staple to the handshake. If no OCSP data is available
    for this connection, return the empty bytestring.
:param data: Some opaque data that will be passed into the callback
    function when called. This can be used to avoid needing to do
    complex data lookups or to keep track of what context is being
    used. This parameter is optional.


def set_ocsp_client_callback(self, callback, data=None):

helper = _OCSPClientCallbackHelper(callback)<EOL>self._set_ocsp_callback(helper, data)<EOL>

Set a callback to validate OCSP data stapled to the TLS handshake on
the client side.

:param callback: The callback function. It will be invoked with three
    arguments: the Connection, a bytestring containing the stapled OCSP
    assertion, and the optional arbitrary data you have provided. The
    callback must return a boolean that indicates the result of
    validating the OCSP data: ``True`` if the OCSP data is valid and
    the certificate can be trusted, or ``False`` if either the OCSP
    data is invalid or the certificate has been revoked.
:param data: Some opaque data that will be passed into the callback
    function when called. This can be used to avoid needing to do
    complex data lookups or to keep track of what context is being
    used. This parameter is optional.


def __init__(self, context, socket=None):

if not isinstance(context, Context):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>ssl = _lib.SSL_new(context._context)<EOL>self._ssl = _ffi.gc(ssl, _lib.SSL_free)<EOL>_lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)<EOL>self._context = context<EOL>self._app_data = None<EOL>self._npn_advertise_callback_args = None<EOL>self._npn_select_callback_args = None<EOL>self._alpn_select_callback_args = None<EOL>self._reverse_mapping[self._ssl] = self<EOL>if socket is None:<EOL><INDENT>self._socket = None<EOL>self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())<EOL>_openssl_assert(self._into_ssl != _ffi.NULL)<EOL>self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())<EOL>_openssl_assert(self._from_ssl != _ffi.NULL)<EOL>_lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)<EOL><DEDENT>else:<EOL><INDENT>self._into_ssl = None<EOL>self._from_ssl = None<EOL>self._socket = socket<EOL>set_result = _lib.SSL_set_fd(<EOL>self._ssl, _asFileDescriptor(self._socket))<EOL>_openssl_assert(set_result == <NUM_LIT:1>)<EOL><DEDENT>

Create a new Connection object, using the given OpenSSL.SSL.Context
instance and socket.

:param context: An SSL Context to use for this connection
:param socket: The socket to use for transport layer


if self._socket is None:<EOL><INDENT>raise AttributeError("<STR_LIT>" % (<EOL>self.__class__.__name__, name<EOL>))<EOL><DEDENT>else:<EOL><INDENT>return getattr(self._socket, name)<EOL><DEDENT>

Look up attributes on the wrapped socket object if they are not found
on the Connection object.


return self._context<EOL>

Retrieve the :class:`Context` object associated with this
:class:`Connection`.


if not isinstance(context, Context):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_lib.SSL_set_SSL_CTX(self._ssl, context._context)<EOL>self._context = context<EOL>

Switch this connection to a new session context.

:param context: A :class:`Context` instance giving the new session
    context to use.


name = _lib.SSL_get_servername(<EOL>self._ssl, _lib.TLSEXT_NAMETYPE_host_name<EOL>)<EOL>if name == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>return _ffi.string(name)<EOL>

Retrieve the servername extension value if provided in the client hello
message, or None if there wasn't one.

:return: A byte string giving the server name or :data:`None`.

.. versionadded:: 0.13


if not isinstance(name, bytes):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>elif b"<STR_LIT>" in name:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_lib.SSL_set_tlsext_host_name(self._ssl, name)<EOL>

Set the value of the servername extension to send in the client hello.

:param name: A byte string giving the name.

.. versionadded:: 0.13


return _lib.SSL_pending(self._ssl)<EOL>

Get the number of bytes that can be safely read from the SSL buffer
(**not** the underlying transport buffer).

:return: The number of bytes available in the receive buffer.


<EOL>buf = _text_to_bytes_and_warn("<STR_LIT>", buf)<EOL>if isinstance(buf, memoryview):<EOL><INDENT>buf = buf.tobytes()<EOL><DEDENT>if isinstance(buf, _buffer):<EOL><INDENT>buf = str(buf)<EOL><DEDENT>if not isinstance(buf, bytes):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if len(buf) > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>result = _lib.SSL_write(self._ssl, buf, len(buf))<EOL>self._raise_ssl_error(self._ssl, result)<EOL>return result<EOL>

Send data on the connection. NOTE: If you get one of the WantRead,
WantWrite or WantX509Lookup exceptions on this, you have to call the
method again with the SAME buffer.

:param buf: The string, buffer or memoryview to send
:param flags: (optional) Included for compatibility with the socket
              API, the value is ignored
:return: The number of bytes written


def sendall(self, buf, flags=<NUM_LIT:0>):

buf = _text_to_bytes_and_warn("<STR_LIT>", buf)<EOL>if isinstance(buf, memoryview):<EOL><INDENT>buf = buf.tobytes()<EOL><DEDENT>if isinstance(buf, _buffer):<EOL><INDENT>buf = str(buf)<EOL><DEDENT>if not isinstance(buf, bytes):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>left_to_send = len(buf)<EOL>total_sent = <NUM_LIT:0><EOL>data = _ffi.new("<STR_LIT>", buf)<EOL>while left_to_send:<EOL><INDENT>result = _lib.SSL_write(<EOL>self._ssl,<EOL>data + total_sent,<EOL>min(left_to_send, <NUM_LIT>)<EOL>)<EOL>self._raise_ssl_error(self._ssl, result)<EOL>total_sent += result<EOL>left_to_send -= result<EOL><DEDENT>

Send "all" data on the connection. This calls send() repeatedly until
all data is sent. If an error occurs, it's impossible to tell how much
data has been sent.

:param buf: The string, buffer or memoryview to send
:param flags: (optional) Included for compatibility with the socket
              API, the value is ignored
:return: The number of bytes written


buf = _no_zero_allocator("<STR_LIT>", bufsiz)<EOL>if flags is not None and flags & socket.MSG_PEEK:<EOL><INDENT>result = _lib.SSL_peek(self._ssl, buf, bufsiz)<EOL><DEDENT>else:<EOL><INDENT>result = _lib.SSL_read(self._ssl, buf, bufsiz)<EOL><DEDENT>self._raise_ssl_error(self._ssl, result)<EOL>return _ffi.buffer(buf, result)[:]<EOL>

Receive data on the connection.

:param bufsiz: The maximum number of bytes to read
:param flags: (optional) The only supported flag is ``MSG_PEEK``,
    all other flags are ignored.
:return: The string read from the Connection


def recv_into(self, buffer, nbytes=None, flags=None):

if nbytes is None:<EOL><INDENT>nbytes = len(buffer)<EOL><DEDENT>else:<EOL><INDENT>nbytes = min(nbytes, len(buffer))<EOL><DEDENT>buf = _no_zero_allocator("<STR_LIT>", nbytes)<EOL>if flags is not None and flags & socket.MSG_PEEK:<EOL><INDENT>result = _lib.SSL_peek(self._ssl, buf, nbytes)<EOL><DEDENT>else:<EOL><INDENT>result = _lib.SSL_read(self._ssl, buf, nbytes)<EOL><DEDENT>self._raise_ssl_error(self._ssl, result)<EOL>buffer[:result] = memoryview(_ffi.buffer(buf, result))<EOL>return result<EOL>

Receive data on the connection and copy it directly into the provided
buffer, rather than creating a new string.

:param buffer: The buffer to copy into.
:param nbytes: (optional) The maximum number of bytes to read into the
    buffer. If not present, defaults to the size of the buffer. If
    larger than the size of the buffer, is reduced to the size of the
    buffer.
:param flags: (optional) The only supported flag is ``MSG_PEEK``,
    all other flags are ignored.
:return: The number of bytes read into the buffer.


if self._from_ssl is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(bufsiz, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>buf = _no_zero_allocator("<STR_LIT>", bufsiz)<EOL>result = _lib.BIO_read(self._from_ssl, buf, bufsiz)<EOL>if result <= <NUM_LIT:0>:<EOL><INDENT>self._handle_bio_errors(self._from_ssl, result)<EOL><DEDENT>return _ffi.buffer(buf, result)[:]<EOL>

If the Connection was created with a memory BIO, this method can be
used to read bytes from the write end of that memory BIO.  Many
Connection methods will add bytes which must be read in this manner or
the buffer will eventually fill up and the Connection will be able to
take no further actions.

:param bufsiz: The maximum number of bytes to read
:return: The string read.


buf = _text_to_bytes_and_warn("<STR_LIT>", buf)<EOL>if self._into_ssl is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>result = _lib.BIO_write(self._into_ssl, buf, len(buf))<EOL>if result <= <NUM_LIT:0>:<EOL><INDENT>self._handle_bio_errors(self._into_ssl, result)<EOL><DEDENT>return result<EOL>

If the Connection was created with a memory BIO, this method can be
used to add bytes to the read end of that memory BIO.  The Connection
can then read the bytes (for example, in response to a call to
:meth:`recv`).

:param buf: The string to put into the memory BIO.
:return: The number of bytes written


if not self.renegotiate_pending():<EOL><INDENT>_openssl_assert(_lib.SSL_renegotiate(self._ssl) == <NUM_LIT:1>)<EOL>return True<EOL><DEDENT>return False<EOL>

Renegotiate the session.

:return: True if the renegotiation can be started, False otherwise
:rtype: bool


result = _lib.SSL_do_handshake(self._ssl)<EOL>self._raise_ssl_error(self._ssl, result)<EOL>

Perform an SSL handshake (usually called after :meth:`renegotiate` or
one of :meth:`set_accept_state` or :meth:`set_accept_state`). This can
raise the same exceptions as :meth:`send` and :meth:`recv`.

:return: None.


return _lib.SSL_renegotiate_pending(self._ssl) == <NUM_LIT:1><EOL>

Check if there's a renegotiation in progress, it will return False once
a renegotiation is finished.

:return: Whether there's a renegotiation in progress
:rtype: bool


return _lib.SSL_total_renegotiations(self._ssl)<EOL>

Find out the total number of renegotiations.

:return: The number of renegotiations.
:rtype: int


_lib.SSL_set_connect_state(self._ssl)<EOL>return self._socket.connect(addr)<EOL>

Call the :meth:`connect` method of the underlying socket and set up SSL
on the socket, using the :class:`Context` object supplied to this
:class:`Connection` object at creation.

:param addr: A remote address
:return: What the socket's connect method returns


connect_ex = self._socket.connect_ex<EOL>self.set_connect_state()<EOL>return connect_ex(addr)<EOL>

Call the :meth:`connect_ex` method of the underlying socket and set up
SSL on the socket, using the Context object supplied to this Connection
object at creation. Note that if the :meth:`connect_ex` method of the
socket doesn't return 0, SSL won't be initialized.

:param addr: A remove address
:return: What the socket's connect_ex method returns


client, addr = self._socket.accept()<EOL>conn = Connection(self._context, client)<EOL>conn.set_accept_state()<EOL>return (conn, addr)<EOL>

Call the :meth:`accept` method of the underlying socket and set up SSL
on the returned socket, using the Context object supplied to this
:class:`Connection` object at creation.

:return: A *(conn, addr)* pair where *conn* is the new
    :class:`Connection` object created, and *address* is as returned by
    the socket's :meth:`accept`.


if self._from_ssl is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_lib.BIO_set_mem_eof_return(self._into_ssl, <NUM_LIT:0>)<EOL>

If the Connection was created with a memory BIO, this method can be
used to indicate that *end of file* has been reached on the read end of
that memory BIO.

:return: None


result = _lib.SSL_shutdown(self._ssl)<EOL>if result < <NUM_LIT:0>:<EOL><INDENT>self._raise_ssl_error(self._ssl, result)<EOL><DEDENT>elif result > <NUM_LIT:0>:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Send the shutdown message to the Connection.

:return: True if the shutdown completed successfully (i.e. both sides
         have sent closure alerts), False otherwise (in which case you
         call :meth:`recv` or :meth:`send` when the connection becomes
         readable/writeable).


ciphers = []<EOL>for i in count():<EOL><INDENT>result = _lib.SSL_get_cipher_list(self._ssl, i)<EOL>if result == _ffi.NULL:<EOL><INDENT>break<EOL><DEDENT>ciphers.append(_native(_ffi.string(result)))<EOL><DEDENT>return ciphers<EOL>

Retrieve the list of ciphers used by the Connection object.

:return: A list of native cipher strings.


ca_names = _lib.SSL_get_client_CA_list(self._ssl)<EOL>if ca_names == _ffi.NULL:<EOL><INDENT>return []<EOL><DEDENT>result = []<EOL>for i in range(_lib.sk_X509_NAME_num(ca_names)):<EOL><INDENT>name = _lib.sk_X509_NAME_value(ca_names, i)<EOL>copy = _lib.X509_NAME_dup(name)<EOL>_openssl_assert(copy != _ffi.NULL)<EOL>pyname = X509Name.__new__(X509Name)<EOL>pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)<EOL>result.append(pyname)<EOL><DEDENT>return result<EOL>

Get CAs whose certificates are suggested for client authentication.

:return: If this is a server connection, the list of certificate
    authorities that will be sent or has been sent to the client, as
    controlled by this :class:`Connection`'s :class:`Context`.

    If this is a client connection, the list will be empty until the
    connection with the server is established.

.. versionadded:: 0.10


raise NotImplementedError(<EOL>"<STR_LIT>")<EOL>

The makefile() method is not implemented, since there is no dup
semantics for SSL connections

:raise: NotImplementedError


return self._app_data<EOL>

Retrieve application data as set by :meth:`set_app_data`.

:return: The application data


self._app_data = data<EOL>

Set application data

:param data: The application data
:return: None


return _lib.SSL_get_shutdown(self._ssl)<EOL>

Get the shutdown state of the Connection.

:return: The shutdown state, a bitvector of SENT_SHUTDOWN,
    RECEIVED_SHUTDOWN.


if not isinstance(state, integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_lib.SSL_set_shutdown(self._ssl, state)<EOL>

Set the shutdown state of the Connection.

:param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
:return: None


return _ffi.string(_lib.SSL_state_string_long(self._ssl))<EOL>

Retrieve a verbose string detailing the state of the Connection.

:return: A string representing the state
:rtype: bytes


session = _lib.SSL_get_session(self._ssl)<EOL>if session == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, <NUM_LIT:0>)<EOL>assert length > <NUM_LIT:0><EOL>outp = _no_zero_allocator("<STR_LIT>", length)<EOL>_lib.SSL_get_server_random(self._ssl, outp, length)<EOL>return _ffi.buffer(outp, length)[:]<EOL>

Retrieve the random value used with the server hello message.

:return: A string representing the state


session = _lib.SSL_get_session(self._ssl)<EOL>if session == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, <NUM_LIT:0>)<EOL>assert length > <NUM_LIT:0><EOL>outp = _no_zero_allocator("<STR_LIT>", length)<EOL>_lib.SSL_get_client_random(self._ssl, outp, length)<EOL>return _ffi.buffer(outp, length)[:]<EOL>

Retrieve the random value used with the client hello message.

:return: A string representing the state


session = _lib.SSL_get_session(self._ssl)<EOL>if session == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, <NUM_LIT:0>)<EOL>assert length > <NUM_LIT:0><EOL>outp = _no_zero_allocator("<STR_LIT>", length)<EOL>_lib.SSL_SESSION_get_master_key(session, outp, length)<EOL>return _ffi.buffer(outp, length)[:]<EOL>

Retrieve the value of the master key for this session.

:return: A string representing the state


def export_keying_material(self, label, olen, context=None):

outp = _no_zero_allocator("<STR_LIT>", olen)<EOL>context_buf = _ffi.NULL<EOL>context_len = <NUM_LIT:0><EOL>use_context = <NUM_LIT:0><EOL>if context is not None:<EOL><INDENT>context_buf = context<EOL>context_len = len(context)<EOL>use_context = <NUM_LIT:1><EOL><DEDENT>success = _lib.SSL_export_keying_material(self._ssl, outp, olen,<EOL>label, len(label),<EOL>context_buf, context_len,<EOL>use_context)<EOL>_openssl_assert(success == <NUM_LIT:1>)<EOL>return _ffi.buffer(outp, olen)[:]<EOL>

Obtain keying material for application use.

:param: label - a disambiguating label string as described in RFC 5705
:param: olen - the length of the exported key material in bytes
:param: context - a per-association context value
:return: the exported key material bytes or None


def sock_shutdown(self, *args, **kwargs):

return self._socket.shutdown(*args, **kwargs)<EOL>

Call the :meth:`shutdown` method of the underlying socket.
See :manpage:`shutdown(2)`.

:return: What the socket's shutdown() method returns


cert = _lib.SSL_get_certificate(self._ssl)<EOL>if cert != _ffi.NULL:<EOL><INDENT>_lib.X509_up_ref(cert)<EOL>return X509._from_raw_x509_ptr(cert)<EOL><DEDENT>return None<EOL>

Retrieve the local certificate (if any)

:return: The local certificate


cert = _lib.SSL_get_peer_certificate(self._ssl)<EOL>if cert != _ffi.NULL:<EOL><INDENT>return X509._from_raw_x509_ptr(cert)<EOL><DEDENT>return None<EOL>

Retrieve the other side's certificate (if any)

:return: The peer's certificate


cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)<EOL>if cert_stack == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>result = []<EOL>for i in range(_lib.sk_X509_num(cert_stack)):<EOL><INDENT>cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))<EOL>pycert = X509._from_raw_x509_ptr(cert)<EOL>result.append(pycert)<EOL><DEDENT>return result<EOL>

Retrieve the other side's certificate (if any)

:return: A list of X509 instances giving the peer's certificate chain,
         or None if it does not have one.


return _lib.SSL_want_read(self._ssl)<EOL>

Checks if more data has to be read from the transport layer to complete
an operation.

:return: True iff more data has to be read


return _lib.SSL_want_write(self._ssl)<EOL>

Checks if there is data to write to the transport layer to complete an
operation.

:return: True iff there is data to write


_lib.SSL_set_accept_state(self._ssl)<EOL>

Set the connection to work in server mode. The handshake will be
handled automatically by read/write.

:return: None


_lib.SSL_set_connect_state(self._ssl)<EOL>

Set the connection to work in client mode. The handshake will be
handled automatically by read/write.

:return: None


session = _lib.SSL_get1_session(self._ssl)<EOL>if session == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>pysession = Session.__new__(Session)<EOL>pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)<EOL>return pysession<EOL>

Returns the Session currently used.

:return: An instance of :class:`OpenSSL.SSL.Session` or
    :obj:`None` if no session exists.

.. versionadded:: 0.14


if not isinstance(session, Session):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>result = _lib.SSL_set_session(self._ssl, session._session)<EOL>if not result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>

Set the session to be used when the TLS/SSL connection is established.

:param session: A Session instance representing the session to use.
:returns: None

.. versionadded:: 0.14


<EOL>empty = _ffi.new("<STR_LIT>", <NUM_LIT:0>)<EOL>size = function(self._ssl, empty, <NUM_LIT:0>)<EOL>if size == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>buf = _no_zero_allocator("<STR_LIT>", size)<EOL>function(self._ssl, buf, size)<EOL>return _ffi.buffer(buf, size)[:]<EOL>

Helper to implement :meth:`get_finished` and
:meth:`get_peer_finished`.

:param function: Either :data:`SSL_get_finished`: or
    :data:`SSL_get_peer_finished`.

:return: :data:`None` if the desired message has not yet been
    received, otherwise the contents of the message.
:rtype: :class:`bytes` or :class:`NoneType`


return self._get_finished_message(_lib.SSL_get_finished)<EOL>

Obtain the latest TLS Finished message that we sent.

:return: The contents of the message or :obj:`None` if the TLS
    handshake has not yet completed.
:rtype: :class:`bytes` or :class:`NoneType`

.. versionadded:: 0.15


return self._get_finished_message(_lib.SSL_get_peer_finished)<EOL>

Obtain the latest TLS Finished message that we received from the peer.

:return: The contents of the message or :obj:`None` if the TLS
    handshake has not yet completed.
:rtype: :class:`bytes` or :class:`NoneType`

.. versionadded:: 0.15


cipher = _lib.SSL_get_current_cipher(self._ssl)<EOL>if cipher == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))<EOL>return name.decode("<STR_LIT:utf-8>")<EOL><DEDENT>

Obtain the name of the currently used cipher.

:returns: The name of the currently used cipher or :obj:`None`
    if no connection has been established.
:rtype: :class:`unicode` or :class:`NoneType`

.. versionadded:: 0.15


cipher = _lib.SSL_get_current_cipher(self._ssl)<EOL>if cipher == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)<EOL><DEDENT>

Obtain the number of secret bits of the currently used cipher.

:returns: The number of secret bits of the currently used cipher
    or :obj:`None` if no connection has been established.
:rtype: :class:`int` or :class:`NoneType`

.. versionadded:: 0.15


cipher = _lib.SSL_get_current_cipher(self._ssl)<EOL>if cipher == _ffi.NULL:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))<EOL>return version.decode("<STR_LIT:utf-8>")<EOL><DEDENT>

Obtain the protocol version of the currently used cipher.

:returns: The protocol name of the currently used cipher
    or :obj:`None` if no connection has been established.
:rtype: :class:`unicode` or :class:`NoneType`

.. versionadded:: 0.15


version = _ffi.string(_lib.SSL_get_version(self._ssl))<EOL>return version.decode("<STR_LIT:utf-8>")<EOL>

Retrieve the protocol version of the current connection.

:returns: The TLS version of the current connection, for example
    the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
    for connections that were not successfully established.
:rtype: :class:`unicode`


version = _lib.SSL_version(self._ssl)<EOL>return version<EOL>

Retrieve the SSL or TLS protocol version of the current connection.

:returns: The TLS version of the current connection.  For example,
    it will return ``0x769`` for connections made over TLS version 1.
:rtype: :class:`int`


_warn_npn()<EOL>data = _ffi.new("<STR_LIT>")<EOL>data_len = _ffi.new("<STR_LIT>")<EOL>_lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)<EOL>return _ffi.buffer(data[<NUM_LIT:0>], data_len[<NUM_LIT:0>])[:]<EOL>

Get the protocol that was negotiated by NPN.

:returns: A bytestring of the protocol name.  If no protocol has been
    negotiated yet, returns an empty string.

.. versionadded:: 0.15


<EOL>protostr = b'<STR_LIT>'.join(<EOL>chain.from_iterable((int2byte(len(p)), p) for p in protos)<EOL>)<EOL>input_str = _ffi.new("<STR_LIT>", protostr)<EOL>_lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))<EOL>

Specify the client's ALPN protocol list.

These protocols are offered to the server during protocol negotiation.

:param protos: A list of the protocols to be offered to the server.
    This list should be a Python list of bytestrings representing the
    protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.


data = _ffi.new("<STR_LIT>")<EOL>data_len = _ffi.new("<STR_LIT>")<EOL>_lib.SSL_get0_alpn_selected(self._ssl, data, data_len)<EOL>if not data_len:<EOL><INDENT>return b'<STR_LIT>'<EOL><DEDENT>return _ffi.buffer(data[<NUM_LIT:0>], data_len[<NUM_LIT:0>])[:]<EOL>

Get the protocol that was negotiated by ALPN.

:returns: A bytestring of the protocol name.  If no protocol has been
    negotiated yet, returns an empty string.


rc = _lib.SSL_set_tlsext_status_type(<EOL>self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp<EOL>)<EOL>_openssl_assert(rc == <NUM_LIT:1>)<EOL>

Called to request that the server sends stapled OCSP data, if
available. If this is not called on the client side then the server
will not send OCSP data. Should be used in conjunction with
:meth:`Context.set_ocsp_client_callback`.


from cryptography.hazmat.backends.openssl.backend import backend<EOL>return backend<EOL>

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.


if buffer is None:<EOL><INDENT>bio = _lib.BIO_new(_lib.BIO_s_mem())<EOL>free = _lib.BIO_free<EOL><DEDENT>else:<EOL><INDENT>data = _ffi.new("<STR_LIT>", buffer)<EOL>bio = _lib.BIO_new_mem_buf(data, len(buffer))<EOL>def free(bio, ref=data):<EOL><INDENT>return _lib.BIO_free(bio)<EOL><DEDENT><DEDENT>_openssl_assert(bio != _ffi.NULL)<EOL>bio = _ffi.gc(bio, free)<EOL>return bio<EOL>

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.


result_buffer = _ffi.new('<STR_LIT>')<EOL>buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)<EOL>return _ffi.buffer(result_buffer[<NUM_LIT:0>], buffer_length)[:]<EOL>

Copy the contents of an OpenSSL BIO object into a Python byte string.


if not isinstance(when, bytes):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>set_result = _lib.ASN1_TIME_set_string(boundary, when)<EOL>if set_result == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

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.


string_timestamp = _ffi.cast('<STR_LIT>', timestamp)<EOL>if _lib.ASN1_STRING_length(string_timestamp) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>elif (<EOL>_lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME<EOL>):<EOL><INDENT>return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))<EOL><DEDENT>else:<EOL><INDENT>generalized_timestamp = _ffi.new("<STR_LIT>")<EOL>_lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)<EOL>if generalized_timestamp[<NUM_LIT:0>] == _ffi.NULL:<EOL><INDENT>_untested_error("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>string_timestamp = _ffi.cast(<EOL>"<STR_LIT>", generalized_timestamp[<NUM_LIT:0>])<EOL>string_data = _lib.ASN1_STRING_data(string_timestamp)<EOL>string_result = _ffi.string(string_data)<EOL>_lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[<NUM_LIT:0>])<EOL>return string_result<EOL><DEDENT><DEDENT>

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.


return _EllipticCurve._get_elliptic_curves(_lib)<EOL>

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.


for curve in get_elliptic_curves():<EOL><INDENT>if curve.name == name:<EOL><INDENT>return curve<EOL><DEDENT><DEDENT>raise ValueError("<STR_LIT>", name)<EOL>

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.


if isinstance(buffer, _text_type):<EOL><INDENT>buffer = buffer.encode("<STR_LIT:ascii>")<EOL><DEDENT>bio = _new_mem_buf(buffer)<EOL>if type == FILETYPE_PEM:<EOL><INDENT>x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>if x509 == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>return X509._from_raw_x509_ptr(x509)<EOL>

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


bio = _new_mem_buf()<EOL>if type == FILETYPE_PEM:<EOL><INDENT>result_code = _lib.PEM_write_bio_X509(bio, cert._x509)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>result_code = _lib.i2d_X509_bio(bio, cert._x509)<EOL><DEDENT>elif type == FILETYPE_TEXT:<EOL><INDENT>result_code = _lib.X509_print_ex(bio, cert._x509, <NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>assert result_code == <NUM_LIT:1><EOL>return _bio_to_string(bio)<EOL>

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


bio = _new_mem_buf()<EOL>if type == FILETYPE_PEM:<EOL><INDENT>write_bio = _lib.PEM_write_bio_PUBKEY<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>write_bio = _lib.i2d_PUBKEY_bio<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>result_code = write_bio(bio, pkey._pkey)<EOL>if result_code != <NUM_LIT:1>:  <EOL><INDENT>_raise_current_error()<EOL><DEDENT>return _bio_to_string(bio)<EOL>

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


def dump_privatekey(type, pkey, cipher=None, passphrase=None):

bio = _new_mem_buf()<EOL>if not isinstance(pkey, PKey):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if cipher is not None:<EOL><INDENT>if passphrase is None:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))<EOL>if cipher_obj == _ffi.NULL:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cipher_obj = _ffi.NULL<EOL><DEDENT>helper = _PassphraseHelper(type, passphrase)<EOL>if type == FILETYPE_PEM:<EOL><INDENT>result_code = _lib.PEM_write_bio_PrivateKey(<EOL>bio, pkey._pkey, cipher_obj, _ffi.NULL, <NUM_LIT:0>,<EOL>helper.callback, helper.callback_args)<EOL>helper.raise_if_problem()<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)<EOL><DEDENT>elif type == FILETYPE_TEXT:<EOL><INDENT>if _lib.EVP_PKEY_id(pkey._pkey) != _lib.EVP_PKEY_RSA:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>rsa = _ffi.gc(<EOL>_lib.EVP_PKEY_get1_RSA(pkey._pkey),<EOL>_lib.RSA_free<EOL>)<EOL>result_code = _lib.RSA_print(bio, rsa, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>_openssl_assert(result_code != <NUM_LIT:0>)<EOL>return _bio_to_string(bio)<EOL>

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


if isinstance(buffer, _text_type):<EOL><INDENT>buffer = buffer.encode("<STR_LIT:ascii>")<EOL><DEDENT>bio = _new_mem_buf(buffer)<EOL>if type == FILETYPE_PEM:<EOL><INDENT>evp_pkey = _lib.PEM_read_bio_PUBKEY(<EOL>bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if evp_pkey == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>pkey = PKey.__new__(PKey)<EOL>pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)<EOL>pkey._only_public = True<EOL>return pkey<EOL>

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`


def load_privatekey(type, buffer, passphrase=None):

if isinstance(buffer, _text_type):<EOL><INDENT>buffer = buffer.encode("<STR_LIT:ascii>")<EOL><DEDENT>bio = _new_mem_buf(buffer)<EOL>helper = _PassphraseHelper(type, passphrase)<EOL>if type == FILETYPE_PEM:<EOL><INDENT>evp_pkey = _lib.PEM_read_bio_PrivateKey(<EOL>bio, _ffi.NULL, helper.callback, helper.callback_args)<EOL>helper.raise_if_problem()<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if evp_pkey == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>pkey = PKey.__new__(PKey)<EOL>pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)<EOL>return pkey<EOL>

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


bio = _new_mem_buf()<EOL>if type == FILETYPE_PEM:<EOL><INDENT>result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>result_code = _lib.i2d_X509_REQ_bio(bio, req._req)<EOL><DEDENT>elif type == FILETYPE_TEXT:<EOL><INDENT>result_code = _lib.X509_REQ_print_ex(bio, req._req, <NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>_openssl_assert(result_code != <NUM_LIT:0>)<EOL>return _bio_to_string(bio)<EOL>

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


if isinstance(buffer, _text_type):<EOL><INDENT>buffer = buffer.encode("<STR_LIT:ascii>")<EOL><DEDENT>bio = _new_mem_buf(buffer)<EOL>if type == FILETYPE_PEM:<EOL><INDENT>req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_openssl_assert(req != _ffi.NULL)<EOL>x509req = X509Req.__new__(X509Req)<EOL>x509req._req = _ffi.gc(req, _lib.X509_REQ_free)<EOL>return x509req<EOL>

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


data = _text_to_bytes_and_warn("<STR_LIT:data>", data)<EOL>digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))<EOL>if digest_obj == _ffi.NULL:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>md_ctx = _lib.Cryptography_EVP_MD_CTX_new()<EOL>md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)<EOL>_lib.EVP_SignInit(md_ctx, digest_obj)<EOL>_lib.EVP_SignUpdate(md_ctx, data, len(data))<EOL>length = _lib.EVP_PKEY_size(pkey._pkey)<EOL>_openssl_assert(length > <NUM_LIT:0>)<EOL>signature_buffer = _ffi.new("<STR_LIT>", length)<EOL>signature_length = _ffi.new("<STR_LIT>")<EOL>final_result = _lib.EVP_SignFinal(<EOL>md_ctx, signature_buffer, signature_length, pkey._pkey)<EOL>_openssl_assert(final_result == <NUM_LIT:1>)<EOL>return _ffi.buffer(signature_buffer, signature_length[<NUM_LIT:0>])[:]<EOL>

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


def verify(cert, signature, data, digest):

data = _text_to_bytes_and_warn("<STR_LIT:data>", data)<EOL>digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))<EOL>if digest_obj == _ffi.NULL:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>pkey = _lib.X509_get_pubkey(cert._x509)<EOL>_openssl_assert(pkey != _ffi.NULL)<EOL>pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)<EOL>md_ctx = _lib.Cryptography_EVP_MD_CTX_new()<EOL>md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)<EOL>_lib.EVP_VerifyInit(md_ctx, digest_obj)<EOL>_lib.EVP_VerifyUpdate(md_ctx, data, len(data))<EOL>verify_result = _lib.EVP_VerifyFinal(<EOL>md_ctx, signature, len(signature), pkey<EOL>)<EOL>if verify_result != <NUM_LIT:1>:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>

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


bio = _new_mem_buf()<EOL>if type == FILETYPE_PEM:<EOL><INDENT>ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)<EOL><DEDENT>elif type == FILETYPE_TEXT:<EOL><INDENT>ret = _lib.X509_CRL_print(bio, crl._crl)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>assert ret == <NUM_LIT:1><EOL>return _bio_to_string(bio)<EOL>

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


if isinstance(buffer, _text_type):<EOL><INDENT>buffer = buffer.encode("<STR_LIT:ascii>")<EOL><DEDENT>bio = _new_mem_buf(buffer)<EOL>if type == FILETYPE_PEM:<EOL><INDENT>crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if crl == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>result = CRL.__new__(CRL)<EOL>result._crl = _ffi.gc(crl, _lib.X509_CRL_free)<EOL>return result<EOL>

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


if isinstance(buffer, _text_type):<EOL><INDENT>buffer = buffer.encode("<STR_LIT:ascii>")<EOL><DEDENT>bio = _new_mem_buf(buffer)<EOL>if type == FILETYPE_PEM:<EOL><INDENT>pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)<EOL><DEDENT>elif type == FILETYPE_ASN1:<EOL><INDENT>pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if pkcs7 == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>pypkcs7 = PKCS7.__new__(PKCS7)<EOL>pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)<EOL>return pypkcs7<EOL>

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


passphrase = _text_to_bytes_and_warn("<STR_LIT>", passphrase)<EOL>if isinstance(buffer, _text_type):<EOL><INDENT>buffer = buffer.encode("<STR_LIT:ascii>")<EOL><DEDENT>bio = _new_mem_buf(buffer)<EOL>if not passphrase:<EOL><INDENT>passphrase = _ffi.NULL<EOL><DEDENT>p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)<EOL>if p12 == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>p12 = _ffi.gc(p12, _lib.PKCS12_free)<EOL>pkey = _ffi.new("<STR_LIT>")<EOL>cert = _ffi.new("<STR_LIT>")<EOL>cacerts = _ffi.new("<STR_LIT>")<EOL>parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)<EOL>if not parse_result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>cacerts = _ffi.gc(cacerts[<NUM_LIT:0>], _lib.sk_X509_free)<EOL>try:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>except Error:<EOL><INDENT>pass<EOL><DEDENT>if pkey[<NUM_LIT:0>] == _ffi.NULL:<EOL><INDENT>pykey = None<EOL><DEDENT>else:<EOL><INDENT>pykey = PKey.__new__(PKey)<EOL>pykey._pkey = _ffi.gc(pkey[<NUM_LIT:0>], _lib.EVP_PKEY_free)<EOL><DEDENT>if cert[<NUM_LIT:0>] == _ffi.NULL:<EOL><INDENT>pycert = None<EOL>friendlyname = None<EOL><DEDENT>else:<EOL><INDENT>pycert = X509._from_raw_x509_ptr(cert[<NUM_LIT:0>])<EOL>friendlyname_length = _ffi.new("<STR_LIT>")<EOL>friendlyname_buffer = _lib.X509_alias_get0(<EOL>cert[<NUM_LIT:0>], friendlyname_length<EOL>)<EOL>friendlyname = _ffi.buffer(<EOL>friendlyname_buffer, friendlyname_length[<NUM_LIT:0>]<EOL>)[:]<EOL>if friendlyname_buffer == _ffi.NULL:<EOL><INDENT>friendlyname = None<EOL><DEDENT><DEDENT>pycacerts = []<EOL>for i in range(_lib.sk_X509_num(cacerts)):<EOL><INDENT>x509 = _lib.sk_X509_value(cacerts, i)<EOL>pycacert = X509._from_raw_x509_ptr(x509)<EOL>pycacerts.append(pycacert)<EOL><DEDENT>if not pycacerts:<EOL><INDENT>pycacerts = None<EOL><DEDENT>pkcs12 = PKCS12.__new__(PKCS12)<EOL>pkcs12._pkey = pykey<EOL>pkcs12._cert = pycert<EOL>pkcs12._cacerts = pycacerts<EOL>pkcs12._friendlyname = friendlyname<EOL>return pkcs12<EOL>

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


backend = _get_backend()<EOL>if self._only_public:<EOL><INDENT>return backend._evp_pkey_to_public_key(self._pkey)<EOL><DEDENT>else:<EOL><INDENT>return backend._evp_pkey_to_private_key(self._pkey)<EOL><DEDENT>

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


pkey = cls()<EOL>if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,<EOL>dsa.DSAPublicKey, dsa.DSAPrivateKey)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>pkey._pkey = crypto_key._evp_pkey<EOL>if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):<EOL><INDENT>pkey._only_public = True<EOL><DEDENT>pkey._initialized = True<EOL>return pkey<EOL>

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


if not isinstance(type, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(bits, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if type == TYPE_RSA:<EOL><INDENT>if bits <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>exponent = _lib.BN_new()<EOL>exponent = _ffi.gc(exponent, _lib.BN_free)<EOL>_lib.BN_set_word(exponent, _lib.RSA_F4)<EOL>rsa = _lib.RSA_new()<EOL>result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)<EOL>_openssl_assert(result == <NUM_LIT:1>)<EOL>result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)<EOL>_openssl_assert(result == <NUM_LIT:1>)<EOL><DEDENT>elif type == TYPE_DSA:<EOL><INDENT>dsa = _lib.DSA_new()<EOL>_openssl_assert(dsa != _ffi.NULL)<EOL>dsa = _ffi.gc(dsa, _lib.DSA_free)<EOL>res = _lib.DSA_generate_parameters_ex(<EOL>dsa, bits, _ffi.NULL, <NUM_LIT:0>, _ffi.NULL, _ffi.NULL, _ffi.NULL<EOL>)<EOL>_openssl_assert(res == <NUM_LIT:1>)<EOL>_openssl_assert(_lib.DSA_generate_key(dsa) == <NUM_LIT:1>)<EOL>_openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>raise Error("<STR_LIT>")<EOL><DEDENT>self._initialized = True<EOL>

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``


if self._only_public:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)<EOL>rsa = _ffi.gc(rsa, _lib.RSA_free)<EOL>result = _lib.RSA_check_key(rsa)<EOL>if result:<EOL><INDENT>return True<EOL><DEDENT>_raise_current_error()<EOL>

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.


return _lib.EVP_PKEY_id(self._pkey)<EOL>

Returns the type of the key

:return: The type of the key.


return _lib.EVP_PKEY_bits(self._pkey)<EOL>

Returns the number of bits of the key

:return: The number of bits of the key.


num_curves = lib.EC_get_builtin_curves(_ffi.NULL, <NUM_LIT:0>)<EOL>builtin_curves = _ffi.new('<STR_LIT>', num_curves)<EOL>lib.EC_get_builtin_curves(builtin_curves, num_curves)<EOL>return set(<EOL>cls.from_nid(lib, c.nid)<EOL>for c in builtin_curves)<EOL>

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.


if cls._curves is None:<EOL><INDENT>cls._curves = cls._load_elliptic_curves(lib)<EOL><DEDENT>return cls._curves<EOL>

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.


@classmethod<EOL><INDENT>def from_nid(cls, lib, nid):<DEDENT>

return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("<STR_LIT:ascii>"))<EOL>

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.


self._lib = lib<EOL>self._nid = nid<EOL>self.name = name<EOL>

: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`


key = self._lib.EC_KEY_new_by_curve_name(self._nid)<EOL>return _ffi.gc(key, _lib.EC_KEY_free)<EOL>

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.


name = _lib.X509_NAME_dup(name._name)<EOL>self._name = _ffi.gc(name, _lib.X509_NAME_free)<EOL>

Create a new X509Name, copying the given X509Name instance.

:param name: The name to copy.
:type name: :py:class:`X509Name`


nid = _lib.OBJ_txt2nid(_byte_string(name))<EOL>if nid == _lib.NID_undef:<EOL><INDENT>try:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>except Error:<EOL><INDENT>pass<EOL><DEDENT>return super(X509Name, self).__getattr__(name)<EOL><DEDENT>entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -<NUM_LIT:1>)<EOL>if entry_index == -<NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>entry = _lib.X509_NAME_get_entry(self._name, entry_index)<EOL>data = _lib.X509_NAME_ENTRY_get_data(entry)<EOL>result_buffer = _ffi.new("<STR_LIT>")<EOL>data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)<EOL>_openssl_assert(data_length >= <NUM_LIT:0>)<EOL>try:<EOL><INDENT>result = _ffi.buffer(<EOL>result_buffer[<NUM_LIT:0>], data_length<EOL>)[:].decode('<STR_LIT:utf-8>')<EOL><DEDENT>finally:<EOL><INDENT>_lib.OPENSSL_free(result_buffer[<NUM_LIT:0>])<EOL><DEDENT>return result<EOL>

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...


result_buffer = _ffi.new("<STR_LIT>", <NUM_LIT>)<EOL>format_result = _lib.X509_NAME_oneline(<EOL>self._name, result_buffer, len(result_buffer))<EOL>_openssl_assert(format_result != _ffi.NULL)<EOL>return "<STR_LIT>" % (<EOL>_native(_ffi.string(result_buffer)),)<EOL>


return _lib.X509_NAME_hash(self._name)<EOL>

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`


result_buffer = _ffi.new('<STR_LIT>')<EOL>encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)<EOL>_openssl_assert(encode_result >= <NUM_LIT:0>)<EOL>string_result = _ffi.buffer(result_buffer[<NUM_LIT:0>], encode_result)[:]<EOL>_lib.OPENSSL_free(result_buffer[<NUM_LIT:0>])<EOL>return string_result<EOL>

Return the DER encoding of this name.

:return: The DER encoded form of this name.
:rtype: :py:class:`bytes`


result = []<EOL>for i in range(_lib.X509_NAME_entry_count(self._name)):<EOL><INDENT>ent = _lib.X509_NAME_get_entry(self._name, i)<EOL>fname = _lib.X509_NAME_ENTRY_get_object(ent)<EOL>fval = _lib.X509_NAME_ENTRY_get_data(ent)<EOL>nid = _lib.OBJ_obj2nid(fname)<EOL>name = _lib.OBJ_nid2sn(nid)<EOL>value = _ffi.buffer(_lib.ASN1_STRING_data(fval),<EOL>_lib.ASN1_STRING_length(fval))[:]<EOL>result.append((_ffi.string(name), value))<EOL><DEDENT>return result<EOL>

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.


def __init__(self, type_name, critical, value, subject=None, issuer=None):

ctx = _ffi.new("<STR_LIT>")<EOL>_lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, <NUM_LIT:0>)<EOL>_lib.X509V3_set_ctx_nodb(ctx)<EOL>if issuer is not None:<EOL><INDENT>if not isinstance(issuer, X509):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>ctx.issuer_cert = issuer._x509<EOL><DEDENT>if subject is not None:<EOL><INDENT>if not isinstance(subject, X509):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>ctx.subject_cert = subject._x509<EOL><DEDENT>if critical:<EOL><INDENT>value = b"<STR_LIT>" + value<EOL><DEDENT>extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)<EOL>if extension == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)<EOL>

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


if _lib.NID_subject_alt_name == self._nid:<EOL><INDENT>return self._subjectAltNameString()<EOL><DEDENT>bio = _new_mem_buf()<EOL>print_result = _lib.X509V3_EXT_print(bio, self._extension, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>_openssl_assert(print_result != <NUM_LIT:0>)<EOL>return _native(_bio_to_string(bio))<EOL>

:return: a nice text representation of the extension


return _lib.X509_EXTENSION_get_critical(self._extension)<EOL>

Returns the critical field of this X.509 extension.

:return: The critical field.


obj = _lib.X509_EXTENSION_get_object(self._extension)<EOL>nid = _lib.OBJ_obj2nid(obj)<EOL>return _ffi.string(_lib.OBJ_nid2sn(nid))<EOL>

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


octet_result = _lib.X509_EXTENSION_get_data(self._extension)<EOL>string_result = _ffi.cast('<STR_LIT>', octet_result)<EOL>char_result = _lib.ASN1_STRING_data(string_result)<EOL>result_length = _lib.ASN1_STRING_length(string_result)<EOL>return _ffi.buffer(char_result, result_length)[:]<EOL>

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


from cryptography.hazmat.backends.openssl.x509 import (<EOL>_CertificateSigningRequest<EOL>)<EOL>backend = _get_backend()<EOL>return _CertificateSigningRequest(backend, self._req)<EOL>

Export as a ``cryptography`` certificate signing request.

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

.. versionadded:: 17.1.0


if not isinstance(crypto_req, x509.CertificateSigningRequest):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>req = cls()<EOL>req._req = crypto_req._x509_req<EOL>return req<EOL>

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


set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)<EOL>_openssl_assert(set_result == <NUM_LIT:1>)<EOL>

Set the public key of the certificate signing request.

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

:return: ``None``


pkey = PKey.__new__(PKey)<EOL>pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)<EOL>_openssl_assert(pkey._pkey != _ffi.NULL)<EOL>pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)<EOL>pkey._only_public = True<EOL>return pkey<EOL>

Get the public key of the certificate signing request.

:return: The public key.
:rtype: :py:class:`PKey`


set_result = _lib.X509_REQ_set_version(self._req, version)<EOL>_openssl_assert(set_result == <NUM_LIT:1>)<EOL>

Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
request.

:param int version: The version number.
:return: ``None``


return _lib.X509_REQ_get_version(self._req)<EOL>

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`


name = X509Name.__new__(X509Name)<EOL>name._name = _lib.X509_REQ_get_subject_name(self._req)<EOL>_openssl_assert(name._name != _ffi.NULL)<EOL>name._owner = self<EOL>return name<EOL>

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`


stack = _lib.sk_X509_EXTENSION_new_null()<EOL>_openssl_assert(stack != _ffi.NULL)<EOL>stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)<EOL>for ext in extensions:<EOL><INDENT>if not isinstance(ext, X509Extension):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_lib.sk_X509_EXTENSION_push(stack, ext._extension)<EOL><DEDENT>add_result = _lib.X509_REQ_add_extensions(self._req, stack)<EOL>_openssl_assert(add_result == <NUM_LIT:1>)<EOL>

Add extensions to the certificate signing request.

:param extensions: The X.509 extensions to add.
:type extensions: iterable of :py:class:`X509Extension`
:return: ``None``


exts = []<EOL>native_exts_obj = _lib.X509_REQ_get_extensions(self._req)<EOL>for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):<EOL><INDENT>ext = X509Extension.__new__(X509Extension)<EOL>ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)<EOL>exts.append(ext)<EOL><DEDENT>return exts<EOL>

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


if pkey._only_public:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not pkey._initialized:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))<EOL>if digest_obj == _ffi.NULL:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)<EOL>_openssl_assert(sign_result > <NUM_LIT:0>)<EOL>

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``


if not isinstance(pkey, PKey):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>result = _lib.X509_REQ_verify(self._req, pkey._pkey)<EOL>if result <= <NUM_LIT:0>:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>return result<EOL>

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.


from cryptography.hazmat.backends.openssl.x509 import _Certificate<EOL>backend = _get_backend()<EOL>return _Certificate(backend, self._x509)<EOL>

Export as a ``cryptography`` certificate.

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

.. versionadded:: 17.1.0


if not isinstance(crypto_cert, x509.Certificate):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>cert = cls()<EOL>cert._x509 = crypto_cert._x509<EOL>return cert<EOL>

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


if not isinstance(version, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_lib.X509_set_version(self._x509, version)<EOL>

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``


return _lib.X509_get_version(self._x509)<EOL>

Return the version number of the certificate.

:return: The version number of the certificate.
:rtype: :py:class:`int`


pkey = PKey.__new__(PKey)<EOL>pkey._pkey = _lib.X509_get_pubkey(self._x509)<EOL>if pkey._pkey == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)<EOL>pkey._only_public = True<EOL>return pkey<EOL>

Get the public key of the certificate.

:return: The public key.
:rtype: :py:class:`PKey`


if not isinstance(pkey, PKey):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)<EOL>_openssl_assert(set_result == <NUM_LIT:1>)<EOL>

Set the public key of the certificate.

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

:return: :py:data:`None`


if not isinstance(pkey, PKey):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if pkey._only_public:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not pkey._initialized:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))<EOL>if evp_md == _ffi.NULL:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)<EOL>_openssl_assert(sign_result > <NUM_LIT:0>)<EOL>

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`


algor = _lib.X509_get0_tbs_sigalg(self._x509)<EOL>nid = _lib.OBJ_obj2nid(algor.algorithm)<EOL>if nid == _lib.NID_undef:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return _ffi.string(_lib.OBJ_nid2ln(nid))<EOL>

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


digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))<EOL>if digest == _ffi.NULL:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>result_buffer = _ffi.new("<STR_LIT>", _lib.EVP_MAX_MD_SIZE)<EOL>result_length = _ffi.new("<STR_LIT>", <NUM_LIT:1>)<EOL>result_length[<NUM_LIT:0>] = len(result_buffer)<EOL>digest_result = _lib.X509_digest(<EOL>self._x509, digest, result_buffer, result_length)<EOL>_openssl_assert(digest_result == <NUM_LIT:1>)<EOL>return b"<STR_LIT::>".join([<EOL>b16encode(ch).upper() for ch<EOL>in _ffi.buffer(result_buffer, result_length[<NUM_LIT:0>])])<EOL>

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`


return _lib.X509_subject_name_hash(self._x509)<EOL>

Return the hash of the X509 subject.

:return: The hash of the subject.
:rtype: :py:class:`bytes`


if not isinstance(serial, _integer_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>hex_serial = hex(serial)[<NUM_LIT:2>:]<EOL>if not isinstance(hex_serial, bytes):<EOL><INDENT>hex_serial = hex_serial.encode('<STR_LIT:ascii>')<EOL><DEDENT>bignum_serial = _ffi.new("<STR_LIT>")<EOL>small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)<EOL>if bignum_serial[<NUM_LIT:0>] == _ffi.NULL:<EOL><INDENT>set_result = _lib.ASN1_INTEGER_set(<EOL>_lib.X509_get_serialNumber(self._x509), small_serial)<EOL>if set_result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[<NUM_LIT:0>], _ffi.NULL)<EOL>_lib.BN_free(bignum_serial[<NUM_LIT:0>])<EOL>if asn1_serial == _ffi.NULL:<EOL><INDENT>_raise_current_error()<EOL><DEDENT>asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)<EOL>set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)<EOL>_openssl_assert(set_result == <NUM_LIT:1>)<EOL><DEDENT>

Set the serial number of the certificate.

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

:return: :py:data`None`


asn1_serial = _lib.X509_get_serialNumber(self._x509)<EOL>bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)<EOL>try:<EOL><INDENT>hex_serial = _lib.BN_bn2hex(bignum_serial)<EOL>try:<EOL><INDENT>hexstring_serial = _ffi.string(hex_serial)<EOL>serial = int(hexstring_serial, <NUM_LIT:16>)<EOL>return serial<EOL><DEDENT>finally:<EOL><INDENT>_lib.OPENSSL_free(hex_serial)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>_lib.BN_free(bignum_serial)<EOL><DEDENT>

Return the serial number of this certificate.

:return: The serial number.
:rtype: int


if not isinstance(amount, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>notAfter = _lib.X509_get_notAfter(self._x509)<EOL>_lib.X509_gmtime_adj(notAfter, amount)<EOL>

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``


if not isinstance(amount, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>notBefore = _lib.X509_get_notBefore(self._x509)<EOL>_lib.X509_gmtime_adj(notBefore, amount)<EOL>

Adjust the timestamp on which the certificate starts being valid.

:param amount: The number of seconds by which to adjust the timestamp.
:return: ``None``


time_string = _native(self.get_notAfter())<EOL>not_after = datetime.datetime.strptime(time_string, "<STR_LIT>")<EOL>return not_after < datetime.datetime.utcnow()<EOL>

Check whether the certificate has expired.

:return: ``True`` if the certificate has expired, ``False`` otherwise.
:rtype: bool


return self._get_boundary_time(_lib.X509_get_notBefore)<EOL>

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


return self._set_boundary_time(_lib.X509_get_notBefore, when)<EOL>

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``


return self._get_boundary_time(_lib.X509_get_notAfter)<EOL>

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


return self._set_boundary_time(_lib.X509_get_notAfter, when)<EOL>

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``


name = self._get_name(_lib.X509_get_issuer_name)<EOL>self._issuer_invalidator.add(name)<EOL>return name<EOL>

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`


self._set_name(_lib.X509_set_issuer_name, issuer)<EOL>self._issuer_invalidator.clear()<EOL>

Set the issuer of this certificate.

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

:return: ``None``


name = self._get_name(_lib.X509_get_subject_name)<EOL>self._subject_invalidator.add(name)<EOL>return name<EOL>

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`


self._set_name(_lib.X509_set_subject_name, subject)<EOL>self._subject_invalidator.clear()<EOL>

Set the subject of this certificate.

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

:return: ``None``


return _lib.X509_get_ext_count(self._x509)<EOL>

Get the number of extensions on this certificate.

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

.. versionadded:: 0.12


for ext in extensions:<EOL><INDENT>if not isinstance(ext, X509Extension):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>add_result = _lib.X509_add_ext(self._x509, ext._extension, -<NUM_LIT:1>)<EOL>if not add_result:<EOL><INDENT>_raise_current_error()<EOL><DEDENT><DEDENT>

Add extensions to the certificate.

:param extensions: The extensions to add.
:type extensions: An iterable of :py:class:`X509Extension` objects.
:return: ``None``