_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q269700 | OAuth2RequestValidator.authenticate_client_id | test | def authenticate_client_id(self, client_id, request, *args, **kwargs):
"""Authenticate a non-confidential client.
:param client_id: Client ID of the non-confidential client
:param request: The Request object passed by oauthlib
"""
if client_id is None:
client_id, _ = self._get_client_creds_from_request(request)
log.debug('Authenticate client %r.', client_id)
| python | {
"resource": ""
} |
q269701 | OAuth2RequestValidator.get_original_scopes | test | def get_original_scopes(self, refresh_token, request, *args, **kwargs):
"""Get the list of scopes associated with the refresh token.
This method is used in the refresh token grant flow. We return
the scope of the token to be refreshed so it can be applied to the
| python | {
"resource": ""
} |
q269702 | OAuth2RequestValidator.confirm_scopes | test | def confirm_scopes(self, refresh_token, scopes, request, *args, **kwargs):
"""Ensures the requested scope matches the scope originally granted
by the resource owner. If the scope is omitted it is treated as equal
to the scope originally granted by the resource owner.
DEPRECATION NOTE: This method will cease to be used in oauthlib>0.4.2,
future versions of ``oauthlib`` use the validator method
``get_original_scopes`` to determine the scope of the refreshed token.
"""
if not scopes:
log.debug('Scope omitted for refresh | python | {
"resource": ""
} |
q269703 | OAuth2RequestValidator.get_default_redirect_uri | test | def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
"""Default redirect_uri for the given client."""
request.client = request.client or self._clientgetter(client_id)
| python | {
"resource": ""
} |
q269704 | OAuth2RequestValidator.get_default_scopes | test | def get_default_scopes(self, client_id, request, *args, **kwargs):
"""Default scopes for the given client."""
| python | {
"resource": ""
} |
q269705 | OAuth2RequestValidator.invalidate_authorization_code | test | def invalidate_authorization_code(self, client_id, code, request,
*args, **kwargs):
"""Invalidate an authorization code after use.
We keep the temporary code in a grant, which has a `delete`
function to destroy itself.
"""
| python | {
"resource": ""
} |
q269706 | OAuth2RequestValidator.save_authorization_code | test | def save_authorization_code(self, client_id, code, request,
*args, **kwargs):
"""Persist the authorization code."""
log.debug(
'Persist authorization code %r for client %r',
code, client_id
)
| python | {
"resource": ""
} |
q269707 | OAuth2RequestValidator.save_bearer_token | test | def save_bearer_token(self, token, request, *args, **kwargs):
"""Persist the Bearer token."""
log.debug('Save bearer token %r', token)
| python | {
"resource": ""
} |
q269708 | OAuth2RequestValidator.validate_bearer_token | test | def validate_bearer_token(self, token, scopes, request):
"""Validate access token.
:param token: A string of random characters
:param scopes: A list of scopes
:param request: The Request object passed by oauthlib
The validation validates:
1) if the token is available
2) if the token has expired
3) if the scopes are available
"""
log.debug('Validate bearer token %r', token)
tok = self._tokengetter(access_token=token)
if not tok:
msg = 'Bearer token not found.'
request.error_message = msg
log.debug(msg)
return False
# validate expires
if tok.expires is not None and \
datetime.datetime.utcnow() > tok.expires:
msg = 'Bearer token is expired.'
request.error_message = msg
log.debug(msg)
| python | {
"resource": ""
} |
q269709 | OAuth2RequestValidator.validate_client_id | test | def validate_client_id(self, client_id, request, *args, **kwargs):
"""Ensure client_id belong to a valid and active client."""
log.debug('Validate client %r', | python | {
"resource": ""
} |
q269710 | OAuth2RequestValidator.validate_code | test | def validate_code(self, client_id, code, client, request, *args, **kwargs):
"""Ensure the grant code is valid."""
client = client or self._clientgetter(client_id)
log.debug(
'Validate code for client %r and code %r', client.client_id, code
)
grant = self._grantgetter(client_id=client.client_id, code=code)
| python | {
"resource": ""
} |
q269711 | OAuth2RequestValidator.validate_grant_type | test | def validate_grant_type(self, client_id, grant_type, client, request,
*args, **kwargs):
"""Ensure the client is authorized to use the grant type requested.
It will allow any of the four grant types (`authorization_code`,
`password`, `client_credentials`, `refresh_token`) by default.
Implemented `allowed_grant_types` for client object to authorize
the request.
It is suggested that `allowed_grant_types` should contain at least
`authorization_code` and `refresh_token`.
"""
if self._usergetter is None and grant_type == 'password':
| python | {
"resource": ""
} |
q269712 | OAuth2RequestValidator.validate_refresh_token | test | def validate_refresh_token(self, refresh_token, client, request,
*args, **kwargs):
"""Ensure the token is valid and belongs to the client
This method is used by the authorization code grant indirectly by
issuing refresh tokens, resource owner password credentials grant
(also indirectly) and the refresh token grant.
"""
| python | {
"resource": ""
} |
q269713 | OAuth2RequestValidator.validate_response_type | test | def validate_response_type(self, client_id, response_type, client, request,
*args, **kwargs):
"""Ensure client is authorized to use the response type requested.
It will allow any of the two (`code`, `token`) response types by
default. Implemented `allowed_response_types` for client object
to authorize the request.
| python | {
"resource": ""
} |
q269714 | OAuth2RequestValidator.validate_scopes | test | def validate_scopes(self, client_id, scopes, client, request,
*args, **kwargs):
"""Ensure the client is authorized access to requested scopes."""
if hasattr(client, 'validate_scopes'):
| python | {
"resource": ""
} |
q269715 | OAuth2RequestValidator.validate_user | test | def validate_user(self, username, password, client, request,
*args, **kwargs):
"""Ensure the username and password is valid.
Attach user object on request for later using.
"""
log.debug('Validating username %r and its password', | python | {
"resource": ""
} |
q269716 | OAuth2RequestValidator.revoke_token | test | def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
"""Revoke an access or refresh token.
"""
if token_type_hint:
tok = self._tokengetter(**{token_type_hint: token})
else:
tok = self._tokengetter(access_token=token)
| python | {
"resource": ""
} |
q269717 | update_qq_api_request_data | test | def update_qq_api_request_data(data={}):
'''Update some required parameters for OAuth2.0 API calls'''
defaults = {
| python | {
"resource": ""
} |
q269718 | convert_keys_to_string | test | def convert_keys_to_string(dictionary):
'''Recursively converts dictionary keys to strings.'''
if not isinstance(dictionary, dict):
return dictionary
| python | {
"resource": ""
} |
q269719 | change_weibo_header | test | def change_weibo_header(uri, headers, body):
"""Since weibo is a rubbish server, it does not follow the standard,
we need to change the authorization header for it."""
auth = headers.get('Authorization')
if auth: | python | {
"resource": ""
} |
q269720 | RemoteAppFactory.register_to | test | def register_to(self, oauth, name=None, **kwargs):
"""Creates a remote app and registers it."""
kwargs = self._process_kwargs(
| python | {
"resource": ""
} |
q269721 | RemoteAppFactory.create | test | def create(self, oauth, **kwargs):
"""Creates a remote app only."""
kwargs = | python | {
"resource": ""
} |
q269722 | extract_params | test | def extract_params():
"""Extract request params."""
uri = _get_uri_from_request(request)
http_method = request.method
headers = dict(request.headers)
if 'wsgi.input' in headers:
del headers['wsgi.input']
if 'wsgi.errors' in headers:
del headers['wsgi.errors']
# Werkzeug, and subsequently Flask provide a safe Authorization header
# parsing, so we just replace the Authorization | python | {
"resource": ""
} |
q269723 | to_bytes | test | def to_bytes(text, encoding='utf-8'):
"""Make sure text is bytes type."""
if not text:
return text
if not | python | {
"resource": ""
} |
q269724 | decode_base64 | test | def decode_base64(text, encoding='utf-8'):
"""Decode base64 string."""
text = to_bytes(text, encoding)
| python | {
"resource": ""
} |
q269725 | create_response | test | def create_response(headers, body, status):
"""Create response class for Flask."""
response = Response(body or '')
for k, v in headers.items():
| python | {
"resource": ""
} |
q269726 | get_cached_clients | test | def get_cached_clients():
"""Gets the cached clients dictionary in current context."""
if OAuth.state_key not in current_app.extensions: | python | {
"resource": ""
} |
q269727 | OAuth.add_remote_app | test | def add_remote_app(self, remote_app, name=None, **kwargs):
"""Adds remote application and applies custom attributes on it.
If the application instance's name is different from the argument
provided name, or the keyword arguments is not empty, then the
application instance will not be modified but be copied as a
prototype.
:param remote_app: the remote application instance.
:type remote_app: the subclasses of :class:`BaseApplication`
:params kwargs: the overriding attributes for the application instance.
"""
if name is None:
name = remote_app.name
| python | {
"resource": ""
} |
q269728 | OAuth.remote_app | test | def remote_app(self, name, version=None, **kwargs):
"""Creates and adds new remote application.
:param name: the remote application's name.
:param version: '1' or '2', the version code of OAuth protocol.
:param kwargs: the attributes of remote application.
"""
if version is None:
if 'request_token_url' in kwargs:
version = '1'
else:
version = '2'
| python | {
"resource": ""
} |
q269729 | Checker_X509_get_pubkey.check_exception | test | def check_exception(self):
"""
Call the method repeatedly such that it will raise an exception.
"""
for i in xrange(self.iterations):
cert = X509()
| python | {
"resource": ""
} |
q269730 | Checker_X509_get_pubkey.check_success | test | def check_success(self):
"""
Call the method repeatedly such that it will return a PKey object.
"""
small = xrange(3)
for i in xrange(self.iterations):
key = PKey()
key.generate_key(TYPE_DSA, 256)
| python | {
"resource": ""
} |
q269731 | Checker_load_privatekey.check_load_privatekey_callback | test | def check_load_privatekey_callback(self):
"""
Call the function with an encrypted PEM and a passphrase callback.
"""
for i in xrange(self.iterations * 10):
| python | {
"resource": ""
} |
q269732 | Checker_load_privatekey.check_load_privatekey_callback_incorrect | test | def check_load_privatekey_callback_incorrect(self):
"""
Call the function with an encrypted PEM and a passphrase callback which
returns the wrong passphrase.
| python | {
"resource": ""
} |
q269733 | Checker_load_privatekey.check_load_privatekey_callback_wrong_type | test | def check_load_privatekey_callback_wrong_type(self):
"""
Call the function with an encrypted PEM and a passphrase callback which
returns a non-string.
| python | {
"resource": ""
} |
q269734 | Checker_CRL.check_get_revoked | test | def check_get_revoked(self):
"""
Create a CRL object with 100 Revoked objects, then call the
get_revoked method repeatedly.
"""
crl = CRL()
for i in xrange(100):
| python | {
"resource": ""
} |
q269735 | Checker_X509_REVOKED_dup.check_X509_REVOKED_dup | test | def check_X509_REVOKED_dup(self):
"""
Copy an empty Revoked object repeatedly. The copy is not garbage
collected, therefore it needs to be manually freed.
"""
for i in xrange(self.iterations * 100):
| python | {
"resource": ""
} |
q269736 | createCertRequest | test | def createCertRequest(pkey, digest="sha256", **name):
"""
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
| python | {
"resource": ""
} |
q269737 | createCertificate | test | def createCertificate(req, issuerCertKey, serial, validityPeriod,
digest="sha256"):
"""
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
| python | {
"resource": ""
} |
q269738 | _make_requires | test | def _make_requires(flag, error):
"""
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.
| python | {
"resource": ""
} |
q269739 | Context.load_verify_locations | test | def load_verify_locations(self, cafile, capath=None):
"""
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
| python | {
"resource": ""
} |
q269740 | Context.set_passwd_cb | test | def set_passwd_cb(self, callback, userdata=None):
"""
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 | python | {
"resource": ""
} |
q269741 | Context.use_certificate_chain_file | test | def use_certificate_chain_file(self, certfile):
"""
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
"""
| python | {
"resource": ""
} |
q269742 | Context.use_certificate_file | test | def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
"""
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 | python | {
"resource": ""
} |
q269743 | Context.use_certificate | test | def use_certificate(self, cert):
"""
Load a certificate from a X509 object
:param cert: The X509 object
:return: None
"""
if not isinstance(cert, X509):
raise TypeError("cert must be an X509 instance")
| python | {
"resource": ""
} |
q269744 | Context.add_extra_chain_cert | test | def add_extra_chain_cert(self, certobj):
"""
Add certificate to chain
:param certobj: The X509 certificate object to add to the chain
:return: None
"""
if not isinstance(certobj, X509):
raise TypeError("certobj must be an X509 instance")
copy = _lib.X509_dup(certobj._x509)
| python | {
"resource": ""
} |
q269745 | Context.use_privatekey_file | test | def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
"""
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
"""
keyfile = _path_string(keyfile)
if filetype is _UNSPECIFIED:
| python | {
"resource": ""
} |
q269746 | Context.use_privatekey | test | def use_privatekey(self, pkey):
"""
Load a private key from a PKey object
:param pkey: The PKey object
:return: None
"""
if not isinstance(pkey, PKey):
raise TypeError("pkey must be a PKey instance")
| python | {
"resource": ""
} |
q269747 | Context.load_client_ca | test | def load_client_ca(self, cafile):
"""
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
| python | {
"resource": ""
} |
q269748 | Context.set_verify_depth | test | def set_verify_depth(self, depth):
"""
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
"""
| python | {
"resource": ""
} |
q269749 | Context.load_tmp_dh | test | def load_tmp_dh(self, dhfile):
"""
Load parameters for Ephemeral Diffie-Hellman
:param dhfile: The file to load EDH parameters from (``bytes`` or
``unicode``).
:return: None
"""
dhfile = _path_string(dhfile)
bio = _lib.BIO_new_file(dhfile, b"r")
if bio == _ffi.NULL:
| python | {
"resource": ""
} |
q269750 | Context.set_cipher_list | test | def set_cipher_list(self, cipher_list):
"""
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
"""
cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
if not isinstance(cipher_list, bytes):
raise TypeError("cipher_list must be a byte string.")
_openssl_assert(
_lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
)
| python | {
"resource": ""
} |
q269751 | Context.set_client_ca_list | test | def set_client_ca_list(self, certificate_authorities):
"""
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
"""
name_stack = _lib.sk_X509_NAME_new_null()
_openssl_assert(name_stack != _ffi.NULL)
try:
for ca_name in certificate_authorities:
if not isinstance(ca_name, X509Name):
raise TypeError(
"client CAs must be X509Name objects, not %s "
"objects" % (
type(ca_name).__name__,
| python | {
"resource": ""
} |
q269752 | Context.add_client_ca | test | def add_client_ca(self, certificate_authority):
"""
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.
| python | {
"resource": ""
} |
q269753 | Context.set_tlsext_servername_callback | test | def set_tlsext_servername_callback(self, callback):
"""
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
"""
@wraps(callback)
def wrapper(ssl, alert, arg):
callback(Connection._reverse_mapping[ssl])
return 0
| python | {
"resource": ""
} |
q269754 | Context.set_tlsext_use_srtp | test | def set_tlsext_use_srtp(self, profiles):
"""
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
"""
if not isinstance(profiles, bytes):
| python | {
"resource": ""
} |
q269755 | Context.set_npn_select_callback | test | def set_npn_select_callback(self, callback):
"""
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
"""
_warn_npn()
| python | {
"resource": ""
} |
q269756 | Context.set_alpn_protos | test | def set_alpn_protos(self, protos):
"""
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']``.
"""
# Take the list of protocols and join them together, prefixing them
# with their lengths.
protostr = b''.join(
| python | {
"resource": ""
} |
q269757 | Context.set_alpn_select_callback | test | def set_alpn_select_callback(self, callback):
"""
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 | python | {
"resource": ""
} |
q269758 | Context._set_ocsp_callback | test | def _set_ocsp_callback(self, helper, data):
"""
This internal helper does the common work for
``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
almost all of it.
"""
self._ocsp_helper = helper
self._ocsp_callback = helper.callback
| python | {
"resource": ""
} |
q269759 | Context.set_ocsp_server_callback | test | def set_ocsp_server_callback(self, callback, data=None):
"""
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
| python | {
"resource": ""
} |
q269760 | Context.set_ocsp_client_callback | test | def set_ocsp_client_callback(self, callback, data=None):
"""
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 | python | {
"resource": ""
} |
q269761 | Connection.set_context | test | def set_context(self, context):
"""
Switch this connection to a new session context.
:param context: A :class:`Context` instance giving the new session
context to use.
"""
if not isinstance(context, | python | {
"resource": ""
} |
q269762 | Connection.get_servername | test | def get_servername(self):
"""
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
"""
| python | {
"resource": ""
} |
q269763 | Connection.set_tlsext_host_name | test | def set_tlsext_host_name(self, name):
"""
Set the value of the servername extension to send in the client hello.
:param name: A byte string giving the name.
.. versionadded:: 0.13
| python | {
"resource": ""
} |
q269764 | Connection.recv | test | def recv(self, bufsiz, flags=None):
"""
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.
| python | {
"resource": ""
} |
q269765 | Connection.recv_into | test | def recv_into(self, buffer, nbytes=None, flags=None):
"""
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 nbytes is None:
nbytes = len(buffer)
else:
nbytes = min(nbytes, len(buffer))
# We need to create a temporary buffer. This is annoying, it would be
# better if we could pass memoryviews straight into the SSL_read call,
# but right now we can't. Revisit this if CFFI gets that ability.
buf = _no_zero_allocator("char[]", nbytes)
if flags is not | python | {
"resource": ""
} |
q269766 | Connection.bio_read | test | def bio_read(self, bufsiz):
"""
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.
"""
if self._from_ssl is None:
raise TypeError("Connection sock was not None")
| python | {
"resource": ""
} |
q269767 | Connection.renegotiate | test | def renegotiate(self):
"""
Renegotiate the session.
:return: True if the renegotiation can be started, False otherwise
:rtype: bool
"""
if not self.renegotiate_pending():
| python | {
"resource": ""
} |
q269768 | Connection.shutdown | test | def shutdown(self):
"""
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
| python | {
"resource": ""
} |
q269769 | Connection.get_cipher_list | test | def get_cipher_list(self):
"""
Retrieve the list of ciphers used by the Connection object.
:return: A list of native cipher strings.
"""
ciphers = []
for i in count():
| python | {
"resource": ""
} |
q269770 | Connection.get_client_ca_list | test | def get_client_ca_list(self):
"""
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
"""
ca_names = _lib.SSL_get_client_CA_list(self._ssl)
if ca_names == _ffi.NULL:
# TODO: This is untested.
| python | {
"resource": ""
} |
q269771 | Connection.set_shutdown | test | def set_shutdown(self, state):
"""
Set the shutdown state of the Connection.
:param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
| python | {
"resource": ""
} |
q269772 | Connection.server_random | test | def server_random(self):
"""
Retrieve the random value used with the server hello message.
:return: A string representing the state
"""
session = _lib.SSL_get_session(self._ssl)
if session == _ffi.NULL:
return None
length = | python | {
"resource": ""
} |
q269773 | Connection.client_random | test | def client_random(self):
"""
Retrieve the random value used with the client hello message.
:return: A string representing the state
"""
session = _lib.SSL_get_session(self._ssl)
if session == _ffi.NULL:
return None
length | python | {
"resource": ""
} |
q269774 | Connection.master_key | test | def master_key(self):
"""
Retrieve the value of the master key for this session.
:return: A string representing the state
"""
session = _lib.SSL_get_session(self._ssl)
if session == _ffi.NULL:
return None
length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0) | python | {
"resource": ""
} |
q269775 | Connection.export_keying_material | test | def export_keying_material(self, label, olen, context=None):
"""
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
"""
outp = _no_zero_allocator("unsigned char[]", olen)
context_buf = _ffi.NULL
context_len = 0
use_context = 0
if context is not None:
context_buf = context
| python | {
"resource": ""
} |
q269776 | Connection.get_session | test | def get_session(self):
"""
Returns the Session currently used.
:return: An instance of :class:`OpenSSL.SSL.Session` or
:obj:`None` if no session exists.
.. versionadded:: 0.14
"""
session = _lib.SSL_get1_session(self._ssl)
| python | {
"resource": ""
} |
q269777 | Connection.get_cipher_name | test | def get_cipher_name(self):
"""
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
"""
| python | {
"resource": ""
} |
q269778 | Connection.get_cipher_bits | test | def get_cipher_bits(self):
"""
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
| python | {
"resource": ""
} |
q269779 | Connection.get_cipher_version | test | def get_cipher_version(self):
"""
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
"""
| python | {
"resource": ""
} |
q269780 | Connection.get_protocol_version_name | test | def get_protocol_version_name(self):
"""
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 | python | {
"resource": ""
} |
q269781 | Connection.get_next_proto_negotiated | test | def get_next_proto_negotiated(self):
"""
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
"""
_warn_npn()
| python | {
"resource": ""
} |
q269782 | Connection.set_alpn_protos | test | def set_alpn_protos(self, protos):
"""
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']``.
"""
# Take the list of protocols and join them together, prefixing them
# with their lengths.
protostr = b''.join(
chain.from_iterable((int2byte(len(p)), p) for p in | python | {
"resource": ""
} |
q269783 | Connection.get_alpn_proto_negotiated | test | def get_alpn_proto_negotiated(self):
"""
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.
"""
data = _ffi.new("unsigned char **")
data_len | python | {
"resource": ""
} |
q269784 | _new_mem_buf | test | def _new_mem_buf(buffer=None):
"""
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.
"""
if buffer is None:
| python | {
"resource": ""
} |
q269785 | _bio_to_string | test | def _bio_to_string(bio):
"""
Copy the contents of an OpenSSL BIO object into a Python byte string.
| python | {
"resource": ""
} |
q269786 | _set_asn1_time | test | def _set_asn1_time(boundary, when):
"""
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.
| python | {
"resource": ""
} |
q269787 | _get_asn1_time | test | def _get_asn1_time(timestamp):
"""
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.
"""
string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
if _lib.ASN1_STRING_length(string_timestamp) == 0:
return None
elif (
_lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
):
return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
else:
generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
_lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
if generalized_timestamp[0] == _ffi.NULL:
# This may happen:
# - if timestamp was not an ASN1_TIME
# - if allocating memory for the ASN1_GENERALIZEDTIME failed
# - if a copy of the time data from timestamp cannot be made for
# the newly allocated ASN1_GENERALIZEDTIME
| python | {
"resource": ""
} |
q269788 | get_elliptic_curve | test | def get_elliptic_curve(name):
"""
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 | python | {
"resource": ""
} |
q269789 | dump_publickey | test | def dump_publickey(type, pkey):
"""
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
| python | {
"resource": ""
} |
q269790 | load_publickey | test | def load_publickey(type, buffer):
"""
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`
"""
if isinstance(buffer, _text_type):
buffer = buffer.encode("ascii")
bio = _new_mem_buf(buffer)
if type == FILETYPE_PEM:
evp_pkey = _lib.PEM_read_bio_PUBKEY(
bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
elif type == FILETYPE_ASN1:
evp_pkey | python | {
"resource": ""
} |
q269791 | sign | test | def sign(pkey, data, digest):
"""
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
"""
data = _text_to_bytes_and_warn("data", data)
digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
if digest_obj == _ffi.NULL:
raise ValueError("No such digest method")
md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
_lib.EVP_SignInit(md_ctx, digest_obj)
_lib.EVP_SignUpdate(md_ctx, data, len(data))
| python | {
"resource": ""
} |
q269792 | verify | test | def verify(cert, signature, data, digest):
"""
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
"""
| python | {
"resource": ""
} |
q269793 | dump_crl | test | def dump_crl(type, crl):
"""
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
"""
bio = _new_mem_buf()
if type == FILETYPE_PEM:
ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
elif type == FILETYPE_ASN1:
| python | {
"resource": ""
} |
q269794 | PKey.to_cryptography_key | test | def to_cryptography_key(self):
"""
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
"""
| python | {
"resource": ""
} |
q269795 | PKey.generate_key | test | def generate_key(self, type, bits):
"""
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 not isinstance(type, int):
raise TypeError("type must be an integer")
if not isinstance(bits, int):
raise TypeError("bits must be an integer")
if type == TYPE_RSA:
if bits <= 0:
raise ValueError("Invalid number of bits")
# TODO Check error return
exponent = _lib.BN_new()
exponent = _ffi.gc(exponent, _lib.BN_free)
_lib.BN_set_word(exponent, _lib.RSA_F4)
rsa = _lib.RSA_new()
| python | {
"resource": ""
} |
q269796 | PKey.check | test | def check(self):
"""
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.
"""
if self._only_public:
raise TypeError("public key only")
if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
| python | {
"resource": ""
} |
q269797 | _EllipticCurve._load_elliptic_curves | test | def _load_elliptic_curves(cls, lib):
"""
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.
"""
num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
# The return value on this call should be num_curves again. We | python | {
"resource": ""
} |
q269798 | _EllipticCurve._get_elliptic_curves | test | def _get_elliptic_curves(cls, lib):
"""
Get, cache, and return the curves supported by OpenSSL.
:param lib: The OpenSSL library binding object.
| python | {
"resource": ""
} |
q269799 | _EllipticCurve._to_EC_KEY | test | def _to_EC_KEY(self):
"""
Create a new OpenSSL EC_KEY structure initialized to use this curve.
The structure is automatically garbage | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.