partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
_EllipticCurve._load_elliptic_curves
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.
src/OpenSSL/crypto.py
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 # could check it to make sure but if it *isn't* then.. what could # we do? Abort the whole process, I suppose...? -exarkun lib.EC_get_builtin_curves(builtin_curves, num_curves) return set( cls.from_nid(lib, c.nid) for c in builtin_curves)
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 # could check it to make sure but if it *isn't* then.. what could # we do? Abort the whole process, I suppose...? -exarkun lib.EC_get_builtin_curves(builtin_curves, num_curves) return set( cls.from_nid(lib, c.nid) for c in builtin_curves)
[ "Get", "the", "curves", "supported", "by", "OpenSSL", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L394-L411
[ "def", "_load_elliptic_curves", "(", "cls", ",", "lib", ")", ":", "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", "# could check it to make sure but if it *isn't* then.. what could", "# we do? Abort the whole process, I suppose...? -exarkun", "lib", ".", "EC_get_builtin_curves", "(", "builtin_curves", ",", "num_curves", ")", "return", "set", "(", "cls", ".", "from_nid", "(", "lib", ",", "c", ".", "nid", ")", "for", "c", "in", "builtin_curves", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
_EllipticCurve._get_elliptic_curves
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.
src/OpenSSL/crypto.py
def _get_elliptic_curves(cls, lib): """ 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. """ if cls._curves is None: cls._curves = cls._load_elliptic_curves(lib) return cls._curves
def _get_elliptic_curves(cls, lib): """ 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. """ if cls._curves is None: cls._curves = cls._load_elliptic_curves(lib) return cls._curves
[ "Get", "cache", "and", "return", "the", "curves", "supported", "by", "OpenSSL", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L414-L425
[ "def", "_get_elliptic_curves", "(", "cls", ",", "lib", ")", ":", "if", "cls", ".", "_curves", "is", "None", ":", "cls", ".", "_curves", "=", "cls", ".", "_load_elliptic_curves", "(", "lib", ")", "return", "cls", ".", "_curves" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
_EllipticCurve.from_nid
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.
src/OpenSSL/crypto.py
def from_nid(cls, lib, nid): """ 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. """ return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
def from_nid(cls, lib, nid): """ 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. """ return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
[ "Instantiate", "a", "new", ":", "py", ":", "class", ":", "_EllipticCurve", "associated", "with", "the", "given", "OpenSSL", "NID", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L428-L442
[ "def", "from_nid", "(", "cls", ",", "lib", ",", "nid", ")", ":", "return", "cls", "(", "lib", ",", "nid", ",", "_ffi", ".", "string", "(", "lib", ".", "OBJ_nid2sn", "(", "nid", ")", ")", ".", "decode", "(", "\"ascii\"", ")", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
_EllipticCurve._to_EC_KEY
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.
src/OpenSSL/crypto.py
def _to_EC_KEY(self): """ 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. """ key = self._lib.EC_KEY_new_by_curve_name(self._nid) return _ffi.gc(key, _lib.EC_KEY_free)
def _to_EC_KEY(self): """ 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. """ key = self._lib.EC_KEY_new_by_curve_name(self._nid) return _ffi.gc(key, _lib.EC_KEY_free)
[ "Create", "a", "new", "OpenSSL", "EC_KEY", "structure", "initialized", "to", "use", "this", "curve", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L464-L472
[ "def", "_to_EC_KEY", "(", "self", ")", ":", "key", "=", "self", ".", "_lib", ".", "EC_KEY_new_by_curve_name", "(", "self", ".", "_nid", ")", "return", "_ffi", ".", "gc", "(", "key", ",", "_lib", ".", "EC_KEY_free", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Name.der
Return the DER encoding of this name. :return: The DER encoded form of this name. :rtype: :py:class:`bytes`
src/OpenSSL/crypto.py
def der(self): """ Return the DER encoding of this name. :return: The DER encoded form of this name. :rtype: :py:class:`bytes` """ result_buffer = _ffi.new('unsigned char**') encode_result = _lib.i2d_X509_NAME(self._name, result_buffer) _openssl_assert(encode_result >= 0) string_result = _ffi.buffer(result_buffer[0], encode_result)[:] _lib.OPENSSL_free(result_buffer[0]) return string_result
def der(self): """ Return the DER encoding of this name. :return: The DER encoded form of this name. :rtype: :py:class:`bytes` """ result_buffer = _ffi.new('unsigned char**') encode_result = _lib.i2d_X509_NAME(self._name, result_buffer) _openssl_assert(encode_result >= 0) string_result = _ffi.buffer(result_buffer[0], encode_result)[:] _lib.OPENSSL_free(result_buffer[0]) return string_result
[ "Return", "the", "DER", "encoding", "of", "this", "name", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L660-L673
[ "def", "der", "(", "self", ")", ":", "result_buffer", "=", "_ffi", ".", "new", "(", "'unsigned char**'", ")", "encode_result", "=", "_lib", ".", "i2d_X509_NAME", "(", "self", ".", "_name", ",", "result_buffer", ")", "_openssl_assert", "(", "encode_result", ">=", "0", ")", "string_result", "=", "_ffi", ".", "buffer", "(", "result_buffer", "[", "0", "]", ",", "encode_result", ")", "[", ":", "]", "_lib", ".", "OPENSSL_free", "(", "result_buffer", "[", "0", "]", ")", "return", "string_result" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Name.get_components
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.
src/OpenSSL/crypto.py
def get_components(self): """ 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. """ result = [] for i in range(_lib.X509_NAME_entry_count(self._name)): ent = _lib.X509_NAME_get_entry(self._name, i) fname = _lib.X509_NAME_ENTRY_get_object(ent) fval = _lib.X509_NAME_ENTRY_get_data(ent) nid = _lib.OBJ_obj2nid(fname) name = _lib.OBJ_nid2sn(nid) # ffi.string does not handle strings containing NULL bytes # (which may have been generated by old, broken software) value = _ffi.buffer(_lib.ASN1_STRING_data(fval), _lib.ASN1_STRING_length(fval))[:] result.append((_ffi.string(name), value)) return result
def get_components(self): """ 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. """ result = [] for i in range(_lib.X509_NAME_entry_count(self._name)): ent = _lib.X509_NAME_get_entry(self._name, i) fname = _lib.X509_NAME_ENTRY_get_object(ent) fval = _lib.X509_NAME_ENTRY_get_data(ent) nid = _lib.OBJ_obj2nid(fname) name = _lib.OBJ_nid2sn(nid) # ffi.string does not handle strings containing NULL bytes # (which may have been generated by old, broken software) value = _ffi.buffer(_lib.ASN1_STRING_data(fval), _lib.ASN1_STRING_length(fval))[:] result.append((_ffi.string(name), value)) return result
[ "Returns", "the", "components", "of", "this", "name", "as", "a", "sequence", "of", "2", "-", "tuples", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L675-L698
[ "def", "get_components", "(", "self", ")", ":", "result", "=", "[", "]", "for", "i", "in", "range", "(", "_lib", ".", "X509_NAME_entry_count", "(", "self", ".", "_name", ")", ")", ":", "ent", "=", "_lib", ".", "X509_NAME_get_entry", "(", "self", ".", "_name", ",", "i", ")", "fname", "=", "_lib", ".", "X509_NAME_ENTRY_get_object", "(", "ent", ")", "fval", "=", "_lib", ".", "X509_NAME_ENTRY_get_data", "(", "ent", ")", "nid", "=", "_lib", ".", "OBJ_obj2nid", "(", "fname", ")", "name", "=", "_lib", ".", "OBJ_nid2sn", "(", "nid", ")", "# ffi.string does not handle strings containing NULL bytes", "# (which may have been generated by old, broken software)", "value", "=", "_ffi", ".", "buffer", "(", "_lib", ".", "ASN1_STRING_data", "(", "fval", ")", ",", "_lib", ".", "ASN1_STRING_length", "(", "fval", ")", ")", "[", ":", "]", "result", ".", "append", "(", "(", "_ffi", ".", "string", "(", "name", ")", ",", "value", ")", ")", "return", "result" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Extension.get_short_name
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
src/OpenSSL/crypto.py
def get_short_name(self): """ 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 """ obj = _lib.X509_EXTENSION_get_object(self._extension) nid = _lib.OBJ_obj2nid(obj) return _ffi.string(_lib.OBJ_nid2sn(nid))
def get_short_name(self): """ 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 """ obj = _lib.X509_EXTENSION_get_object(self._extension) nid = _lib.OBJ_obj2nid(obj) return _ffi.string(_lib.OBJ_nid2sn(nid))
[ "Returns", "the", "short", "type", "name", "of", "this", "X", ".", "509", "extension", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L821-L834
[ "def", "get_short_name", "(", "self", ")", ":", "obj", "=", "_lib", ".", "X509_EXTENSION_get_object", "(", "self", ".", "_extension", ")", "nid", "=", "_lib", ".", "OBJ_obj2nid", "(", "obj", ")", "return", "_ffi", ".", "string", "(", "_lib", ".", "OBJ_nid2sn", "(", "nid", ")", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Extension.get_data
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
src/OpenSSL/crypto.py
def get_data(self): """ 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 """ octet_result = _lib.X509_EXTENSION_get_data(self._extension) string_result = _ffi.cast('ASN1_STRING*', octet_result) char_result = _lib.ASN1_STRING_data(string_result) result_length = _lib.ASN1_STRING_length(string_result) return _ffi.buffer(char_result, result_length)[:]
def get_data(self): """ 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 """ octet_result = _lib.X509_EXTENSION_get_data(self._extension) string_result = _ffi.cast('ASN1_STRING*', octet_result) char_result = _lib.ASN1_STRING_data(string_result) result_length = _lib.ASN1_STRING_length(string_result) return _ffi.buffer(char_result, result_length)[:]
[ "Returns", "the", "data", "of", "the", "X509", "extension", "encoded", "as", "ASN", ".", "1", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L836-L849
[ "def", "get_data", "(", "self", ")", ":", "octet_result", "=", "_lib", ".", "X509_EXTENSION_get_data", "(", "self", ".", "_extension", ")", "string_result", "=", "_ffi", ".", "cast", "(", "'ASN1_STRING*'", ",", "octet_result", ")", "char_result", "=", "_lib", ".", "ASN1_STRING_data", "(", "string_result", ")", "result_length", "=", "_lib", ".", "ASN1_STRING_length", "(", "string_result", ")", "return", "_ffi", ".", "buffer", "(", "char_result", ",", "result_length", ")", "[", ":", "]" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.to_cryptography
Export as a ``cryptography`` certificate signing request. :rtype: ``cryptography.x509.CertificateSigningRequest`` .. versionadded:: 17.1.0
src/OpenSSL/crypto.py
def to_cryptography(self): """ Export as a ``cryptography`` certificate signing request. :rtype: ``cryptography.x509.CertificateSigningRequest`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import ( _CertificateSigningRequest ) backend = _get_backend() return _CertificateSigningRequest(backend, self._req)
def to_cryptography(self): """ Export as a ``cryptography`` certificate signing request. :rtype: ``cryptography.x509.CertificateSigningRequest`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import ( _CertificateSigningRequest ) backend = _get_backend() return _CertificateSigningRequest(backend, self._req)
[ "Export", "as", "a", "cryptography", "certificate", "signing", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L863-L875
[ "def", "to_cryptography", "(", "self", ")", ":", "from", "cryptography", ".", "hazmat", ".", "backends", ".", "openssl", ".", "x509", "import", "(", "_CertificateSigningRequest", ")", "backend", "=", "_get_backend", "(", ")", "return", "_CertificateSigningRequest", "(", "backend", ",", "self", ".", "_req", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.from_cryptography
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
src/OpenSSL/crypto.py
def from_cryptography(cls, crypto_req): """ 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 """ if not isinstance(crypto_req, x509.CertificateSigningRequest): raise TypeError("Must be a certificate signing request") req = cls() req._req = crypto_req._x509_req return req
def from_cryptography(cls, crypto_req): """ 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 """ if not isinstance(crypto_req, x509.CertificateSigningRequest): raise TypeError("Must be a certificate signing request") req = cls() req._req = crypto_req._x509_req return req
[ "Construct", "based", "on", "a", "cryptography", "*", "crypto_req", "*", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L878-L894
[ "def", "from_cryptography", "(", "cls", ",", "crypto_req", ")", ":", "if", "not", "isinstance", "(", "crypto_req", ",", "x509", ".", "CertificateSigningRequest", ")", ":", "raise", "TypeError", "(", "\"Must be a certificate signing request\"", ")", "req", "=", "cls", "(", ")", "req", ".", "_req", "=", "crypto_req", ".", "_x509_req", "return", "req" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.set_pubkey
Set the public key of the certificate signing request. :param pkey: The public key to use. :type pkey: :py:class:`PKey` :return: ``None``
src/OpenSSL/crypto.py
def set_pubkey(self, pkey): """ Set the public key of the certificate signing request. :param pkey: The public key to use. :type pkey: :py:class:`PKey` :return: ``None`` """ set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey) _openssl_assert(set_result == 1)
def set_pubkey(self, pkey): """ Set the public key of the certificate signing request. :param pkey: The public key to use. :type pkey: :py:class:`PKey` :return: ``None`` """ set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey) _openssl_assert(set_result == 1)
[ "Set", "the", "public", "key", "of", "the", "certificate", "signing", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L896-L906
[ "def", "set_pubkey", "(", "self", ",", "pkey", ")", ":", "set_result", "=", "_lib", ".", "X509_REQ_set_pubkey", "(", "self", ".", "_req", ",", "pkey", ".", "_pkey", ")", "_openssl_assert", "(", "set_result", "==", "1", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.get_pubkey
Get the public key of the certificate signing request. :return: The public key. :rtype: :py:class:`PKey`
src/OpenSSL/crypto.py
def get_pubkey(self): """ Get the public key of the certificate signing request. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.X509_REQ_get_pubkey(self._req) _openssl_assert(pkey._pkey != _ffi.NULL) pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
def get_pubkey(self): """ Get the public key of the certificate signing request. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.X509_REQ_get_pubkey(self._req) _openssl_assert(pkey._pkey != _ffi.NULL) pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
[ "Get", "the", "public", "key", "of", "the", "certificate", "signing", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L908-L920
[ "def", "get_pubkey", "(", "self", ")", ":", "pkey", "=", "PKey", ".", "__new__", "(", "PKey", ")", "pkey", ".", "_pkey", "=", "_lib", ".", "X509_REQ_get_pubkey", "(", "self", ".", "_req", ")", "_openssl_assert", "(", "pkey", ".", "_pkey", "!=", "_ffi", ".", "NULL", ")", "pkey", ".", "_pkey", "=", "_ffi", ".", "gc", "(", "pkey", ".", "_pkey", ",", "_lib", ".", "EVP_PKEY_free", ")", "pkey", ".", "_only_public", "=", "True", "return", "pkey" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.set_version
Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate request. :param int version: The version number. :return: ``None``
src/OpenSSL/crypto.py
def set_version(self, version): """ Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate request. :param int version: The version number. :return: ``None`` """ set_result = _lib.X509_REQ_set_version(self._req, version) _openssl_assert(set_result == 1)
def set_version(self, version): """ Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate request. :param int version: The version number. :return: ``None`` """ set_result = _lib.X509_REQ_set_version(self._req, version) _openssl_assert(set_result == 1)
[ "Set", "the", "version", "subfield", "(", "RFC", "2459", "section", "4", ".", "1", ".", "2", ".", "1", ")", "of", "the", "certificate", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L922-L931
[ "def", "set_version", "(", "self", ",", "version", ")", ":", "set_result", "=", "_lib", ".", "X509_REQ_set_version", "(", "self", ".", "_req", ",", "version", ")", "_openssl_assert", "(", "set_result", "==", "1", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.get_subject
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`
src/OpenSSL/crypto.py
def get_subject(self): """ 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` """ name = X509Name.__new__(X509Name) name._name = _lib.X509_REQ_get_subject_name(self._req) _openssl_assert(name._name != _ffi.NULL) # The name is owned by the X509Req structure. As long as the X509Name # Python object is alive, keep the X509Req Python object alive. name._owner = self return name
def get_subject(self): """ 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` """ name = X509Name.__new__(X509Name) name._name = _lib.X509_REQ_get_subject_name(self._req) _openssl_assert(name._name != _ffi.NULL) # The name is owned by the X509Req structure. As long as the X509Name # Python object is alive, keep the X509Req Python object alive. name._owner = self return name
[ "Return", "the", "subject", "of", "this", "certificate", "signing", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L943-L963
[ "def", "get_subject", "(", "self", ")", ":", "name", "=", "X509Name", ".", "__new__", "(", "X509Name", ")", "name", ".", "_name", "=", "_lib", ".", "X509_REQ_get_subject_name", "(", "self", ".", "_req", ")", "_openssl_assert", "(", "name", ".", "_name", "!=", "_ffi", ".", "NULL", ")", "# The name is owned by the X509Req structure. As long as the X509Name", "# Python object is alive, keep the X509Req Python object alive.", "name", ".", "_owner", "=", "self", "return", "name" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.add_extensions
Add extensions to the certificate signing request. :param extensions: The X.509 extensions to add. :type extensions: iterable of :py:class:`X509Extension` :return: ``None``
src/OpenSSL/crypto.py
def add_extensions(self, extensions): """ Add extensions to the certificate signing request. :param extensions: The X.509 extensions to add. :type extensions: iterable of :py:class:`X509Extension` :return: ``None`` """ stack = _lib.sk_X509_EXTENSION_new_null() _openssl_assert(stack != _ffi.NULL) stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free) for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("One of the elements is not an X509Extension") # TODO push can fail (here and elsewhere) _lib.sk_X509_EXTENSION_push(stack, ext._extension) add_result = _lib.X509_REQ_add_extensions(self._req, stack) _openssl_assert(add_result == 1)
def add_extensions(self, extensions): """ Add extensions to the certificate signing request. :param extensions: The X.509 extensions to add. :type extensions: iterable of :py:class:`X509Extension` :return: ``None`` """ stack = _lib.sk_X509_EXTENSION_new_null() _openssl_assert(stack != _ffi.NULL) stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free) for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("One of the elements is not an X509Extension") # TODO push can fail (here and elsewhere) _lib.sk_X509_EXTENSION_push(stack, ext._extension) add_result = _lib.X509_REQ_add_extensions(self._req, stack) _openssl_assert(add_result == 1)
[ "Add", "extensions", "to", "the", "certificate", "signing", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L965-L986
[ "def", "add_extensions", "(", "self", ",", "extensions", ")", ":", "stack", "=", "_lib", ".", "sk_X509_EXTENSION_new_null", "(", ")", "_openssl_assert", "(", "stack", "!=", "_ffi", ".", "NULL", ")", "stack", "=", "_ffi", ".", "gc", "(", "stack", ",", "_lib", ".", "sk_X509_EXTENSION_free", ")", "for", "ext", "in", "extensions", ":", "if", "not", "isinstance", "(", "ext", ",", "X509Extension", ")", ":", "raise", "ValueError", "(", "\"One of the elements is not an X509Extension\"", ")", "# TODO push can fail (here and elsewhere)", "_lib", ".", "sk_X509_EXTENSION_push", "(", "stack", ",", "ext", ".", "_extension", ")", "add_result", "=", "_lib", ".", "X509_REQ_add_extensions", "(", "self", ".", "_req", ",", "stack", ")", "_openssl_assert", "(", "add_result", "==", "1", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.get_extensions
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
src/OpenSSL/crypto.py
def get_extensions(self): """ 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 """ exts = [] native_exts_obj = _lib.X509_REQ_get_extensions(self._req) for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)): ext = X509Extension.__new__(X509Extension) ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i) exts.append(ext) return exts
def get_extensions(self): """ 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 """ exts = [] native_exts_obj = _lib.X509_REQ_get_extensions(self._req) for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)): ext = X509Extension.__new__(X509Extension) ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i) exts.append(ext) return exts
[ "Get", "X", ".", "509", "extensions", "in", "the", "certificate", "signing", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L988-L1003
[ "def", "get_extensions", "(", "self", ")", ":", "exts", "=", "[", "]", "native_exts_obj", "=", "_lib", ".", "X509_REQ_get_extensions", "(", "self", ".", "_req", ")", "for", "i", "in", "range", "(", "_lib", ".", "sk_X509_EXTENSION_num", "(", "native_exts_obj", ")", ")", ":", "ext", "=", "X509Extension", ".", "__new__", "(", "X509Extension", ")", "ext", ".", "_extension", "=", "_lib", ".", "sk_X509_EXTENSION_value", "(", "native_exts_obj", ",", "i", ")", "exts", ".", "append", "(", "ext", ")", "return", "exts" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Req.verify
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.
src/OpenSSL/crypto.py
def verify(self, pkey): """ 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. """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") result = _lib.X509_REQ_verify(self._req, pkey._pkey) if result <= 0: _raise_current_error() return result
def verify(self, pkey): """ 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. """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") result = _lib.X509_REQ_verify(self._req, pkey._pkey) if result <= 0: _raise_current_error() return result
[ "Verifies", "the", "signature", "on", "this", "certificate", "signing", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1029-L1048
[ "def", "verify", "(", "self", ",", "pkey", ")", ":", "if", "not", "isinstance", "(", "pkey", ",", "PKey", ")", ":", "raise", "TypeError", "(", "\"pkey must be a PKey instance\"", ")", "result", "=", "_lib", ".", "X509_REQ_verify", "(", "self", ".", "_req", ",", "pkey", ".", "_pkey", ")", "if", "result", "<=", "0", ":", "_raise_current_error", "(", ")", "return", "result" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.to_cryptography
Export as a ``cryptography`` certificate. :rtype: ``cryptography.x509.Certificate`` .. versionadded:: 17.1.0
src/OpenSSL/crypto.py
def to_cryptography(self): """ Export as a ``cryptography`` certificate. :rtype: ``cryptography.x509.Certificate`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import _Certificate backend = _get_backend() return _Certificate(backend, self._x509)
def to_cryptography(self): """ Export as a ``cryptography`` certificate. :rtype: ``cryptography.x509.Certificate`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import _Certificate backend = _get_backend() return _Certificate(backend, self._x509)
[ "Export", "as", "a", "cryptography", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1071-L1081
[ "def", "to_cryptography", "(", "self", ")", ":", "from", "cryptography", ".", "hazmat", ".", "backends", ".", "openssl", ".", "x509", "import", "_Certificate", "backend", "=", "_get_backend", "(", ")", "return", "_Certificate", "(", "backend", ",", "self", ".", "_x509", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.from_cryptography
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
src/OpenSSL/crypto.py
def from_cryptography(cls, crypto_cert): """ 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(crypto_cert, x509.Certificate): raise TypeError("Must be a certificate") cert = cls() cert._x509 = crypto_cert._x509 return cert
def from_cryptography(cls, crypto_cert): """ 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(crypto_cert, x509.Certificate): raise TypeError("Must be a certificate") cert = cls() cert._x509 = crypto_cert._x509 return cert
[ "Construct", "based", "on", "a", "cryptography", "*", "crypto_cert", "*", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1084-L1100
[ "def", "from_cryptography", "(", "cls", ",", "crypto_cert", ")", ":", "if", "not", "isinstance", "(", "crypto_cert", ",", "x509", ".", "Certificate", ")", ":", "raise", "TypeError", "(", "\"Must be a certificate\"", ")", "cert", "=", "cls", "(", ")", "cert", ".", "_x509", "=", "crypto_cert", ".", "_x509", "return", "cert" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.set_version
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``
src/OpenSSL/crypto.py
def set_version(self, version): """ 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`` """ if not isinstance(version, int): raise TypeError("version must be an integer") _lib.X509_set_version(self._x509, version)
def set_version(self, version): """ 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`` """ if not isinstance(version, int): raise TypeError("version must be an integer") _lib.X509_set_version(self._x509, version)
[ "Set", "the", "version", "number", "of", "the", "certificate", ".", "Note", "that", "the", "version", "value", "is", "zero", "-", "based", "eg", ".", "a", "value", "of", "0", "is", "V1", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1102-L1115
[ "def", "set_version", "(", "self", ",", "version", ")", ":", "if", "not", "isinstance", "(", "version", ",", "int", ")", ":", "raise", "TypeError", "(", "\"version must be an integer\"", ")", "_lib", ".", "X509_set_version", "(", "self", ".", "_x509", ",", "version", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.get_pubkey
Get the public key of the certificate. :return: The public key. :rtype: :py:class:`PKey`
src/OpenSSL/crypto.py
def get_pubkey(self): """ Get the public key of the certificate. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.X509_get_pubkey(self._x509) if pkey._pkey == _ffi.NULL: _raise_current_error() pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
def get_pubkey(self): """ Get the public key of the certificate. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.X509_get_pubkey(self._x509) if pkey._pkey == _ffi.NULL: _raise_current_error() pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
[ "Get", "the", "public", "key", "of", "the", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1126-L1139
[ "def", "get_pubkey", "(", "self", ")", ":", "pkey", "=", "PKey", ".", "__new__", "(", "PKey", ")", "pkey", ".", "_pkey", "=", "_lib", ".", "X509_get_pubkey", "(", "self", ".", "_x509", ")", "if", "pkey", ".", "_pkey", "==", "_ffi", ".", "NULL", ":", "_raise_current_error", "(", ")", "pkey", ".", "_pkey", "=", "_ffi", ".", "gc", "(", "pkey", ".", "_pkey", ",", "_lib", ".", "EVP_PKEY_free", ")", "pkey", ".", "_only_public", "=", "True", "return", "pkey" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.set_pubkey
Set the public key of the certificate. :param pkey: The public key. :type pkey: :py:class:`PKey` :return: :py:data:`None`
src/OpenSSL/crypto.py
def set_pubkey(self, pkey): """ 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): raise TypeError("pkey must be a PKey instance") set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey) _openssl_assert(set_result == 1)
def set_pubkey(self, pkey): """ 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): raise TypeError("pkey must be a PKey instance") set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey) _openssl_assert(set_result == 1)
[ "Set", "the", "public", "key", "of", "the", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1141-L1154
[ "def", "set_pubkey", "(", "self", ",", "pkey", ")", ":", "if", "not", "isinstance", "(", "pkey", ",", "PKey", ")", ":", "raise", "TypeError", "(", "\"pkey must be a PKey instance\"", ")", "set_result", "=", "_lib", ".", "X509_set_pubkey", "(", "self", ".", "_x509", ",", "pkey", ".", "_pkey", ")", "_openssl_assert", "(", "set_result", "==", "1", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.sign
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`
src/OpenSSL/crypto.py
def sign(self, pkey, digest): """ 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` """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") if pkey._only_public: raise ValueError("Key only has public part") if not pkey._initialized: raise ValueError("Key is uninitialized") evp_md = _lib.EVP_get_digestbyname(_byte_string(digest)) if evp_md == _ffi.NULL: raise ValueError("No such digest method") sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md) _openssl_assert(sign_result > 0)
def sign(self, pkey, digest): """ 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` """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") if pkey._only_public: raise ValueError("Key only has public part") if not pkey._initialized: raise ValueError("Key is uninitialized") evp_md = _lib.EVP_get_digestbyname(_byte_string(digest)) if evp_md == _ffi.NULL: raise ValueError("No such digest method") sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md) _openssl_assert(sign_result > 0)
[ "Sign", "the", "certificate", "with", "this", "key", "and", "digest", "type", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1156-L1182
[ "def", "sign", "(", "self", ",", "pkey", ",", "digest", ")", ":", "if", "not", "isinstance", "(", "pkey", ",", "PKey", ")", ":", "raise", "TypeError", "(", "\"pkey must be a PKey instance\"", ")", "if", "pkey", ".", "_only_public", ":", "raise", "ValueError", "(", "\"Key only has public part\"", ")", "if", "not", "pkey", ".", "_initialized", ":", "raise", "ValueError", "(", "\"Key is uninitialized\"", ")", "evp_md", "=", "_lib", ".", "EVP_get_digestbyname", "(", "_byte_string", "(", "digest", ")", ")", "if", "evp_md", "==", "_ffi", ".", "NULL", ":", "raise", "ValueError", "(", "\"No such digest method\"", ")", "sign_result", "=", "_lib", ".", "X509_sign", "(", "self", ".", "_x509", ",", "pkey", ".", "_pkey", ",", "evp_md", ")", "_openssl_assert", "(", "sign_result", ">", "0", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.get_signature_algorithm
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
src/OpenSSL/crypto.py
def get_signature_algorithm(self): """ 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 """ algor = _lib.X509_get0_tbs_sigalg(self._x509) nid = _lib.OBJ_obj2nid(algor.algorithm) if nid == _lib.NID_undef: raise ValueError("Undefined signature algorithm") return _ffi.string(_lib.OBJ_nid2ln(nid))
def get_signature_algorithm(self): """ 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 """ algor = _lib.X509_get0_tbs_sigalg(self._x509) nid = _lib.OBJ_obj2nid(algor.algorithm) if nid == _lib.NID_undef: raise ValueError("Undefined signature algorithm") return _ffi.string(_lib.OBJ_nid2ln(nid))
[ "Return", "the", "signature", "algorithm", "used", "in", "the", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1184-L1199
[ "def", "get_signature_algorithm", "(", "self", ")", ":", "algor", "=", "_lib", ".", "X509_get0_tbs_sigalg", "(", "self", ".", "_x509", ")", "nid", "=", "_lib", ".", "OBJ_obj2nid", "(", "algor", ".", "algorithm", ")", "if", "nid", "==", "_lib", ".", "NID_undef", ":", "raise", "ValueError", "(", "\"Undefined signature algorithm\"", ")", "return", "_ffi", ".", "string", "(", "_lib", ".", "OBJ_nid2ln", "(", "nid", ")", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.digest
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`
src/OpenSSL/crypto.py
def digest(self, digest_name): """ 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` """ digest = _lib.EVP_get_digestbyname(_byte_string(digest_name)) if digest == _ffi.NULL: raise ValueError("No such digest method") result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE) result_length = _ffi.new("unsigned int[]", 1) result_length[0] = len(result_buffer) digest_result = _lib.X509_digest( self._x509, digest, result_buffer, result_length) _openssl_assert(digest_result == 1) return b":".join([ b16encode(ch).upper() for ch in _ffi.buffer(result_buffer, result_length[0])])
def digest(self, digest_name): """ 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` """ digest = _lib.EVP_get_digestbyname(_byte_string(digest_name)) if digest == _ffi.NULL: raise ValueError("No such digest method") result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE) result_length = _ffi.new("unsigned int[]", 1) result_length[0] = len(result_buffer) digest_result = _lib.X509_digest( self._x509, digest, result_buffer, result_length) _openssl_assert(digest_result == 1) return b":".join([ b16encode(ch).upper() for ch in _ffi.buffer(result_buffer, result_length[0])])
[ "Return", "the", "digest", "of", "the", "X509", "object", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1201-L1226
[ "def", "digest", "(", "self", ",", "digest_name", ")", ":", "digest", "=", "_lib", ".", "EVP_get_digestbyname", "(", "_byte_string", "(", "digest_name", ")", ")", "if", "digest", "==", "_ffi", ".", "NULL", ":", "raise", "ValueError", "(", "\"No such digest method\"", ")", "result_buffer", "=", "_ffi", ".", "new", "(", "\"unsigned char[]\"", ",", "_lib", ".", "EVP_MAX_MD_SIZE", ")", "result_length", "=", "_ffi", ".", "new", "(", "\"unsigned int[]\"", ",", "1", ")", "result_length", "[", "0", "]", "=", "len", "(", "result_buffer", ")", "digest_result", "=", "_lib", ".", "X509_digest", "(", "self", ".", "_x509", ",", "digest", ",", "result_buffer", ",", "result_length", ")", "_openssl_assert", "(", "digest_result", "==", "1", ")", "return", "b\":\"", ".", "join", "(", "[", "b16encode", "(", "ch", ")", ".", "upper", "(", ")", "for", "ch", "in", "_ffi", ".", "buffer", "(", "result_buffer", ",", "result_length", "[", "0", "]", ")", "]", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.set_serial_number
Set the serial number of the certificate. :param serial: The new serial number. :type serial: :py:class:`int` :return: :py:data`None`
src/OpenSSL/crypto.py
def set_serial_number(self, serial): """ Set the serial number of the certificate. :param serial: The new serial number. :type serial: :py:class:`int` :return: :py:data`None` """ if not isinstance(serial, _integer_types): raise TypeError("serial must be an integer") hex_serial = hex(serial)[2:] if not isinstance(hex_serial, bytes): hex_serial = hex_serial.encode('ascii') bignum_serial = _ffi.new("BIGNUM**") # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like # it. If bignum is still NULL after this call, then the return value # is actually the result. I hope. -exarkun small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial) if bignum_serial[0] == _ffi.NULL: set_result = _lib.ASN1_INTEGER_set( _lib.X509_get_serialNumber(self._x509), small_serial) if set_result: # TODO Not tested _raise_current_error() else: asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL) _lib.BN_free(bignum_serial[0]) if asn1_serial == _ffi.NULL: # TODO Not tested _raise_current_error() asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free) set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial) _openssl_assert(set_result == 1)
def set_serial_number(self, serial): """ Set the serial number of the certificate. :param serial: The new serial number. :type serial: :py:class:`int` :return: :py:data`None` """ if not isinstance(serial, _integer_types): raise TypeError("serial must be an integer") hex_serial = hex(serial)[2:] if not isinstance(hex_serial, bytes): hex_serial = hex_serial.encode('ascii') bignum_serial = _ffi.new("BIGNUM**") # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like # it. If bignum is still NULL after this call, then the return value # is actually the result. I hope. -exarkun small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial) if bignum_serial[0] == _ffi.NULL: set_result = _lib.ASN1_INTEGER_set( _lib.X509_get_serialNumber(self._x509), small_serial) if set_result: # TODO Not tested _raise_current_error() else: asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL) _lib.BN_free(bignum_serial[0]) if asn1_serial == _ffi.NULL: # TODO Not tested _raise_current_error() asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free) set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial) _openssl_assert(set_result == 1)
[ "Set", "the", "serial", "number", "of", "the", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1237-L1274
[ "def", "set_serial_number", "(", "self", ",", "serial", ")", ":", "if", "not", "isinstance", "(", "serial", ",", "_integer_types", ")", ":", "raise", "TypeError", "(", "\"serial must be an integer\"", ")", "hex_serial", "=", "hex", "(", "serial", ")", "[", "2", ":", "]", "if", "not", "isinstance", "(", "hex_serial", ",", "bytes", ")", ":", "hex_serial", "=", "hex_serial", ".", "encode", "(", "'ascii'", ")", "bignum_serial", "=", "_ffi", ".", "new", "(", "\"BIGNUM**\"", ")", "# BN_hex2bn stores the result in &bignum. Unless it doesn't feel like", "# it. If bignum is still NULL after this call, then the return value", "# is actually the result. I hope. -exarkun", "small_serial", "=", "_lib", ".", "BN_hex2bn", "(", "bignum_serial", ",", "hex_serial", ")", "if", "bignum_serial", "[", "0", "]", "==", "_ffi", ".", "NULL", ":", "set_result", "=", "_lib", ".", "ASN1_INTEGER_set", "(", "_lib", ".", "X509_get_serialNumber", "(", "self", ".", "_x509", ")", ",", "small_serial", ")", "if", "set_result", ":", "# TODO Not tested", "_raise_current_error", "(", ")", "else", ":", "asn1_serial", "=", "_lib", ".", "BN_to_ASN1_INTEGER", "(", "bignum_serial", "[", "0", "]", ",", "_ffi", ".", "NULL", ")", "_lib", ".", "BN_free", "(", "bignum_serial", "[", "0", "]", ")", "if", "asn1_serial", "==", "_ffi", ".", "NULL", ":", "# TODO Not tested", "_raise_current_error", "(", ")", "asn1_serial", "=", "_ffi", ".", "gc", "(", "asn1_serial", ",", "_lib", ".", "ASN1_INTEGER_free", ")", "set_result", "=", "_lib", ".", "X509_set_serialNumber", "(", "self", ".", "_x509", ",", "asn1_serial", ")", "_openssl_assert", "(", "set_result", "==", "1", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.get_serial_number
Return the serial number of this certificate. :return: The serial number. :rtype: int
src/OpenSSL/crypto.py
def get_serial_number(self): """ Return the serial number of this certificate. :return: The serial number. :rtype: int """ asn1_serial = _lib.X509_get_serialNumber(self._x509) bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL) try: hex_serial = _lib.BN_bn2hex(bignum_serial) try: hexstring_serial = _ffi.string(hex_serial) serial = int(hexstring_serial, 16) return serial finally: _lib.OPENSSL_free(hex_serial) finally: _lib.BN_free(bignum_serial)
def get_serial_number(self): """ Return the serial number of this certificate. :return: The serial number. :rtype: int """ asn1_serial = _lib.X509_get_serialNumber(self._x509) bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL) try: hex_serial = _lib.BN_bn2hex(bignum_serial) try: hexstring_serial = _ffi.string(hex_serial) serial = int(hexstring_serial, 16) return serial finally: _lib.OPENSSL_free(hex_serial) finally: _lib.BN_free(bignum_serial)
[ "Return", "the", "serial", "number", "of", "this", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1276-L1294
[ "def", "get_serial_number", "(", "self", ")", ":", "asn1_serial", "=", "_lib", ".", "X509_get_serialNumber", "(", "self", ".", "_x509", ")", "bignum_serial", "=", "_lib", ".", "ASN1_INTEGER_to_BN", "(", "asn1_serial", ",", "_ffi", ".", "NULL", ")", "try", ":", "hex_serial", "=", "_lib", ".", "BN_bn2hex", "(", "bignum_serial", ")", "try", ":", "hexstring_serial", "=", "_ffi", ".", "string", "(", "hex_serial", ")", "serial", "=", "int", "(", "hexstring_serial", ",", "16", ")", "return", "serial", "finally", ":", "_lib", ".", "OPENSSL_free", "(", "hex_serial", ")", "finally", ":", "_lib", ".", "BN_free", "(", "bignum_serial", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.gmtime_adj_notAfter
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``
src/OpenSSL/crypto.py
def gmtime_adj_notAfter(self, amount): """ 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): raise TypeError("amount must be an integer") notAfter = _lib.X509_get_notAfter(self._x509) _lib.X509_gmtime_adj(notAfter, amount)
def gmtime_adj_notAfter(self, amount): """ 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): raise TypeError("amount must be an integer") notAfter = _lib.X509_get_notAfter(self._x509) _lib.X509_gmtime_adj(notAfter, amount)
[ "Adjust", "the", "time", "stamp", "on", "which", "the", "certificate", "stops", "being", "valid", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1296-L1308
[ "def", "gmtime_adj_notAfter", "(", "self", ",", "amount", ")", ":", "if", "not", "isinstance", "(", "amount", ",", "int", ")", ":", "raise", "TypeError", "(", "\"amount must be an integer\"", ")", "notAfter", "=", "_lib", ".", "X509_get_notAfter", "(", "self", ".", "_x509", ")", "_lib", ".", "X509_gmtime_adj", "(", "notAfter", ",", "amount", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.gmtime_adj_notBefore
Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None``
src/OpenSSL/crypto.py
def gmtime_adj_notBefore(self, amount): """ Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None`` """ if not isinstance(amount, int): raise TypeError("amount must be an integer") notBefore = _lib.X509_get_notBefore(self._x509) _lib.X509_gmtime_adj(notBefore, amount)
def gmtime_adj_notBefore(self, amount): """ Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None`` """ if not isinstance(amount, int): raise TypeError("amount must be an integer") notBefore = _lib.X509_get_notBefore(self._x509) _lib.X509_gmtime_adj(notBefore, amount)
[ "Adjust", "the", "timestamp", "on", "which", "the", "certificate", "starts", "being", "valid", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1310-L1321
[ "def", "gmtime_adj_notBefore", "(", "self", ",", "amount", ")", ":", "if", "not", "isinstance", "(", "amount", ",", "int", ")", ":", "raise", "TypeError", "(", "\"amount must be an integer\"", ")", "notBefore", "=", "_lib", ".", "X509_get_notBefore", "(", "self", ".", "_x509", ")", "_lib", ".", "X509_gmtime_adj", "(", "notBefore", ",", "amount", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.has_expired
Check whether the certificate has expired. :return: ``True`` if the certificate has expired, ``False`` otherwise. :rtype: bool
src/OpenSSL/crypto.py
def has_expired(self): """ Check whether the certificate has expired. :return: ``True`` if the certificate has expired, ``False`` otherwise. :rtype: bool """ time_string = _native(self.get_notAfter()) not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ") return not_after < datetime.datetime.utcnow()
def has_expired(self): """ Check whether the certificate has expired. :return: ``True`` if the certificate has expired, ``False`` otherwise. :rtype: bool """ time_string = _native(self.get_notAfter()) not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ") return not_after < datetime.datetime.utcnow()
[ "Check", "whether", "the", "certificate", "has", "expired", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1323-L1333
[ "def", "has_expired", "(", "self", ")", ":", "time_string", "=", "_native", "(", "self", ".", "get_notAfter", "(", ")", ")", "not_after", "=", "datetime", ".", "datetime", ".", "strptime", "(", "time_string", ",", "\"%Y%m%d%H%M%SZ\"", ")", "return", "not_after", "<", "datetime", ".", "datetime", ".", "utcnow", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.get_issuer
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`
src/OpenSSL/crypto.py
def get_issuer(self): """ 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` """ name = self._get_name(_lib.X509_get_issuer_name) self._issuer_invalidator.add(name) return name
def get_issuer(self): """ 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` """ name = self._get_name(_lib.X509_get_issuer_name) self._issuer_invalidator.add(name) return name
[ "Return", "the", "issuer", "of", "this", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1410-L1424
[ "def", "get_issuer", "(", "self", ")", ":", "name", "=", "self", ".", "_get_name", "(", "_lib", ".", "X509_get_issuer_name", ")", "self", ".", "_issuer_invalidator", ".", "add", "(", "name", ")", "return", "name" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.set_issuer
Set the issuer of this certificate. :param issuer: The issuer. :type issuer: :py:class:`X509Name` :return: ``None``
src/OpenSSL/crypto.py
def set_issuer(self, issuer): """ Set the issuer of this certificate. :param issuer: The issuer. :type issuer: :py:class:`X509Name` :return: ``None`` """ self._set_name(_lib.X509_set_issuer_name, issuer) self._issuer_invalidator.clear()
def set_issuer(self, issuer): """ Set the issuer of this certificate. :param issuer: The issuer. :type issuer: :py:class:`X509Name` :return: ``None`` """ self._set_name(_lib.X509_set_issuer_name, issuer) self._issuer_invalidator.clear()
[ "Set", "the", "issuer", "of", "this", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1426-L1436
[ "def", "set_issuer", "(", "self", ",", "issuer", ")", ":", "self", ".", "_set_name", "(", "_lib", ".", "X509_set_issuer_name", ",", "issuer", ")", "self", ".", "_issuer_invalidator", ".", "clear", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.get_subject
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`
src/OpenSSL/crypto.py
def get_subject(self): """ 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` """ name = self._get_name(_lib.X509_get_subject_name) self._subject_invalidator.add(name) return name
def get_subject(self): """ 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` """ name = self._get_name(_lib.X509_get_subject_name) self._subject_invalidator.add(name) return name
[ "Return", "the", "subject", "of", "this", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1438-L1452
[ "def", "get_subject", "(", "self", ")", ":", "name", "=", "self", ".", "_get_name", "(", "_lib", ".", "X509_get_subject_name", ")", "self", ".", "_subject_invalidator", ".", "add", "(", "name", ")", "return", "name" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.set_subject
Set the subject of this certificate. :param subject: The subject. :type subject: :py:class:`X509Name` :return: ``None``
src/OpenSSL/crypto.py
def set_subject(self, subject): """ Set the subject of this certificate. :param subject: The subject. :type subject: :py:class:`X509Name` :return: ``None`` """ self._set_name(_lib.X509_set_subject_name, subject) self._subject_invalidator.clear()
def set_subject(self, subject): """ Set the subject of this certificate. :param subject: The subject. :type subject: :py:class:`X509Name` :return: ``None`` """ self._set_name(_lib.X509_set_subject_name, subject) self._subject_invalidator.clear()
[ "Set", "the", "subject", "of", "this", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1454-L1464
[ "def", "set_subject", "(", "self", ",", "subject", ")", ":", "self", ".", "_set_name", "(", "_lib", ".", "X509_set_subject_name", ",", "subject", ")", "self", ".", "_subject_invalidator", ".", "clear", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.add_extensions
Add extensions to the certificate. :param extensions: The extensions to add. :type extensions: An iterable of :py:class:`X509Extension` objects. :return: ``None``
src/OpenSSL/crypto.py
def add_extensions(self, extensions): """ Add extensions to the certificate. :param extensions: The extensions to add. :type extensions: An iterable of :py:class:`X509Extension` objects. :return: ``None`` """ for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("One of the elements is not an X509Extension") add_result = _lib.X509_add_ext(self._x509, ext._extension, -1) if not add_result: _raise_current_error()
def add_extensions(self, extensions): """ Add extensions to the certificate. :param extensions: The extensions to add. :type extensions: An iterable of :py:class:`X509Extension` objects. :return: ``None`` """ for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("One of the elements is not an X509Extension") add_result = _lib.X509_add_ext(self._x509, ext._extension, -1) if not add_result: _raise_current_error()
[ "Add", "extensions", "to", "the", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1477-L1491
[ "def", "add_extensions", "(", "self", ",", "extensions", ")", ":", "for", "ext", "in", "extensions", ":", "if", "not", "isinstance", "(", "ext", ",", "X509Extension", ")", ":", "raise", "ValueError", "(", "\"One of the elements is not an X509Extension\"", ")", "add_result", "=", "_lib", ".", "X509_add_ext", "(", "self", ".", "_x509", ",", "ext", ".", "_extension", ",", "-", "1", ")", "if", "not", "add_result", ":", "_raise_current_error", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509.get_extension
Get a specific extension of the certificate by index. Extensions on a certificate are kept in order. The index parameter selects which extension will be returned. :param int index: The index of the extension to retrieve. :return: The extension at the specified index. :rtype: :py:class:`X509Extension` :raises IndexError: If the extension index was out of bounds. .. versionadded:: 0.12
src/OpenSSL/crypto.py
def get_extension(self, index): """ Get a specific extension of the certificate by index. Extensions on a certificate are kept in order. The index parameter selects which extension will be returned. :param int index: The index of the extension to retrieve. :return: The extension at the specified index. :rtype: :py:class:`X509Extension` :raises IndexError: If the extension index was out of bounds. .. versionadded:: 0.12 """ ext = X509Extension.__new__(X509Extension) ext._extension = _lib.X509_get_ext(self._x509, index) if ext._extension == _ffi.NULL: raise IndexError("extension index out of bounds") extension = _lib.X509_EXTENSION_dup(ext._extension) ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free) return ext
def get_extension(self, index): """ Get a specific extension of the certificate by index. Extensions on a certificate are kept in order. The index parameter selects which extension will be returned. :param int index: The index of the extension to retrieve. :return: The extension at the specified index. :rtype: :py:class:`X509Extension` :raises IndexError: If the extension index was out of bounds. .. versionadded:: 0.12 """ ext = X509Extension.__new__(X509Extension) ext._extension = _lib.X509_get_ext(self._x509, index) if ext._extension == _ffi.NULL: raise IndexError("extension index out of bounds") extension = _lib.X509_EXTENSION_dup(ext._extension) ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free) return ext
[ "Get", "a", "specific", "extension", "of", "the", "certificate", "by", "index", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1493-L1514
[ "def", "get_extension", "(", "self", ",", "index", ")", ":", "ext", "=", "X509Extension", ".", "__new__", "(", "X509Extension", ")", "ext", ".", "_extension", "=", "_lib", ".", "X509_get_ext", "(", "self", ".", "_x509", ",", "index", ")", "if", "ext", ".", "_extension", "==", "_ffi", ".", "NULL", ":", "raise", "IndexError", "(", "\"extension index out of bounds\"", ")", "extension", "=", "_lib", ".", "X509_EXTENSION_dup", "(", "ext", ".", "_extension", ")", "ext", ".", "_extension", "=", "_ffi", ".", "gc", "(", "extension", ",", "_lib", ".", "X509_EXTENSION_free", ")", "return", "ext" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Store.add_cert
Adds a trusted certificate to this store. Adding a certificate with this method adds this certificate as a *trusted* certificate. :param X509 cert: The certificate to add to this store. :raises TypeError: If the certificate is not an :class:`X509`. :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your certificate. :return: ``None`` if the certificate was added successfully.
src/OpenSSL/crypto.py
def add_cert(self, cert): """ Adds a trusted certificate to this store. Adding a certificate with this method adds this certificate as a *trusted* certificate. :param X509 cert: The certificate to add to this store. :raises TypeError: If the certificate is not an :class:`X509`. :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your certificate. :return: ``None`` if the certificate was added successfully. """ if not isinstance(cert, X509): raise TypeError() # As of OpenSSL 1.1.0i adding the same cert to the store more than # once doesn't cause an error. Accordingly, this code now silences # the error for OpenSSL < 1.1.0i as well. if _lib.X509_STORE_add_cert(self._store, cert._x509) == 0: code = _lib.ERR_peek_error() err_reason = _lib.ERR_GET_REASON(code) _openssl_assert( err_reason == _lib.X509_R_CERT_ALREADY_IN_HASH_TABLE ) _lib.ERR_clear_error()
def add_cert(self, cert): """ Adds a trusted certificate to this store. Adding a certificate with this method adds this certificate as a *trusted* certificate. :param X509 cert: The certificate to add to this store. :raises TypeError: If the certificate is not an :class:`X509`. :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your certificate. :return: ``None`` if the certificate was added successfully. """ if not isinstance(cert, X509): raise TypeError() # As of OpenSSL 1.1.0i adding the same cert to the store more than # once doesn't cause an error. Accordingly, this code now silences # the error for OpenSSL < 1.1.0i as well. if _lib.X509_STORE_add_cert(self._store, cert._x509) == 0: code = _lib.ERR_peek_error() err_reason = _lib.ERR_GET_REASON(code) _openssl_assert( err_reason == _lib.X509_R_CERT_ALREADY_IN_HASH_TABLE ) _lib.ERR_clear_error()
[ "Adds", "a", "trusted", "certificate", "to", "this", "store", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1558-L1586
[ "def", "add_cert", "(", "self", ",", "cert", ")", ":", "if", "not", "isinstance", "(", "cert", ",", "X509", ")", ":", "raise", "TypeError", "(", ")", "# As of OpenSSL 1.1.0i adding the same cert to the store more than", "# once doesn't cause an error. Accordingly, this code now silences", "# the error for OpenSSL < 1.1.0i as well.", "if", "_lib", ".", "X509_STORE_add_cert", "(", "self", ".", "_store", ",", "cert", ".", "_x509", ")", "==", "0", ":", "code", "=", "_lib", ".", "ERR_peek_error", "(", ")", "err_reason", "=", "_lib", ".", "ERR_GET_REASON", "(", "code", ")", "_openssl_assert", "(", "err_reason", "==", "_lib", ".", "X509_R_CERT_ALREADY_IN_HASH_TABLE", ")", "_lib", ".", "ERR_clear_error", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Store.add_crl
Add a certificate revocation list to this store. The certificate revocation lists added to a store will only be used if the associated flags are configured to check certificate revocation lists. .. versionadded:: 16.1.0 :param CRL crl: The certificate revocation list to add to this store. :return: ``None`` if the certificate revocation list was added successfully.
src/OpenSSL/crypto.py
def add_crl(self, crl): """ Add a certificate revocation list to this store. The certificate revocation lists added to a store will only be used if the associated flags are configured to check certificate revocation lists. .. versionadded:: 16.1.0 :param CRL crl: The certificate revocation list to add to this store. :return: ``None`` if the certificate revocation list was added successfully. """ _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
def add_crl(self, crl): """ Add a certificate revocation list to this store. The certificate revocation lists added to a store will only be used if the associated flags are configured to check certificate revocation lists. .. versionadded:: 16.1.0 :param CRL crl: The certificate revocation list to add to this store. :return: ``None`` if the certificate revocation list was added successfully. """ _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
[ "Add", "a", "certificate", "revocation", "list", "to", "this", "store", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1588-L1602
[ "def", "add_crl", "(", "self", ",", "crl", ")", ":", "_openssl_assert", "(", "_lib", ".", "X509_STORE_add_crl", "(", "self", ".", "_store", ",", "crl", ".", "_crl", ")", "!=", "0", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509Store.set_time
Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param datetime vfy_time: The verification time to set on this store. :return: ``None`` if the verification time was successfully set.
src/OpenSSL/crypto.py
def set_time(self, vfy_time): """ Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param datetime vfy_time: The verification time to set on this store. :return: ``None`` if the verification time was successfully set. """ param = _lib.X509_VERIFY_PARAM_new() param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free) _lib.X509_VERIFY_PARAM_set_time(param, int(vfy_time.strftime('%s'))) _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
def set_time(self, vfy_time): """ Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param datetime vfy_time: The verification time to set on this store. :return: ``None`` if the verification time was successfully set. """ param = _lib.X509_VERIFY_PARAM_new() param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free) _lib.X509_VERIFY_PARAM_set_time(param, int(vfy_time.strftime('%s'))) _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
[ "Set", "the", "time", "against", "which", "the", "certificates", "are", "verified", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1628-L1648
[ "def", "set_time", "(", "self", ",", "vfy_time", ")", ":", "param", "=", "_lib", ".", "X509_VERIFY_PARAM_new", "(", ")", "param", "=", "_ffi", ".", "gc", "(", "param", ",", "_lib", ".", "X509_VERIFY_PARAM_free", ")", "_lib", ".", "X509_VERIFY_PARAM_set_time", "(", "param", ",", "int", "(", "vfy_time", ".", "strftime", "(", "'%s'", ")", ")", ")", "_openssl_assert", "(", "_lib", ".", "X509_STORE_set1_param", "(", "self", ".", "_store", ",", "param", ")", "!=", "0", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509StoreContext._init
Set up the store context for a subsequent verification operation. Calling this method more than once without first calling :meth:`_cleanup` will leak memory.
src/OpenSSL/crypto.py
def _init(self): """ Set up the store context for a subsequent verification operation. Calling this method more than once without first calling :meth:`_cleanup` will leak memory. """ ret = _lib.X509_STORE_CTX_init( self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL ) if ret <= 0: _raise_current_error()
def _init(self): """ Set up the store context for a subsequent verification operation. Calling this method more than once without first calling :meth:`_cleanup` will leak memory. """ ret = _lib.X509_STORE_CTX_init( self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL ) if ret <= 0: _raise_current_error()
[ "Set", "up", "the", "store", "context", "for", "a", "subsequent", "verification", "operation", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1693-L1704
[ "def", "_init", "(", "self", ")", ":", "ret", "=", "_lib", ".", "X509_STORE_CTX_init", "(", "self", ".", "_store_ctx", ",", "self", ".", "_store", ".", "_store", ",", "self", ".", "_cert", ".", "_x509", ",", "_ffi", ".", "NULL", ")", "if", "ret", "<=", "0", ":", "_raise_current_error", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509StoreContext._exception_from_context
Convert an OpenSSL native context error failure into a Python exception. When a call to native OpenSSL X509_verify_cert fails, additional information about the failure can be obtained from the store context.
src/OpenSSL/crypto.py
def _exception_from_context(self): """ Convert an OpenSSL native context error failure into a Python exception. When a call to native OpenSSL X509_verify_cert fails, additional information about the failure can be obtained from the store context. """ errors = [ _lib.X509_STORE_CTX_get_error(self._store_ctx), _lib.X509_STORE_CTX_get_error_depth(self._store_ctx), _native(_ffi.string(_lib.X509_verify_cert_error_string( _lib.X509_STORE_CTX_get_error(self._store_ctx)))), ] # A context error should always be associated with a certificate, so we # expect this call to never return :class:`None`. _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx) _cert = _lib.X509_dup(_x509) pycert = X509._from_raw_x509_ptr(_cert) return X509StoreContextError(errors, pycert)
def _exception_from_context(self): """ Convert an OpenSSL native context error failure into a Python exception. When a call to native OpenSSL X509_verify_cert fails, additional information about the failure can be obtained from the store context. """ errors = [ _lib.X509_STORE_CTX_get_error(self._store_ctx), _lib.X509_STORE_CTX_get_error_depth(self._store_ctx), _native(_ffi.string(_lib.X509_verify_cert_error_string( _lib.X509_STORE_CTX_get_error(self._store_ctx)))), ] # A context error should always be associated with a certificate, so we # expect this call to never return :class:`None`. _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx) _cert = _lib.X509_dup(_x509) pycert = X509._from_raw_x509_ptr(_cert) return X509StoreContextError(errors, pycert)
[ "Convert", "an", "OpenSSL", "native", "context", "error", "failure", "into", "a", "Python", "exception", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1714-L1733
[ "def", "_exception_from_context", "(", "self", ")", ":", "errors", "=", "[", "_lib", ".", "X509_STORE_CTX_get_error", "(", "self", ".", "_store_ctx", ")", ",", "_lib", ".", "X509_STORE_CTX_get_error_depth", "(", "self", ".", "_store_ctx", ")", ",", "_native", "(", "_ffi", ".", "string", "(", "_lib", ".", "X509_verify_cert_error_string", "(", "_lib", ".", "X509_STORE_CTX_get_error", "(", "self", ".", "_store_ctx", ")", ")", ")", ")", ",", "]", "# A context error should always be associated with a certificate, so we", "# expect this call to never return :class:`None`.", "_x509", "=", "_lib", ".", "X509_STORE_CTX_get_current_cert", "(", "self", ".", "_store_ctx", ")", "_cert", "=", "_lib", ".", "X509_dup", "(", "_x509", ")", "pycert", "=", "X509", ".", "_from_raw_x509_ptr", "(", "_cert", ")", "return", "X509StoreContextError", "(", "errors", ",", "pycert", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
X509StoreContext.verify_certificate
Verify a certificate in a context. .. versionadded:: 0.15 :raises X509StoreContextError: If an error occurred when validating a certificate in the context. Sets ``certificate`` attribute to indicate which certificate caused the error.
src/OpenSSL/crypto.py
def verify_certificate(self): """ Verify a certificate in a context. .. versionadded:: 0.15 :raises X509StoreContextError: If an error occurred when validating a certificate in the context. Sets ``certificate`` attribute to indicate which certificate caused the error. """ # Always re-initialize the store context in case # :meth:`verify_certificate` is called multiple times. # # :meth:`_init` is called in :meth:`__init__` so _cleanup is called # before _init to ensure memory is not leaked. self._cleanup() self._init() ret = _lib.X509_verify_cert(self._store_ctx) self._cleanup() if ret <= 0: raise self._exception_from_context()
def verify_certificate(self): """ Verify a certificate in a context. .. versionadded:: 0.15 :raises X509StoreContextError: If an error occurred when validating a certificate in the context. Sets ``certificate`` attribute to indicate which certificate caused the error. """ # Always re-initialize the store context in case # :meth:`verify_certificate` is called multiple times. # # :meth:`_init` is called in :meth:`__init__` so _cleanup is called # before _init to ensure memory is not leaked. self._cleanup() self._init() ret = _lib.X509_verify_cert(self._store_ctx) self._cleanup() if ret <= 0: raise self._exception_from_context()
[ "Verify", "a", "certificate", "in", "a", "context", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1746-L1766
[ "def", "verify_certificate", "(", "self", ")", ":", "# Always re-initialize the store context in case", "# :meth:`verify_certificate` is called multiple times.", "#", "# :meth:`_init` is called in :meth:`__init__` so _cleanup is called", "# before _init to ensure memory is not leaked.", "self", ".", "_cleanup", "(", ")", "self", ".", "_init", "(", ")", "ret", "=", "_lib", ".", "X509_verify_cert", "(", "self", ".", "_store_ctx", ")", "self", ".", "_cleanup", "(", ")", "if", "ret", "<=", "0", ":", "raise", "self", ".", "_exception_from_context", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Revoked.set_serial
Set the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :param bytes hex_str: The new serial number. :return: ``None``
src/OpenSSL/crypto.py
def set_serial(self, hex_str): """ Set the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :param bytes hex_str: The new serial number. :return: ``None`` """ bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free) bignum_ptr = _ffi.new("BIGNUM**") bignum_ptr[0] = bignum_serial bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str) if not bn_result: raise ValueError("bad hex string") asn1_serial = _ffi.gc( _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL), _lib.ASN1_INTEGER_free) _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
def set_serial(self, hex_str): """ Set the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :param bytes hex_str: The new serial number. :return: ``None`` """ bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free) bignum_ptr = _ffi.new("BIGNUM**") bignum_ptr[0] = bignum_serial bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str) if not bn_result: raise ValueError("bad hex string") asn1_serial = _ffi.gc( _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL), _lib.ASN1_INTEGER_free) _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
[ "Set", "the", "serial", "number", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1933-L1954
[ "def", "set_serial", "(", "self", ",", "hex_str", ")", ":", "bignum_serial", "=", "_ffi", ".", "gc", "(", "_lib", ".", "BN_new", "(", ")", ",", "_lib", ".", "BN_free", ")", "bignum_ptr", "=", "_ffi", ".", "new", "(", "\"BIGNUM**\"", ")", "bignum_ptr", "[", "0", "]", "=", "bignum_serial", "bn_result", "=", "_lib", ".", "BN_hex2bn", "(", "bignum_ptr", ",", "hex_str", ")", "if", "not", "bn_result", ":", "raise", "ValueError", "(", "\"bad hex string\"", ")", "asn1_serial", "=", "_ffi", ".", "gc", "(", "_lib", ".", "BN_to_ASN1_INTEGER", "(", "bignum_serial", ",", "_ffi", ".", "NULL", ")", ",", "_lib", ".", "ASN1_INTEGER_free", ")", "_lib", ".", "X509_REVOKED_set_serialNumber", "(", "self", ".", "_revoked", ",", "asn1_serial", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Revoked.get_serial
Get the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :return: The serial number. :rtype: bytes
src/OpenSSL/crypto.py
def get_serial(self): """ Get the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :return: The serial number. :rtype: bytes """ bio = _new_mem_buf() asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked) _openssl_assert(asn1_int != _ffi.NULL) result = _lib.i2a_ASN1_INTEGER(bio, asn1_int) _openssl_assert(result >= 0) return _bio_to_string(bio)
def get_serial(self): """ Get the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :return: The serial number. :rtype: bytes """ bio = _new_mem_buf() asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked) _openssl_assert(asn1_int != _ffi.NULL) result = _lib.i2a_ASN1_INTEGER(bio, asn1_int) _openssl_assert(result >= 0) return _bio_to_string(bio)
[ "Get", "the", "serial", "number", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1956-L1972
[ "def", "get_serial", "(", "self", ")", ":", "bio", "=", "_new_mem_buf", "(", ")", "asn1_int", "=", "_lib", ".", "X509_REVOKED_get0_serialNumber", "(", "self", ".", "_revoked", ")", "_openssl_assert", "(", "asn1_int", "!=", "_ffi", ".", "NULL", ")", "result", "=", "_lib", ".", "i2a_ASN1_INTEGER", "(", "bio", ",", "asn1_int", ")", "_openssl_assert", "(", "result", ">=", "0", ")", "return", "_bio_to_string", "(", "bio", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Revoked.set_reason
Set the reason of this revocation. If :data:`reason` is ``None``, delete the reason instead. :param reason: The reason string. :type reason: :class:`bytes` or :class:`NoneType` :return: ``None`` .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons which you might pass to this method.
src/OpenSSL/crypto.py
def set_reason(self, reason): """ Set the reason of this revocation. If :data:`reason` is ``None``, delete the reason instead. :param reason: The reason string. :type reason: :class:`bytes` or :class:`NoneType` :return: ``None`` .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons which you might pass to this method. """ if reason is None: self._delete_reason() elif not isinstance(reason, bytes): raise TypeError("reason must be None or a byte string") else: reason = reason.lower().replace(b' ', b'') reason_code = [r.lower() for r in self._crl_reasons].index(reason) new_reason_ext = _lib.ASN1_ENUMERATED_new() _openssl_assert(new_reason_ext != _ffi.NULL) new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free) set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code) _openssl_assert(set_result != _ffi.NULL) self._delete_reason() add_result = _lib.X509_REVOKED_add1_ext_i2d( self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0) _openssl_assert(add_result == 1)
def set_reason(self, reason): """ Set the reason of this revocation. If :data:`reason` is ``None``, delete the reason instead. :param reason: The reason string. :type reason: :class:`bytes` or :class:`NoneType` :return: ``None`` .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons which you might pass to this method. """ if reason is None: self._delete_reason() elif not isinstance(reason, bytes): raise TypeError("reason must be None or a byte string") else: reason = reason.lower().replace(b' ', b'') reason_code = [r.lower() for r in self._crl_reasons].index(reason) new_reason_ext = _lib.ASN1_ENUMERATED_new() _openssl_assert(new_reason_ext != _ffi.NULL) new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free) set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code) _openssl_assert(set_result != _ffi.NULL) self._delete_reason() add_result = _lib.X509_REVOKED_add1_ext_i2d( self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0) _openssl_assert(add_result == 1)
[ "Set", "the", "reason", "of", "this", "revocation", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1983-L2017
[ "def", "set_reason", "(", "self", ",", "reason", ")", ":", "if", "reason", "is", "None", ":", "self", ".", "_delete_reason", "(", ")", "elif", "not", "isinstance", "(", "reason", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"reason must be None or a byte string\"", ")", "else", ":", "reason", "=", "reason", ".", "lower", "(", ")", ".", "replace", "(", "b' '", ",", "b''", ")", "reason_code", "=", "[", "r", ".", "lower", "(", ")", "for", "r", "in", "self", ".", "_crl_reasons", "]", ".", "index", "(", "reason", ")", "new_reason_ext", "=", "_lib", ".", "ASN1_ENUMERATED_new", "(", ")", "_openssl_assert", "(", "new_reason_ext", "!=", "_ffi", ".", "NULL", ")", "new_reason_ext", "=", "_ffi", ".", "gc", "(", "new_reason_ext", ",", "_lib", ".", "ASN1_ENUMERATED_free", ")", "set_result", "=", "_lib", ".", "ASN1_ENUMERATED_set", "(", "new_reason_ext", ",", "reason_code", ")", "_openssl_assert", "(", "set_result", "!=", "_ffi", ".", "NULL", ")", "self", ".", "_delete_reason", "(", ")", "add_result", "=", "_lib", ".", "X509_REVOKED_add1_ext_i2d", "(", "self", ".", "_revoked", ",", "_lib", ".", "NID_crl_reason", ",", "new_reason_ext", ",", "0", ",", "0", ")", "_openssl_assert", "(", "add_result", "==", "1", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Revoked.get_reason
Get the reason of this revocation. :return: The reason, or ``None`` if there is none. :rtype: bytes or NoneType .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons this method might return.
src/OpenSSL/crypto.py
def get_reason(self): """ Get the reason of this revocation. :return: The reason, or ``None`` if there is none. :rtype: bytes or NoneType .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons this method might return. """ for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)): ext = _lib.X509_REVOKED_get_ext(self._revoked, i) obj = _lib.X509_EXTENSION_get_object(ext) if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason: bio = _new_mem_buf() print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0) if not print_result: print_result = _lib.M_ASN1_OCTET_STRING_print( bio, _lib.X509_EXTENSION_get_data(ext) ) _openssl_assert(print_result != 0) return _bio_to_string(bio)
def get_reason(self): """ Get the reason of this revocation. :return: The reason, or ``None`` if there is none. :rtype: bytes or NoneType .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons this method might return. """ for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)): ext = _lib.X509_REVOKED_get_ext(self._revoked, i) obj = _lib.X509_EXTENSION_get_object(ext) if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason: bio = _new_mem_buf() print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0) if not print_result: print_result = _lib.M_ASN1_OCTET_STRING_print( bio, _lib.X509_EXTENSION_get_data(ext) ) _openssl_assert(print_result != 0) return _bio_to_string(bio)
[ "Get", "the", "reason", "of", "this", "revocation", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2019-L2044
[ "def", "get_reason", "(", "self", ")", ":", "for", "i", "in", "range", "(", "_lib", ".", "X509_REVOKED_get_ext_count", "(", "self", ".", "_revoked", ")", ")", ":", "ext", "=", "_lib", ".", "X509_REVOKED_get_ext", "(", "self", ".", "_revoked", ",", "i", ")", "obj", "=", "_lib", ".", "X509_EXTENSION_get_object", "(", "ext", ")", "if", "_lib", ".", "OBJ_obj2nid", "(", "obj", ")", "==", "_lib", ".", "NID_crl_reason", ":", "bio", "=", "_new_mem_buf", "(", ")", "print_result", "=", "_lib", ".", "X509V3_EXT_print", "(", "bio", ",", "ext", ",", "0", ",", "0", ")", "if", "not", "print_result", ":", "print_result", "=", "_lib", ".", "M_ASN1_OCTET_STRING_print", "(", "bio", ",", "_lib", ".", "X509_EXTENSION_get_data", "(", "ext", ")", ")", "_openssl_assert", "(", "print_result", "!=", "0", ")", "return", "_bio_to_string", "(", "bio", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Revoked.set_rev_date
Set the revocation timestamp. :param bytes when: The timestamp of the revocation, as ASN.1 TIME. :return: ``None``
src/OpenSSL/crypto.py
def set_rev_date(self, when): """ Set the revocation timestamp. :param bytes when: The timestamp of the revocation, as ASN.1 TIME. :return: ``None`` """ dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked) return _set_asn1_time(dt, when)
def set_rev_date(self, when): """ Set the revocation timestamp. :param bytes when: The timestamp of the revocation, as ASN.1 TIME. :return: ``None`` """ dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked) return _set_asn1_time(dt, when)
[ "Set", "the", "revocation", "timestamp", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2058-L2067
[ "def", "set_rev_date", "(", "self", ",", "when", ")", ":", "dt", "=", "_lib", ".", "X509_REVOKED_get0_revocationDate", "(", "self", ".", "_revoked", ")", "return", "_set_asn1_time", "(", "dt", ",", "when", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
CRL.to_cryptography
Export as a ``cryptography`` CRL. :rtype: ``cryptography.x509.CertificateRevocationList`` .. versionadded:: 17.1.0
src/OpenSSL/crypto.py
def to_cryptography(self): """ Export as a ``cryptography`` CRL. :rtype: ``cryptography.x509.CertificateRevocationList`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import ( _CertificateRevocationList ) backend = _get_backend() return _CertificateRevocationList(backend, self._crl)
def to_cryptography(self): """ Export as a ``cryptography`` CRL. :rtype: ``cryptography.x509.CertificateRevocationList`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import ( _CertificateRevocationList ) backend = _get_backend() return _CertificateRevocationList(backend, self._crl)
[ "Export", "as", "a", "cryptography", "CRL", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2089-L2101
[ "def", "to_cryptography", "(", "self", ")", ":", "from", "cryptography", ".", "hazmat", ".", "backends", ".", "openssl", ".", "x509", "import", "(", "_CertificateRevocationList", ")", "backend", "=", "_get_backend", "(", ")", "return", "_CertificateRevocationList", "(", "backend", ",", "self", ".", "_crl", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
CRL.from_cryptography
Construct based on a ``cryptography`` *crypto_crl*. :param crypto_crl: A ``cryptography`` certificate revocation list :type crypto_crl: ``cryptography.x509.CertificateRevocationList`` :rtype: CRL .. versionadded:: 17.1.0
src/OpenSSL/crypto.py
def from_cryptography(cls, crypto_crl): """ Construct based on a ``cryptography`` *crypto_crl*. :param crypto_crl: A ``cryptography`` certificate revocation list :type crypto_crl: ``cryptography.x509.CertificateRevocationList`` :rtype: CRL .. versionadded:: 17.1.0 """ if not isinstance(crypto_crl, x509.CertificateRevocationList): raise TypeError("Must be a certificate revocation list") crl = cls() crl._crl = crypto_crl._x509_crl return crl
def from_cryptography(cls, crypto_crl): """ Construct based on a ``cryptography`` *crypto_crl*. :param crypto_crl: A ``cryptography`` certificate revocation list :type crypto_crl: ``cryptography.x509.CertificateRevocationList`` :rtype: CRL .. versionadded:: 17.1.0 """ if not isinstance(crypto_crl, x509.CertificateRevocationList): raise TypeError("Must be a certificate revocation list") crl = cls() crl._crl = crypto_crl._x509_crl return crl
[ "Construct", "based", "on", "a", "cryptography", "*", "crypto_crl", "*", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2104-L2120
[ "def", "from_cryptography", "(", "cls", ",", "crypto_crl", ")", ":", "if", "not", "isinstance", "(", "crypto_crl", ",", "x509", ".", "CertificateRevocationList", ")", ":", "raise", "TypeError", "(", "\"Must be a certificate revocation list\"", ")", "crl", "=", "cls", "(", ")", "crl", ".", "_crl", "=", "crypto_crl", ".", "_x509_crl", "return", "crl" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
CRL.get_revoked
Return the revocations in this certificate revocation list. These revocations will be provided by value, not by reference. That means it's okay to mutate them: it won't affect this CRL. :return: The revocations in this CRL. :rtype: :class:`tuple` of :class:`Revocation`
src/OpenSSL/crypto.py
def get_revoked(self): """ Return the revocations in this certificate revocation list. These revocations will be provided by value, not by reference. That means it's okay to mutate them: it won't affect this CRL. :return: The revocations in this CRL. :rtype: :class:`tuple` of :class:`Revocation` """ results = [] revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl) for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)): revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i) revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked) pyrev = Revoked.__new__(Revoked) pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free) results.append(pyrev) if results: return tuple(results)
def get_revoked(self): """ Return the revocations in this certificate revocation list. These revocations will be provided by value, not by reference. That means it's okay to mutate them: it won't affect this CRL. :return: The revocations in this CRL. :rtype: :class:`tuple` of :class:`Revocation` """ results = [] revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl) for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)): revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i) revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked) pyrev = Revoked.__new__(Revoked) pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free) results.append(pyrev) if results: return tuple(results)
[ "Return", "the", "revocations", "in", "this", "certificate", "revocation", "list", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2122-L2141
[ "def", "get_revoked", "(", "self", ")", ":", "results", "=", "[", "]", "revoked_stack", "=", "_lib", ".", "X509_CRL_get_REVOKED", "(", "self", ".", "_crl", ")", "for", "i", "in", "range", "(", "_lib", ".", "sk_X509_REVOKED_num", "(", "revoked_stack", ")", ")", ":", "revoked", "=", "_lib", ".", "sk_X509_REVOKED_value", "(", "revoked_stack", ",", "i", ")", "revoked_copy", "=", "_lib", ".", "Cryptography_X509_REVOKED_dup", "(", "revoked", ")", "pyrev", "=", "Revoked", ".", "__new__", "(", "Revoked", ")", "pyrev", ".", "_revoked", "=", "_ffi", ".", "gc", "(", "revoked_copy", ",", "_lib", ".", "X509_REVOKED_free", ")", "results", ".", "append", "(", "pyrev", ")", "if", "results", ":", "return", "tuple", "(", "results", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
CRL.add_revoked
Add a revoked (by value not reference) to the CRL structure This revocation will be added by value, not by reference. That means it's okay to mutate it after adding: it won't affect this CRL. :param Revoked revoked: The new revocation. :return: ``None``
src/OpenSSL/crypto.py
def add_revoked(self, revoked): """ Add a revoked (by value not reference) to the CRL structure This revocation will be added by value, not by reference. That means it's okay to mutate it after adding: it won't affect this CRL. :param Revoked revoked: The new revocation. :return: ``None`` """ copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked) _openssl_assert(copy != _ffi.NULL) add_result = _lib.X509_CRL_add0_revoked(self._crl, copy) _openssl_assert(add_result != 0)
def add_revoked(self, revoked): """ Add a revoked (by value not reference) to the CRL structure This revocation will be added by value, not by reference. That means it's okay to mutate it after adding: it won't affect this CRL. :param Revoked revoked: The new revocation. :return: ``None`` """ copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked) _openssl_assert(copy != _ffi.NULL) add_result = _lib.X509_CRL_add0_revoked(self._crl, copy) _openssl_assert(add_result != 0)
[ "Add", "a", "revoked", "(", "by", "value", "not", "reference", ")", "to", "the", "CRL", "structure" ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2143-L2158
[ "def", "add_revoked", "(", "self", ",", "revoked", ")", ":", "copy", "=", "_lib", ".", "Cryptography_X509_REVOKED_dup", "(", "revoked", ".", "_revoked", ")", "_openssl_assert", "(", "copy", "!=", "_ffi", ".", "NULL", ")", "add_result", "=", "_lib", ".", "X509_CRL_add0_revoked", "(", "self", ".", "_crl", ",", "copy", ")", "_openssl_assert", "(", "add_result", "!=", "0", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
CRL.get_issuer
Get the CRL's issuer. .. versionadded:: 16.1.0 :rtype: X509Name
src/OpenSSL/crypto.py
def get_issuer(self): """ Get the CRL's issuer. .. versionadded:: 16.1.0 :rtype: X509Name """ _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl)) _openssl_assert(_issuer != _ffi.NULL) _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free) issuer = X509Name.__new__(X509Name) issuer._name = _issuer return issuer
def get_issuer(self): """ Get the CRL's issuer. .. versionadded:: 16.1.0 :rtype: X509Name """ _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl)) _openssl_assert(_issuer != _ffi.NULL) _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free) issuer = X509Name.__new__(X509Name) issuer._name = _issuer return issuer
[ "Get", "the", "CRL", "s", "issuer", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2160-L2173
[ "def", "get_issuer", "(", "self", ")", ":", "_issuer", "=", "_lib", ".", "X509_NAME_dup", "(", "_lib", ".", "X509_CRL_get_issuer", "(", "self", ".", "_crl", ")", ")", "_openssl_assert", "(", "_issuer", "!=", "_ffi", ".", "NULL", ")", "_issuer", "=", "_ffi", ".", "gc", "(", "_issuer", ",", "_lib", ".", "X509_NAME_free", ")", "issuer", "=", "X509Name", ".", "__new__", "(", "X509Name", ")", "issuer", ".", "_name", "=", "_issuer", "return", "issuer" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
CRL.sign
Sign the CRL. Signing a CRL enables clients to associate the CRL itself with an issuer. Before a CRL is meaningful to other OpenSSL functions, it must be signed by an issuer. This method implicitly sets the issuer's name based on the issuer certificate and private key used to sign the CRL. .. versionadded:: 16.1.0 :param X509 issuer_cert: The issuer's certificate. :param PKey issuer_key: The issuer's private key. :param bytes digest: The digest method to sign the CRL with.
src/OpenSSL/crypto.py
def sign(self, issuer_cert, issuer_key, digest): """ Sign the CRL. Signing a CRL enables clients to associate the CRL itself with an issuer. Before a CRL is meaningful to other OpenSSL functions, it must be signed by an issuer. This method implicitly sets the issuer's name based on the issuer certificate and private key used to sign the CRL. .. versionadded:: 16.1.0 :param X509 issuer_cert: The issuer's certificate. :param PKey issuer_key: The issuer's private key. :param bytes digest: The digest method to sign the CRL with. """ digest_obj = _lib.EVP_get_digestbyname(digest) _openssl_assert(digest_obj != _ffi.NULL) _lib.X509_CRL_set_issuer_name( self._crl, _lib.X509_get_subject_name(issuer_cert._x509)) _lib.X509_CRL_sort(self._crl) result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj) _openssl_assert(result != 0)
def sign(self, issuer_cert, issuer_key, digest): """ Sign the CRL. Signing a CRL enables clients to associate the CRL itself with an issuer. Before a CRL is meaningful to other OpenSSL functions, it must be signed by an issuer. This method implicitly sets the issuer's name based on the issuer certificate and private key used to sign the CRL. .. versionadded:: 16.1.0 :param X509 issuer_cert: The issuer's certificate. :param PKey issuer_key: The issuer's private key. :param bytes digest: The digest method to sign the CRL with. """ digest_obj = _lib.EVP_get_digestbyname(digest) _openssl_assert(digest_obj != _ffi.NULL) _lib.X509_CRL_set_issuer_name( self._crl, _lib.X509_get_subject_name(issuer_cert._x509)) _lib.X509_CRL_sort(self._crl) result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj) _openssl_assert(result != 0)
[ "Sign", "the", "CRL", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2219-L2242
[ "def", "sign", "(", "self", ",", "issuer_cert", ",", "issuer_key", ",", "digest", ")", ":", "digest_obj", "=", "_lib", ".", "EVP_get_digestbyname", "(", "digest", ")", "_openssl_assert", "(", "digest_obj", "!=", "_ffi", ".", "NULL", ")", "_lib", ".", "X509_CRL_set_issuer_name", "(", "self", ".", "_crl", ",", "_lib", ".", "X509_get_subject_name", "(", "issuer_cert", ".", "_x509", ")", ")", "_lib", ".", "X509_CRL_sort", "(", "self", ".", "_crl", ")", "result", "=", "_lib", ".", "X509_CRL_sign", "(", "self", ".", "_crl", ",", "issuer_key", ".", "_pkey", ",", "digest_obj", ")", "_openssl_assert", "(", "result", "!=", "0", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
CRL.export
Export the CRL as a string. :param X509 cert: The certificate used to sign the CRL. :param PKey key: The key used to sign the CRL. :param int type: The export format, either :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`. :param int days: The number of days until the next update of this CRL. :param bytes digest: The name of the message digest to use (eg ``b"sha256"``). :rtype: bytes
src/OpenSSL/crypto.py
def export(self, cert, key, type=FILETYPE_PEM, days=100, digest=_UNSPECIFIED): """ Export the CRL as a string. :param X509 cert: The certificate used to sign the CRL. :param PKey key: The key used to sign the CRL. :param int type: The export format, either :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`. :param int days: The number of days until the next update of this CRL. :param bytes digest: The name of the message digest to use (eg ``b"sha256"``). :rtype: bytes """ if not isinstance(cert, X509): raise TypeError("cert must be an X509 instance") if not isinstance(key, PKey): raise TypeError("key must be a PKey instance") if not isinstance(type, int): raise TypeError("type must be an integer") if digest is _UNSPECIFIED: raise TypeError("digest must be provided") digest_obj = _lib.EVP_get_digestbyname(digest) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") bio = _lib.BIO_new(_lib.BIO_s_mem()) _openssl_assert(bio != _ffi.NULL) # A scratch time object to give different values to different CRL # fields sometime = _lib.ASN1_TIME_new() _openssl_assert(sometime != _ffi.NULL) _lib.X509_gmtime_adj(sometime, 0) _lib.X509_CRL_set_lastUpdate(self._crl, sometime) _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60) _lib.X509_CRL_set_nextUpdate(self._crl, sometime) _lib.X509_CRL_set_issuer_name( self._crl, _lib.X509_get_subject_name(cert._x509) ) sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj) if not sign_result: _raise_current_error() return dump_crl(type, self)
def export(self, cert, key, type=FILETYPE_PEM, days=100, digest=_UNSPECIFIED): """ Export the CRL as a string. :param X509 cert: The certificate used to sign the CRL. :param PKey key: The key used to sign the CRL. :param int type: The export format, either :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`. :param int days: The number of days until the next update of this CRL. :param bytes digest: The name of the message digest to use (eg ``b"sha256"``). :rtype: bytes """ if not isinstance(cert, X509): raise TypeError("cert must be an X509 instance") if not isinstance(key, PKey): raise TypeError("key must be a PKey instance") if not isinstance(type, int): raise TypeError("type must be an integer") if digest is _UNSPECIFIED: raise TypeError("digest must be provided") digest_obj = _lib.EVP_get_digestbyname(digest) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") bio = _lib.BIO_new(_lib.BIO_s_mem()) _openssl_assert(bio != _ffi.NULL) # A scratch time object to give different values to different CRL # fields sometime = _lib.ASN1_TIME_new() _openssl_assert(sometime != _ffi.NULL) _lib.X509_gmtime_adj(sometime, 0) _lib.X509_CRL_set_lastUpdate(self._crl, sometime) _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60) _lib.X509_CRL_set_nextUpdate(self._crl, sometime) _lib.X509_CRL_set_issuer_name( self._crl, _lib.X509_get_subject_name(cert._x509) ) sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj) if not sign_result: _raise_current_error() return dump_crl(type, self)
[ "Export", "the", "CRL", "as", "a", "string", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2244-L2295
[ "def", "export", "(", "self", ",", "cert", ",", "key", ",", "type", "=", "FILETYPE_PEM", ",", "days", "=", "100", ",", "digest", "=", "_UNSPECIFIED", ")", ":", "if", "not", "isinstance", "(", "cert", ",", "X509", ")", ":", "raise", "TypeError", "(", "\"cert must be an X509 instance\"", ")", "if", "not", "isinstance", "(", "key", ",", "PKey", ")", ":", "raise", "TypeError", "(", "\"key must be a PKey instance\"", ")", "if", "not", "isinstance", "(", "type", ",", "int", ")", ":", "raise", "TypeError", "(", "\"type must be an integer\"", ")", "if", "digest", "is", "_UNSPECIFIED", ":", "raise", "TypeError", "(", "\"digest must be provided\"", ")", "digest_obj", "=", "_lib", ".", "EVP_get_digestbyname", "(", "digest", ")", "if", "digest_obj", "==", "_ffi", ".", "NULL", ":", "raise", "ValueError", "(", "\"No such digest method\"", ")", "bio", "=", "_lib", ".", "BIO_new", "(", "_lib", ".", "BIO_s_mem", "(", ")", ")", "_openssl_assert", "(", "bio", "!=", "_ffi", ".", "NULL", ")", "# A scratch time object to give different values to different CRL", "# fields", "sometime", "=", "_lib", ".", "ASN1_TIME_new", "(", ")", "_openssl_assert", "(", "sometime", "!=", "_ffi", ".", "NULL", ")", "_lib", ".", "X509_gmtime_adj", "(", "sometime", ",", "0", ")", "_lib", ".", "X509_CRL_set_lastUpdate", "(", "self", ".", "_crl", ",", "sometime", ")", "_lib", ".", "X509_gmtime_adj", "(", "sometime", ",", "days", "*", "24", "*", "60", "*", "60", ")", "_lib", ".", "X509_CRL_set_nextUpdate", "(", "self", ".", "_crl", ",", "sometime", ")", "_lib", ".", "X509_CRL_set_issuer_name", "(", "self", ".", "_crl", ",", "_lib", ".", "X509_get_subject_name", "(", "cert", ".", "_x509", ")", ")", "sign_result", "=", "_lib", ".", "X509_CRL_sign", "(", "self", ".", "_crl", ",", "key", ".", "_pkey", ",", "digest_obj", ")", "if", "not", "sign_result", ":", "_raise_current_error", "(", ")", "return", "dump_crl", "(", "type", ",", "self", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
PKCS7.get_type_name
Returns the type name of the PKCS7 structure :return: A string with the typename
src/OpenSSL/crypto.py
def get_type_name(self): """ Returns the type name of the PKCS7 structure :return: A string with the typename """ nid = _lib.OBJ_obj2nid(self._pkcs7.type) string_type = _lib.OBJ_nid2sn(nid) return _ffi.string(string_type)
def get_type_name(self): """ Returns the type name of the PKCS7 structure :return: A string with the typename """ nid = _lib.OBJ_obj2nid(self._pkcs7.type) string_type = _lib.OBJ_nid2sn(nid) return _ffi.string(string_type)
[ "Returns", "the", "type", "name", "of", "the", "PKCS7", "structure" ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2331-L2339
[ "def", "get_type_name", "(", "self", ")", ":", "nid", "=", "_lib", ".", "OBJ_obj2nid", "(", "self", ".", "_pkcs7", ".", "type", ")", "string_type", "=", "_lib", ".", "OBJ_nid2sn", "(", "nid", ")", "return", "_ffi", ".", "string", "(", "string_type", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
PKCS12.set_certificate
Set the certificate in the PKCS #12 structure. :param cert: The new certificate, or :py:const:`None` to unset it. :type cert: :py:class:`X509` or :py:const:`None` :return: ``None``
src/OpenSSL/crypto.py
def set_certificate(self, cert): """ Set the certificate in the PKCS #12 structure. :param cert: The new certificate, or :py:const:`None` to unset it. :type cert: :py:class:`X509` or :py:const:`None` :return: ``None`` """ if not isinstance(cert, X509): raise TypeError("cert must be an X509 instance") self._cert = cert
def set_certificate(self, cert): """ Set the certificate in the PKCS #12 structure. :param cert: The new certificate, or :py:const:`None` to unset it. :type cert: :py:class:`X509` or :py:const:`None` :return: ``None`` """ if not isinstance(cert, X509): raise TypeError("cert must be an X509 instance") self._cert = cert
[ "Set", "the", "certificate", "in", "the", "PKCS", "#12", "structure", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2362-L2373
[ "def", "set_certificate", "(", "self", ",", "cert", ")", ":", "if", "not", "isinstance", "(", "cert", ",", "X509", ")", ":", "raise", "TypeError", "(", "\"cert must be an X509 instance\"", ")", "self", ".", "_cert", "=", "cert" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
PKCS12.set_privatekey
Set the certificate portion of the PKCS #12 structure. :param pkey: The new private key, or :py:const:`None` to unset it. :type pkey: :py:class:`PKey` or :py:const:`None` :return: ``None``
src/OpenSSL/crypto.py
def set_privatekey(self, pkey): """ Set the certificate portion of the PKCS #12 structure. :param pkey: The new private key, or :py:const:`None` to unset it. :type pkey: :py:class:`PKey` or :py:const:`None` :return: ``None`` """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") self._pkey = pkey
def set_privatekey(self, pkey): """ Set the certificate portion of the PKCS #12 structure. :param pkey: The new private key, or :py:const:`None` to unset it. :type pkey: :py:class:`PKey` or :py:const:`None` :return: ``None`` """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") self._pkey = pkey
[ "Set", "the", "certificate", "portion", "of", "the", "PKCS", "#12", "structure", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2384-L2395
[ "def", "set_privatekey", "(", "self", ",", "pkey", ")", ":", "if", "not", "isinstance", "(", "pkey", ",", "PKey", ")", ":", "raise", "TypeError", "(", "\"pkey must be a PKey instance\"", ")", "self", ".", "_pkey", "=", "pkey" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
PKCS12.set_ca_certificates
Replace or set the CA certificates within the PKCS12 object. :param cacerts: The new CA certificates, or :py:const:`None` to unset them. :type cacerts: An iterable of :py:class:`X509` or :py:const:`None` :return: ``None``
src/OpenSSL/crypto.py
def set_ca_certificates(self, cacerts): """ Replace or set the CA certificates within the PKCS12 object. :param cacerts: The new CA certificates, or :py:const:`None` to unset them. :type cacerts: An iterable of :py:class:`X509` or :py:const:`None` :return: ``None`` """ if cacerts is None: self._cacerts = None else: cacerts = list(cacerts) for cert in cacerts: if not isinstance(cert, X509): raise TypeError( "iterable must only contain X509 instances" ) self._cacerts = cacerts
def set_ca_certificates(self, cacerts): """ Replace or set the CA certificates within the PKCS12 object. :param cacerts: The new CA certificates, or :py:const:`None` to unset them. :type cacerts: An iterable of :py:class:`X509` or :py:const:`None` :return: ``None`` """ if cacerts is None: self._cacerts = None else: cacerts = list(cacerts) for cert in cacerts: if not isinstance(cert, X509): raise TypeError( "iterable must only contain X509 instances" ) self._cacerts = cacerts
[ "Replace", "or", "set", "the", "CA", "certificates", "within", "the", "PKCS12", "object", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2408-L2427
[ "def", "set_ca_certificates", "(", "self", ",", "cacerts", ")", ":", "if", "cacerts", "is", "None", ":", "self", ".", "_cacerts", "=", "None", "else", ":", "cacerts", "=", "list", "(", "cacerts", ")", "for", "cert", "in", "cacerts", ":", "if", "not", "isinstance", "(", "cert", ",", "X509", ")", ":", "raise", "TypeError", "(", "\"iterable must only contain X509 instances\"", ")", "self", ".", "_cacerts", "=", "cacerts" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
PKCS12.set_friendlyname
Set the friendly name in the PKCS #12 structure. :param name: The new friendly name, or :py:const:`None` to unset. :type name: :py:class:`bytes` or :py:const:`None` :return: ``None``
src/OpenSSL/crypto.py
def set_friendlyname(self, name): """ Set the friendly name in the PKCS #12 structure. :param name: The new friendly name, or :py:const:`None` to unset. :type name: :py:class:`bytes` or :py:const:`None` :return: ``None`` """ if name is None: self._friendlyname = None elif not isinstance(name, bytes): raise TypeError( "name must be a byte string or None (not %r)" % (name,) ) self._friendlyname = name
def set_friendlyname(self, name): """ Set the friendly name in the PKCS #12 structure. :param name: The new friendly name, or :py:const:`None` to unset. :type name: :py:class:`bytes` or :py:const:`None` :return: ``None`` """ if name is None: self._friendlyname = None elif not isinstance(name, bytes): raise TypeError( "name must be a byte string or None (not %r)" % (name,) ) self._friendlyname = name
[ "Set", "the", "friendly", "name", "in", "the", "PKCS", "#12", "structure", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2429-L2444
[ "def", "set_friendlyname", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "self", ".", "_friendlyname", "=", "None", "elif", "not", "isinstance", "(", "name", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"name must be a byte string or None (not %r)\"", "%", "(", "name", ",", ")", ")", "self", ".", "_friendlyname", "=", "name" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
PKCS12.export
Dump a PKCS12 object as a string. For more information, see the :c:func:`PKCS12_create` man page. :param passphrase: The passphrase used to encrypt the structure. Unlike some other passphrase arguments, this *must* be a string, not a callback. :type passphrase: :py:data:`bytes` :param iter: Number of times to repeat the encryption step. :type iter: :py:data:`int` :param maciter: Number of times to repeat the MAC step. :type maciter: :py:data:`int` :return: The string representation of the PKCS #12 structure. :rtype:
src/OpenSSL/crypto.py
def export(self, passphrase=None, iter=2048, maciter=1): """ Dump a PKCS12 object as a string. For more information, see the :c:func:`PKCS12_create` man page. :param passphrase: The passphrase used to encrypt the structure. Unlike some other passphrase arguments, this *must* be a string, not a callback. :type passphrase: :py:data:`bytes` :param iter: Number of times to repeat the encryption step. :type iter: :py:data:`int` :param maciter: Number of times to repeat the MAC step. :type maciter: :py:data:`int` :return: The string representation of the PKCS #12 structure. :rtype: """ passphrase = _text_to_bytes_and_warn("passphrase", passphrase) if self._cacerts is None: cacerts = _ffi.NULL else: cacerts = _lib.sk_X509_new_null() cacerts = _ffi.gc(cacerts, _lib.sk_X509_free) for cert in self._cacerts: _lib.sk_X509_push(cacerts, cert._x509) if passphrase is None: passphrase = _ffi.NULL friendlyname = self._friendlyname if friendlyname is None: friendlyname = _ffi.NULL if self._pkey is None: pkey = _ffi.NULL else: pkey = self._pkey._pkey if self._cert is None: cert = _ffi.NULL else: cert = self._cert._x509 pkcs12 = _lib.PKCS12_create( passphrase, friendlyname, pkey, cert, cacerts, _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC, _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC, iter, maciter, 0) if pkcs12 == _ffi.NULL: _raise_current_error() pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free) bio = _new_mem_buf() _lib.i2d_PKCS12_bio(bio, pkcs12) return _bio_to_string(bio)
def export(self, passphrase=None, iter=2048, maciter=1): """ Dump a PKCS12 object as a string. For more information, see the :c:func:`PKCS12_create` man page. :param passphrase: The passphrase used to encrypt the structure. Unlike some other passphrase arguments, this *must* be a string, not a callback. :type passphrase: :py:data:`bytes` :param iter: Number of times to repeat the encryption step. :type iter: :py:data:`int` :param maciter: Number of times to repeat the MAC step. :type maciter: :py:data:`int` :return: The string representation of the PKCS #12 structure. :rtype: """ passphrase = _text_to_bytes_and_warn("passphrase", passphrase) if self._cacerts is None: cacerts = _ffi.NULL else: cacerts = _lib.sk_X509_new_null() cacerts = _ffi.gc(cacerts, _lib.sk_X509_free) for cert in self._cacerts: _lib.sk_X509_push(cacerts, cert._x509) if passphrase is None: passphrase = _ffi.NULL friendlyname = self._friendlyname if friendlyname is None: friendlyname = _ffi.NULL if self._pkey is None: pkey = _ffi.NULL else: pkey = self._pkey._pkey if self._cert is None: cert = _ffi.NULL else: cert = self._cert._x509 pkcs12 = _lib.PKCS12_create( passphrase, friendlyname, pkey, cert, cacerts, _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC, _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC, iter, maciter, 0) if pkcs12 == _ffi.NULL: _raise_current_error() pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free) bio = _new_mem_buf() _lib.i2d_PKCS12_bio(bio, pkcs12) return _bio_to_string(bio)
[ "Dump", "a", "PKCS12", "object", "as", "a", "string", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2455-L2513
[ "def", "export", "(", "self", ",", "passphrase", "=", "None", ",", "iter", "=", "2048", ",", "maciter", "=", "1", ")", ":", "passphrase", "=", "_text_to_bytes_and_warn", "(", "\"passphrase\"", ",", "passphrase", ")", "if", "self", ".", "_cacerts", "is", "None", ":", "cacerts", "=", "_ffi", ".", "NULL", "else", ":", "cacerts", "=", "_lib", ".", "sk_X509_new_null", "(", ")", "cacerts", "=", "_ffi", ".", "gc", "(", "cacerts", ",", "_lib", ".", "sk_X509_free", ")", "for", "cert", "in", "self", ".", "_cacerts", ":", "_lib", ".", "sk_X509_push", "(", "cacerts", ",", "cert", ".", "_x509", ")", "if", "passphrase", "is", "None", ":", "passphrase", "=", "_ffi", ".", "NULL", "friendlyname", "=", "self", ".", "_friendlyname", "if", "friendlyname", "is", "None", ":", "friendlyname", "=", "_ffi", ".", "NULL", "if", "self", ".", "_pkey", "is", "None", ":", "pkey", "=", "_ffi", ".", "NULL", "else", ":", "pkey", "=", "self", ".", "_pkey", ".", "_pkey", "if", "self", ".", "_cert", "is", "None", ":", "cert", "=", "_ffi", ".", "NULL", "else", ":", "cert", "=", "self", ".", "_cert", ".", "_x509", "pkcs12", "=", "_lib", ".", "PKCS12_create", "(", "passphrase", ",", "friendlyname", ",", "pkey", ",", "cert", ",", "cacerts", ",", "_lib", ".", "NID_pbe_WithSHA1And3_Key_TripleDES_CBC", ",", "_lib", ".", "NID_pbe_WithSHA1And3_Key_TripleDES_CBC", ",", "iter", ",", "maciter", ",", "0", ")", "if", "pkcs12", "==", "_ffi", ".", "NULL", ":", "_raise_current_error", "(", ")", "pkcs12", "=", "_ffi", ".", "gc", "(", "pkcs12", ",", "_lib", ".", "PKCS12_free", ")", "bio", "=", "_new_mem_buf", "(", ")", "_lib", ".", "i2d_PKCS12_bio", "(", "bio", ",", "pkcs12", ")", "return", "_bio_to_string", "(", "bio", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
NetscapeSPKI.sign
Sign the certificate request with this key and digest type. :param pkey: The private key to sign with. :type pkey: :py:class:`PKey` :param digest: The message digest to use. :type digest: :py:class:`bytes` :return: ``None``
src/OpenSSL/crypto.py
def sign(self, pkey, digest): """ Sign the certificate request with this key and digest type. :param pkey: The private key to sign with. :type pkey: :py:class:`PKey` :param digest: The message digest to use. :type digest: :py:class:`bytes` :return: ``None`` """ if pkey._only_public: raise ValueError("Key has only public part") if not pkey._initialized: raise ValueError("Key is uninitialized") digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") sign_result = _lib.NETSCAPE_SPKI_sign( self._spki, pkey._pkey, digest_obj ) _openssl_assert(sign_result > 0)
def sign(self, pkey, digest): """ Sign the certificate request with this key and digest type. :param pkey: The private key to sign with. :type pkey: :py:class:`PKey` :param digest: The message digest to use. :type digest: :py:class:`bytes` :return: ``None`` """ if pkey._only_public: raise ValueError("Key has only public part") if not pkey._initialized: raise ValueError("Key is uninitialized") digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") sign_result = _lib.NETSCAPE_SPKI_sign( self._spki, pkey._pkey, digest_obj ) _openssl_assert(sign_result > 0)
[ "Sign", "the", "certificate", "request", "with", "this", "key", "and", "digest", "type", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2525-L2550
[ "def", "sign", "(", "self", ",", "pkey", ",", "digest", ")", ":", "if", "pkey", ".", "_only_public", ":", "raise", "ValueError", "(", "\"Key has only public part\"", ")", "if", "not", "pkey", ".", "_initialized", ":", "raise", "ValueError", "(", "\"Key is uninitialized\"", ")", "digest_obj", "=", "_lib", ".", "EVP_get_digestbyname", "(", "_byte_string", "(", "digest", ")", ")", "if", "digest_obj", "==", "_ffi", ".", "NULL", ":", "raise", "ValueError", "(", "\"No such digest method\"", ")", "sign_result", "=", "_lib", ".", "NETSCAPE_SPKI_sign", "(", "self", ".", "_spki", ",", "pkey", ".", "_pkey", ",", "digest_obj", ")", "_openssl_assert", "(", "sign_result", ">", "0", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
NetscapeSPKI.verify
Verifies a signature on a certificate request. :param PKey key: The public key that signature is supposedly from. :return: ``True`` if the signature is correct. :rtype: bool :raises OpenSSL.crypto.Error: If the signature is invalid, or there was a problem verifying the signature.
src/OpenSSL/crypto.py
def verify(self, key): """ Verifies a signature on a certificate request. :param PKey key: The public key that signature is supposedly from. :return: ``True`` if the signature is correct. :rtype: bool :raises OpenSSL.crypto.Error: If the signature is invalid, or there was a problem verifying the signature. """ answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey) if answer <= 0: _raise_current_error() return True
def verify(self, key): """ Verifies a signature on a certificate request. :param PKey key: The public key that signature is supposedly from. :return: ``True`` if the signature is correct. :rtype: bool :raises OpenSSL.crypto.Error: If the signature is invalid, or there was a problem verifying the signature. """ answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey) if answer <= 0: _raise_current_error() return True
[ "Verifies", "a", "signature", "on", "a", "certificate", "request", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2552-L2567
[ "def", "verify", "(", "self", ",", "key", ")", ":", "answer", "=", "_lib", ".", "NETSCAPE_SPKI_verify", "(", "self", ".", "_spki", ",", "key", ".", "_pkey", ")", "if", "answer", "<=", "0", ":", "_raise_current_error", "(", ")", "return", "True" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
NetscapeSPKI.b64_encode
Generate a base64 encoded representation of this SPKI object. :return: The base64 encoded string. :rtype: :py:class:`bytes`
src/OpenSSL/crypto.py
def b64_encode(self): """ Generate a base64 encoded representation of this SPKI object. :return: The base64 encoded string. :rtype: :py:class:`bytes` """ encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki) result = _ffi.string(encoded) _lib.OPENSSL_free(encoded) return result
def b64_encode(self): """ Generate a base64 encoded representation of this SPKI object. :return: The base64 encoded string. :rtype: :py:class:`bytes` """ encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki) result = _ffi.string(encoded) _lib.OPENSSL_free(encoded) return result
[ "Generate", "a", "base64", "encoded", "representation", "of", "this", "SPKI", "object", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2569-L2579
[ "def", "b64_encode", "(", "self", ")", ":", "encoded", "=", "_lib", ".", "NETSCAPE_SPKI_b64_encode", "(", "self", ".", "_spki", ")", "result", "=", "_ffi", ".", "string", "(", "encoded", ")", "_lib", ".", "OPENSSL_free", "(", "encoded", ")", "return", "result" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
NetscapeSPKI.get_pubkey
Get the public key of this certificate. :return: The public key. :rtype: :py:class:`PKey`
src/OpenSSL/crypto.py
def get_pubkey(self): """ Get the public key of this certificate. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki) _openssl_assert(pkey._pkey != _ffi.NULL) pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
def get_pubkey(self): """ Get the public key of this certificate. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki) _openssl_assert(pkey._pkey != _ffi.NULL) pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
[ "Get", "the", "public", "key", "of", "this", "certificate", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2581-L2593
[ "def", "get_pubkey", "(", "self", ")", ":", "pkey", "=", "PKey", ".", "__new__", "(", "PKey", ")", "pkey", ".", "_pkey", "=", "_lib", ".", "NETSCAPE_SPKI_get_pubkey", "(", "self", ".", "_spki", ")", "_openssl_assert", "(", "pkey", ".", "_pkey", "!=", "_ffi", ".", "NULL", ")", "pkey", ".", "_pkey", "=", "_ffi", ".", "gc", "(", "pkey", ".", "_pkey", ",", "_lib", ".", "EVP_PKEY_free", ")", "pkey", ".", "_only_public", "=", "True", "return", "pkey" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
NetscapeSPKI.set_pubkey
Set the public key of the certificate :param pkey: The public key :return: ``None``
src/OpenSSL/crypto.py
def set_pubkey(self, pkey): """ Set the public key of the certificate :param pkey: The public key :return: ``None`` """ set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey) _openssl_assert(set_result == 1)
def set_pubkey(self, pkey): """ Set the public key of the certificate :param pkey: The public key :return: ``None`` """ set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey) _openssl_assert(set_result == 1)
[ "Set", "the", "public", "key", "of", "the", "certificate" ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2595-L2603
[ "def", "set_pubkey", "(", "self", ",", "pkey", ")", ":", "set_result", "=", "_lib", ".", "NETSCAPE_SPKI_set_pubkey", "(", "self", ".", "_spki", ",", "pkey", ".", "_pkey", ")", "_openssl_assert", "(", "set_result", "==", "1", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
exception_from_error_queue
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.
src/OpenSSL/_util.py
def exception_from_error_queue(exception_type): """ 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. """ errors = [] while True: error = lib.ERR_get_error() if error == 0: break errors.append(( text(lib.ERR_lib_error_string(error)), text(lib.ERR_func_error_string(error)), text(lib.ERR_reason_error_string(error)))) raise exception_type(errors)
def exception_from_error_queue(exception_type): """ 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. """ errors = [] while True: error = lib.ERR_get_error() if error == 0: break errors.append(( text(lib.ERR_lib_error_string(error)), text(lib.ERR_func_error_string(error)), text(lib.ERR_reason_error_string(error)))) raise exception_type(errors)
[ "Convert", "an", "OpenSSL", "library", "failure", "into", "a", "Python", "exception", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/_util.py#L34-L54
[ "def", "exception_from_error_queue", "(", "exception_type", ")", ":", "errors", "=", "[", "]", "while", "True", ":", "error", "=", "lib", ".", "ERR_get_error", "(", ")", "if", "error", "==", "0", ":", "break", "errors", ".", "append", "(", "(", "text", "(", "lib", ".", "ERR_lib_error_string", "(", "error", ")", ")", ",", "text", "(", "lib", ".", "ERR_func_error_string", "(", "error", ")", ")", ",", "text", "(", "lib", ".", "ERR_reason_error_string", "(", "error", ")", ")", ")", ")", "raise", "exception_type", "(", "errors", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
native
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`.
src/OpenSSL/_util.py
def native(s): """ 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 not isinstance(s, (binary_type, text_type)): raise TypeError("%r is neither bytes nor unicode" % s) if PY3: if isinstance(s, binary_type): return s.decode("utf-8") else: if isinstance(s, text_type): return s.encode("utf-8") return s
def native(s): """ 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 not isinstance(s, (binary_type, text_type)): raise TypeError("%r is neither bytes nor unicode" % s) if PY3: if isinstance(s, binary_type): return s.decode("utf-8") else: if isinstance(s, text_type): return s.encode("utf-8") return s
[ "Convert", ":", "py", ":", "class", ":", "bytes", "or", ":", "py", ":", "class", ":", "unicode", "to", "the", "native", ":", "py", ":", "class", ":", "str", "type", "using", "UTF", "-", "8", "encoding", "if", "conversion", "is", "necessary", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/_util.py#L72-L90
[ "def", "native", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "(", "binary_type", ",", "text_type", ")", ")", ":", "raise", "TypeError", "(", "\"%r is neither bytes nor unicode\"", "%", "s", ")", "if", "PY3", ":", "if", "isinstance", "(", "s", ",", "binary_type", ")", ":", "return", "s", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "if", "isinstance", "(", "s", ",", "text_type", ")", ":", "return", "s", ".", "encode", "(", "\"utf-8\"", ")", "return", "s" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
path_string
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`.
src/OpenSSL/_util.py
def path_string(s): """ 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(s, binary_type): return s elif isinstance(s, text_type): return s.encode(sys.getfilesystemencoding()) else: raise TypeError("Path must be represented as bytes or unicode string")
def path_string(s): """ 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(s, binary_type): return s elif isinstance(s, text_type): return s.encode(sys.getfilesystemencoding()) else: raise TypeError("Path must be represented as bytes or unicode string")
[ "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", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/_util.py#L93-L107
[ "def", "path_string", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "binary_type", ")", ":", "return", "s", "elif", "isinstance", "(", "s", ",", "text_type", ")", ":", "return", "s", ".", "encode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ")", "else", ":", "raise", "TypeError", "(", "\"Path must be represented as bytes or unicode string\"", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
text_to_bytes_and_warn
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.
src/OpenSSL/_util.py
def text_to_bytes_and_warn(label, obj): """ 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. """ if isinstance(obj, text_type): warnings.warn( _TEXT_WARNING.format(label), category=DeprecationWarning, stacklevel=3 ) return obj.encode('utf-8') return obj
def text_to_bytes_and_warn(label, obj): """ 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. """ if isinstance(obj, text_type): warnings.warn( _TEXT_WARNING.format(label), category=DeprecationWarning, stacklevel=3 ) return obj.encode('utf-8') return obj
[ "If", "obj", "is", "text", "emit", "a", "warning", "that", "it", "should", "be", "bytes", "instead", "and", "try", "to", "convert", "it", "to", "bytes", "automatically", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/_util.py#L127-L147
[ "def", "text_to_bytes_and_warn", "(", "label", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "text_type", ")", ":", "warnings", ".", "warn", "(", "_TEXT_WARNING", ".", "format", "(", "label", ")", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "3", ")", "return", "obj", ".", "encode", "(", "'utf-8'", ")", "return", "obj" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
add
Mix bytes from *string* into the PRNG state. The *entropy* argument is (the lower bound of) an estimate of how much randomness is contained in *string*, measured in bytes. For more information, see e.g. :rfc:`1750`. This function is only relevant if you are forking Python processes and need to reseed the CSPRNG after fork. :param buffer: Buffer with random data. :param entropy: The entropy (in bytes) measurement of the buffer. :return: :obj:`None`
src/OpenSSL/rand.py
def add(buffer, entropy): """ Mix bytes from *string* into the PRNG state. The *entropy* argument is (the lower bound of) an estimate of how much randomness is contained in *string*, measured in bytes. For more information, see e.g. :rfc:`1750`. This function is only relevant if you are forking Python processes and need to reseed the CSPRNG after fork. :param buffer: Buffer with random data. :param entropy: The entropy (in bytes) measurement of the buffer. :return: :obj:`None` """ if not isinstance(buffer, bytes): raise TypeError("buffer must be a byte string") if not isinstance(entropy, int): raise TypeError("entropy must be an integer") _lib.RAND_add(buffer, len(buffer), entropy)
def add(buffer, entropy): """ Mix bytes from *string* into the PRNG state. The *entropy* argument is (the lower bound of) an estimate of how much randomness is contained in *string*, measured in bytes. For more information, see e.g. :rfc:`1750`. This function is only relevant if you are forking Python processes and need to reseed the CSPRNG after fork. :param buffer: Buffer with random data. :param entropy: The entropy (in bytes) measurement of the buffer. :return: :obj:`None` """ if not isinstance(buffer, bytes): raise TypeError("buffer must be a byte string") if not isinstance(entropy, int): raise TypeError("entropy must be an integer") _lib.RAND_add(buffer, len(buffer), entropy)
[ "Mix", "bytes", "from", "*", "string", "*", "into", "the", "PRNG", "state", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/rand.py#L8-L31
[ "def", "add", "(", "buffer", ",", "entropy", ")", ":", "if", "not", "isinstance", "(", "buffer", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"buffer must be a byte string\"", ")", "if", "not", "isinstance", "(", "entropy", ",", "int", ")", ":", "raise", "TypeError", "(", "\"entropy must be an integer\"", ")", "_lib", ".", "RAND_add", "(", "buffer", ",", "len", "(", "buffer", ")", ",", "entropy", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
SSLWrapper.accept
This is the other part of the shutdown() workaround. Since servers create new sockets, we have to infect them with our magic. :)
examples/SecureXMLRPCServer.py
def accept(self): """ This is the other part of the shutdown() workaround. Since servers create new sockets, we have to infect them with our magic. :) """ c, a = self.__dict__["conn"].accept() return (SSLWrapper(c), a)
def accept(self): """ This is the other part of the shutdown() workaround. Since servers create new sockets, we have to infect them with our magic. :) """ c, a = self.__dict__["conn"].accept() return (SSLWrapper(c), a)
[ "This", "is", "the", "other", "part", "of", "the", "shutdown", "()", "workaround", ".", "Since", "servers", "create", "new", "sockets", "we", "have", "to", "infect", "them", "with", "our", "magic", ".", ":", ")" ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/examples/SecureXMLRPCServer.py#L52-L59
[ "def", "accept", "(", "self", ")", ":", "c", ",", "a", "=", "self", ".", "__dict__", "[", "\"conn\"", "]", ".", "accept", "(", ")", "return", "(", "SSLWrapper", "(", "c", ")", ",", "a", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
SecureXMLRPCRequestHandler.setup
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
examples/SecureXMLRPCServer.py
def setup(self): """ 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.connection = self.request # for doPOST self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
def setup(self): """ 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.connection = self.request # for doPOST self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
[ "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" ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/examples/SecureXMLRPCServer.py#L91-L99
[ "def", "setup", "(", "self", ")", ":", "self", ".", "connection", "=", "self", ".", "request", "# for doPOST", "self", ".", "rfile", "=", "socket", ".", "_fileobject", "(", "self", ".", "request", ",", "\"rb\"", ",", "self", ".", "rbufsize", ")", "self", ".", "wfile", "=", "socket", ".", "_fileobject", "(", "self", ".", "request", ",", "\"wb\"", ",", "self", ".", "wbufsize", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
main
Run an SNI-enabled server which selects between a few certificates in a C{dict} based on the handshake request it receives from a client.
examples/sni/server.py
def main(): """ Run an SNI-enabled server which selects between a few certificates in a C{dict} based on the handshake request it receives from a client. """ port = socket() port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) port.bind(('', 8443)) port.listen(3) print('Accepting...', end="") stdout.flush() server, addr = port.accept() print('accepted', addr) server_context = Context(TLSv1_METHOD) server_context.set_tlsext_servername_callback(pick_certificate) server_ssl = Connection(server_context, server) server_ssl.set_accept_state() server_ssl.do_handshake() server.close()
def main(): """ Run an SNI-enabled server which selects between a few certificates in a C{dict} based on the handshake request it receives from a client. """ port = socket() port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) port.bind(('', 8443)) port.listen(3) print('Accepting...', end="") stdout.flush() server, addr = port.accept() print('accepted', addr) server_context = Context(TLSv1_METHOD) server_context.set_tlsext_servername_callback(pick_certificate) server_ssl = Connection(server_context, server) server_ssl.set_accept_state() server_ssl.do_handshake() server.close()
[ "Run", "an", "SNI", "-", "enabled", "server", "which", "selects", "between", "a", "few", "certificates", "in", "a", "C", "{", "dict", "}", "based", "on", "the", "handshake", "request", "it", "receives", "from", "a", "client", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/examples/sni/server.py#L24-L45
[ "def", "main", "(", ")", ":", "port", "=", "socket", "(", ")", "port", ".", "setsockopt", "(", "SOL_SOCKET", ",", "SO_REUSEADDR", ",", "1", ")", "port", ".", "bind", "(", "(", "''", ",", "8443", ")", ")", "port", ".", "listen", "(", "3", ")", "print", "(", "'Accepting...'", ",", "end", "=", "\"\"", ")", "stdout", ".", "flush", "(", ")", "server", ",", "addr", "=", "port", ".", "accept", "(", ")", "print", "(", "'accepted'", ",", "addr", ")", "server_context", "=", "Context", "(", "TLSv1_METHOD", ")", "server_context", ".", "set_tlsext_servername_callback", "(", "pick_certificate", ")", "server_ssl", "=", "Connection", "(", "server_context", ",", "server", ")", "server_ssl", ".", "set_accept_state", "(", ")", "server_ssl", ".", "do_handshake", "(", ")", "server", ".", "close", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
_print_token_factory
Internal helper to provide color names.
PyInquirer/color_print.py
def _print_token_factory(col): """Internal helper to provide color names.""" def _helper(msg): style = style_from_dict({ Token.Color: col, }) tokens = [ (Token.Color, msg) ] print_tokens(tokens, style=style) def _helper_no_terminal(msg): # workaround if we have no terminal print(msg) if sys.stdout.isatty(): return _helper else: return _helper_no_terminal
def _print_token_factory(col): """Internal helper to provide color names.""" def _helper(msg): style = style_from_dict({ Token.Color: col, }) tokens = [ (Token.Color, msg) ] print_tokens(tokens, style=style) def _helper_no_terminal(msg): # workaround if we have no terminal print(msg) if sys.stdout.isatty(): return _helper else: return _helper_no_terminal
[ "Internal", "helper", "to", "provide", "color", "names", "." ]
CITGuru/PyInquirer
python
https://github.com/CITGuru/PyInquirer/blob/10d53723b36ebc7bba311457ec4afd9747a5c777/PyInquirer/color_print.py#L10-L27
[ "def", "_print_token_factory", "(", "col", ")", ":", "def", "_helper", "(", "msg", ")", ":", "style", "=", "style_from_dict", "(", "{", "Token", ".", "Color", ":", "col", ",", "}", ")", "tokens", "=", "[", "(", "Token", ".", "Color", ",", "msg", ")", "]", "print_tokens", "(", "tokens", ",", "style", "=", "style", ")", "def", "_helper_no_terminal", "(", "msg", ")", ":", "# workaround if we have no terminal", "print", "(", "msg", ")", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "return", "_helper", "else", ":", "return", "_helper_no_terminal" ]
10d53723b36ebc7bba311457ec4afd9747a5c777
test
TrelloService.get_service_metadata
Return extra config options to be passed to the TrelloIssue class
bugwarrior/services/trello.py
def get_service_metadata(self): """ Return extra config options to be passed to the TrelloIssue class """ return { 'import_labels_as_tags': self.config.get('import_labels_as_tags', False, asbool), 'label_template': self.config.get('label_template', DEFAULT_LABEL_TEMPLATE), }
def get_service_metadata(self): """ Return extra config options to be passed to the TrelloIssue class """ return { 'import_labels_as_tags': self.config.get('import_labels_as_tags', False, asbool), 'label_template': self.config.get('label_template', DEFAULT_LABEL_TEMPLATE), }
[ "Return", "extra", "config", "options", "to", "be", "passed", "to", "the", "TrelloIssue", "class" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L92-L101
[ "def", "get_service_metadata", "(", "self", ")", ":", "return", "{", "'import_labels_as_tags'", ":", "self", ".", "config", ".", "get", "(", "'import_labels_as_tags'", ",", "False", ",", "asbool", ")", ",", "'label_template'", ":", "self", ".", "config", ".", "get", "(", "'label_template'", ",", "DEFAULT_LABEL_TEMPLATE", ")", ",", "}" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
TrelloService.issues
Returns a list of dicts representing issues from a remote service.
bugwarrior/services/trello.py
def issues(self): """ Returns a list of dicts representing issues from a remote service. """ for board in self.get_boards(): for lst in self.get_lists(board['id']): listextra = dict(boardname=board['name'], listname=lst['name']) for card in self.get_cards(lst['id']): issue = self.get_issue_for_record(card, extra=listextra) issue.update_extra({"annotations": self.annotations(card)}) yield issue
def issues(self): """ Returns a list of dicts representing issues from a remote service. """ for board in self.get_boards(): for lst in self.get_lists(board['id']): listextra = dict(boardname=board['name'], listname=lst['name']) for card in self.get_cards(lst['id']): issue = self.get_issue_for_record(card, extra=listextra) issue.update_extra({"annotations": self.annotations(card)}) yield issue
[ "Returns", "a", "list", "of", "dicts", "representing", "issues", "from", "a", "remote", "service", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L103-L113
[ "def", "issues", "(", "self", ")", ":", "for", "board", "in", "self", ".", "get_boards", "(", ")", ":", "for", "lst", "in", "self", ".", "get_lists", "(", "board", "[", "'id'", "]", ")", ":", "listextra", "=", "dict", "(", "boardname", "=", "board", "[", "'name'", "]", ",", "listname", "=", "lst", "[", "'name'", "]", ")", "for", "card", "in", "self", ".", "get_cards", "(", "lst", "[", "'id'", "]", ")", ":", "issue", "=", "self", ".", "get_issue_for_record", "(", "card", ",", "extra", "=", "listextra", ")", "issue", ".", "update_extra", "(", "{", "\"annotations\"", ":", "self", ".", "annotations", "(", "card", ")", "}", ")", "yield", "issue" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
TrelloService.annotations
A wrapper around get_comments that build the taskwarrior annotations.
bugwarrior/services/trello.py
def annotations(self, card_json): """ A wrapper around get_comments that build the taskwarrior annotations. """ comments = self.get_comments(card_json['id']) annotations = self.build_annotations( ((c['memberCreator']['username'], c['data']['text']) for c in comments), card_json["shortUrl"]) return annotations
def annotations(self, card_json): """ A wrapper around get_comments that build the taskwarrior annotations. """ comments = self.get_comments(card_json['id']) annotations = self.build_annotations( ((c['memberCreator']['username'], c['data']['text']) for c in comments), card_json["shortUrl"]) return annotations
[ "A", "wrapper", "around", "get_comments", "that", "build", "the", "taskwarrior", "annotations", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L115-L122
[ "def", "annotations", "(", "self", ",", "card_json", ")", ":", "comments", "=", "self", ".", "get_comments", "(", "card_json", "[", "'id'", "]", ")", "annotations", "=", "self", ".", "build_annotations", "(", "(", "(", "c", "[", "'memberCreator'", "]", "[", "'username'", "]", ",", "c", "[", "'data'", "]", "[", "'text'", "]", ")", "for", "c", "in", "comments", ")", ",", "card_json", "[", "\"shortUrl\"", "]", ")", "return", "annotations" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
TrelloService.get_boards
Get the list of boards to pull cards from. If the user gave a value to trello.include_boards use that, otherwise ask the Trello API for the user's boards.
bugwarrior/services/trello.py
def get_boards(self): """ Get the list of boards to pull cards from. If the user gave a value to trello.include_boards use that, otherwise ask the Trello API for the user's boards. """ if 'include_boards' in self.config: for boardid in self.config.get('include_boards', to_type=aslist): # Get the board name yield self.api_request( "/1/boards/{id}".format(id=boardid), fields='name') else: boards = self.api_request("/1/members/me/boards", fields='name') for board in boards: yield board
def get_boards(self): """ Get the list of boards to pull cards from. If the user gave a value to trello.include_boards use that, otherwise ask the Trello API for the user's boards. """ if 'include_boards' in self.config: for boardid in self.config.get('include_boards', to_type=aslist): # Get the board name yield self.api_request( "/1/boards/{id}".format(id=boardid), fields='name') else: boards = self.api_request("/1/members/me/boards", fields='name') for board in boards: yield board
[ "Get", "the", "list", "of", "boards", "to", "pull", "cards", "from", ".", "If", "the", "user", "gave", "a", "value", "to", "trello", ".", "include_boards", "use", "that", "otherwise", "ask", "the", "Trello", "API", "for", "the", "user", "s", "boards", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L125-L139
[ "def", "get_boards", "(", "self", ")", ":", "if", "'include_boards'", "in", "self", ".", "config", ":", "for", "boardid", "in", "self", ".", "config", ".", "get", "(", "'include_boards'", ",", "to_type", "=", "aslist", ")", ":", "# Get the board name", "yield", "self", ".", "api_request", "(", "\"/1/boards/{id}\"", ".", "format", "(", "id", "=", "boardid", ")", ",", "fields", "=", "'name'", ")", "else", ":", "boards", "=", "self", ".", "api_request", "(", "\"/1/members/me/boards\"", ",", "fields", "=", "'name'", ")", "for", "board", "in", "boards", ":", "yield", "board" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
TrelloService.get_lists
Returns a list of the filtered lists for the given board This filters the trello lists according to the configuration values of trello.include_lists and trello.exclude_lists.
bugwarrior/services/trello.py
def get_lists(self, board): """ Returns a list of the filtered lists for the given board This filters the trello lists according to the configuration values of trello.include_lists and trello.exclude_lists. """ lists = self.api_request( "/1/boards/{board_id}/lists/open".format(board_id=board), fields='name') include_lists = self.config.get('include_lists', to_type=aslist) if include_lists: lists = [l for l in lists if l['name'] in include_lists] exclude_lists = self.config.get('exclude_lists', to_type=aslist) if exclude_lists: lists = [l for l in lists if l['name'] not in exclude_lists] return lists
def get_lists(self, board): """ Returns a list of the filtered lists for the given board This filters the trello lists according to the configuration values of trello.include_lists and trello.exclude_lists. """ lists = self.api_request( "/1/boards/{board_id}/lists/open".format(board_id=board), fields='name') include_lists = self.config.get('include_lists', to_type=aslist) if include_lists: lists = [l for l in lists if l['name'] in include_lists] exclude_lists = self.config.get('exclude_lists', to_type=aslist) if exclude_lists: lists = [l for l in lists if l['name'] not in exclude_lists] return lists
[ "Returns", "a", "list", "of", "the", "filtered", "lists", "for", "the", "given", "board", "This", "filters", "the", "trello", "lists", "according", "to", "the", "configuration", "values", "of", "trello", ".", "include_lists", "and", "trello", ".", "exclude_lists", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L141-L159
[ "def", "get_lists", "(", "self", ",", "board", ")", ":", "lists", "=", "self", ".", "api_request", "(", "\"/1/boards/{board_id}/lists/open\"", ".", "format", "(", "board_id", "=", "board", ")", ",", "fields", "=", "'name'", ")", "include_lists", "=", "self", ".", "config", ".", "get", "(", "'include_lists'", ",", "to_type", "=", "aslist", ")", "if", "include_lists", ":", "lists", "=", "[", "l", "for", "l", "in", "lists", "if", "l", "[", "'name'", "]", "in", "include_lists", "]", "exclude_lists", "=", "self", ".", "config", ".", "get", "(", "'exclude_lists'", ",", "to_type", "=", "aslist", ")", "if", "exclude_lists", ":", "lists", "=", "[", "l", "for", "l", "in", "lists", "if", "l", "[", "'name'", "]", "not", "in", "exclude_lists", "]", "return", "lists" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
TrelloService.get_cards
Returns an iterator for the cards in a given list, filtered according to configuration values of trello.only_if_assigned and trello.also_unassigned
bugwarrior/services/trello.py
def get_cards(self, list_id): """ Returns an iterator for the cards in a given list, filtered according to configuration values of trello.only_if_assigned and trello.also_unassigned """ params = {'fields': 'name,idShort,shortLink,shortUrl,url,labels,due'} member = self.config.get('only_if_assigned', None) unassigned = self.config.get('also_unassigned', False, asbool) if member is not None: params['members'] = 'true' params['member_fields'] = 'username' cards = self.api_request( "/1/lists/{list_id}/cards/open".format(list_id=list_id), **params) for card in cards: if (member is None or member in [m['username'] for m in card['members']] or (unassigned and not card['members'])): yield card
def get_cards(self, list_id): """ Returns an iterator for the cards in a given list, filtered according to configuration values of trello.only_if_assigned and trello.also_unassigned """ params = {'fields': 'name,idShort,shortLink,shortUrl,url,labels,due'} member = self.config.get('only_if_assigned', None) unassigned = self.config.get('also_unassigned', False, asbool) if member is not None: params['members'] = 'true' params['member_fields'] = 'username' cards = self.api_request( "/1/lists/{list_id}/cards/open".format(list_id=list_id), **params) for card in cards: if (member is None or member in [m['username'] for m in card['members']] or (unassigned and not card['members'])): yield card
[ "Returns", "an", "iterator", "for", "the", "cards", "in", "a", "given", "list", "filtered", "according", "to", "configuration", "values", "of", "trello", ".", "only_if_assigned", "and", "trello", ".", "also_unassigned" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L161-L178
[ "def", "get_cards", "(", "self", ",", "list_id", ")", ":", "params", "=", "{", "'fields'", ":", "'name,idShort,shortLink,shortUrl,url,labels,due'", "}", "member", "=", "self", ".", "config", ".", "get", "(", "'only_if_assigned'", ",", "None", ")", "unassigned", "=", "self", ".", "config", ".", "get", "(", "'also_unassigned'", ",", "False", ",", "asbool", ")", "if", "member", "is", "not", "None", ":", "params", "[", "'members'", "]", "=", "'true'", "params", "[", "'member_fields'", "]", "=", "'username'", "cards", "=", "self", ".", "api_request", "(", "\"/1/lists/{list_id}/cards/open\"", ".", "format", "(", "list_id", "=", "list_id", ")", ",", "*", "*", "params", ")", "for", "card", "in", "cards", ":", "if", "(", "member", "is", "None", "or", "member", "in", "[", "m", "[", "'username'", "]", "for", "m", "in", "card", "[", "'members'", "]", "]", "or", "(", "unassigned", "and", "not", "card", "[", "'members'", "]", ")", ")", ":", "yield", "card" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
TrelloService.get_comments
Returns an iterator for the comments on a certain card.
bugwarrior/services/trello.py
def get_comments(self, card_id): """ Returns an iterator for the comments on a certain card. """ params = {'filter': 'commentCard', 'memberCreator_fields': 'username'} comments = self.api_request( "/1/cards/{card_id}/actions".format(card_id=card_id), **params) for comment in comments: assert comment['type'] == 'commentCard' yield comment
def get_comments(self, card_id): """ Returns an iterator for the comments on a certain card. """ params = {'filter': 'commentCard', 'memberCreator_fields': 'username'} comments = self.api_request( "/1/cards/{card_id}/actions".format(card_id=card_id), **params) for comment in comments: assert comment['type'] == 'commentCard' yield comment
[ "Returns", "an", "iterator", "for", "the", "comments", "on", "a", "certain", "card", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L180-L188
[ "def", "get_comments", "(", "self", ",", "card_id", ")", ":", "params", "=", "{", "'filter'", ":", "'commentCard'", ",", "'memberCreator_fields'", ":", "'username'", "}", "comments", "=", "self", ".", "api_request", "(", "\"/1/cards/{card_id}/actions\"", ".", "format", "(", "card_id", "=", "card_id", ")", ",", "*", "*", "params", ")", "for", "comment", "in", "comments", ":", "assert", "comment", "[", "'type'", "]", "==", "'commentCard'", "yield", "comment" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
TrelloService.api_request
Make a trello API request. This takes an absolute url (without protocol and host) and a list of argumnets and return a GET request with the key and token from the configuration
bugwarrior/services/trello.py
def api_request(self, url, **params): """ Make a trello API request. This takes an absolute url (without protocol and host) and a list of argumnets and return a GET request with the key and token from the configuration """ params['key'] = self.config.get('api_key'), params['token'] = self.config.get('token'), url = "https://api.trello.com" + url return self.json_response(requests.get(url, params=params))
def api_request(self, url, **params): """ Make a trello API request. This takes an absolute url (without protocol and host) and a list of argumnets and return a GET request with the key and token from the configuration """ params['key'] = self.config.get('api_key'), params['token'] = self.config.get('token'), url = "https://api.trello.com" + url return self.json_response(requests.get(url, params=params))
[ "Make", "a", "trello", "API", "request", ".", "This", "takes", "an", "absolute", "url", "(", "without", "protocol", "and", "host", ")", "and", "a", "list", "of", "argumnets", "and", "return", "a", "GET", "request", "with", "the", "key", "and", "token", "from", "the", "configuration" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/trello.py#L190-L199
[ "def", "api_request", "(", "self", ",", "url", ",", "*", "*", "params", ")", ":", "params", "[", "'key'", "]", "=", "self", ".", "config", ".", "get", "(", "'api_key'", ")", ",", "params", "[", "'token'", "]", "=", "self", ".", "config", ".", "get", "(", "'token'", ")", ",", "url", "=", "\"https://api.trello.com\"", "+", "url", "return", "self", ".", "json_response", "(", "requests", ".", "get", "(", "url", ",", "params", "=", "params", ")", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
PagureService.get_issues
Grab all the issues
bugwarrior/services/pagure.py
def get_issues(self, repo, keys): """ Grab all the issues """ key1, key2 = keys key3 = key1[:-1] # Just the singular form of key1 url = self.base_url + "/api/0/" + repo + "/" + key1 response = self.session.get(url, params=dict(status='Open')) if not bool(response): error = response.json() code = error['error_code'] if code == 'ETRACKERDISABLED': return [] else: raise IOError('Failed to talk to %r %r' % (url, error)) issues = [] for result in response.json()[key2]: idx = six.text_type(result['id']) result['html_url'] = "/".join([self.base_url, repo, key3, idx]) issues.append((repo, result)) return issues
def get_issues(self, repo, keys): """ Grab all the issues """ key1, key2 = keys key3 = key1[:-1] # Just the singular form of key1 url = self.base_url + "/api/0/" + repo + "/" + key1 response = self.session.get(url, params=dict(status='Open')) if not bool(response): error = response.json() code = error['error_code'] if code == 'ETRACKERDISABLED': return [] else: raise IOError('Failed to talk to %r %r' % (url, error)) issues = [] for result in response.json()[key2]: idx = six.text_type(result['id']) result['html_url'] = "/".join([self.base_url, repo, key3, idx]) issues.append((repo, result)) return issues
[ "Grab", "all", "the", "issues" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/pagure.py#L131-L153
[ "def", "get_issues", "(", "self", ",", "repo", ",", "keys", ")", ":", "key1", ",", "key2", "=", "keys", "key3", "=", "key1", "[", ":", "-", "1", "]", "# Just the singular form of key1", "url", "=", "self", ".", "base_url", "+", "\"/api/0/\"", "+", "repo", "+", "\"/\"", "+", "key1", "response", "=", "self", ".", "session", ".", "get", "(", "url", ",", "params", "=", "dict", "(", "status", "=", "'Open'", ")", ")", "if", "not", "bool", "(", "response", ")", ":", "error", "=", "response", ".", "json", "(", ")", "code", "=", "error", "[", "'error_code'", "]", "if", "code", "==", "'ETRACKERDISABLED'", ":", "return", "[", "]", "else", ":", "raise", "IOError", "(", "'Failed to talk to %r %r'", "%", "(", "url", ",", "error", ")", ")", "issues", "=", "[", "]", "for", "result", "in", "response", ".", "json", "(", ")", "[", "key2", "]", ":", "idx", "=", "six", ".", "text_type", "(", "result", "[", "'id'", "]", ")", "result", "[", "'html_url'", "]", "=", "\"/\"", ".", "join", "(", "[", "self", ".", "base_url", ",", "repo", ",", "key3", ",", "idx", "]", ")", "issues", ".", "append", "(", "(", "repo", ",", "result", ")", ")", "return", "issues" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
ActiveCollab2Client.get_issue_generator
Approach: 1. Get user ID from bugwarriorrc file 2. Get list of tickets from /user-tasks for a given project 3. For each ticket/task returned from #2, get ticket/task info and check if logged-in user is primary (look at `is_owner` and `user_id`)
bugwarrior/services/activecollab2.py
def get_issue_generator(self, user_id, project_id, project_name): """ Approach: 1. Get user ID from bugwarriorrc file 2. Get list of tickets from /user-tasks for a given project 3. For each ticket/task returned from #2, get ticket/task info and check if logged-in user is primary (look at `is_owner` and `user_id`) """ user_tasks_data = self.call_api( "/projects/" + six.text_type(project_id) + "/user-tasks") for key, task in enumerate(user_tasks_data): assigned_task = self.get_task_dict(project_id, key, task) if assigned_task: log.debug( " Adding '" + assigned_task['description'] + "' to task list.") yield assigned_task
def get_issue_generator(self, user_id, project_id, project_name): """ Approach: 1. Get user ID from bugwarriorrc file 2. Get list of tickets from /user-tasks for a given project 3. For each ticket/task returned from #2, get ticket/task info and check if logged-in user is primary (look at `is_owner` and `user_id`) """ user_tasks_data = self.call_api( "/projects/" + six.text_type(project_id) + "/user-tasks") for key, task in enumerate(user_tasks_data): assigned_task = self.get_task_dict(project_id, key, task) if assigned_task: log.debug( " Adding '" + assigned_task['description'] + "' to task list.") yield assigned_task
[ "Approach", ":" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/activecollab2.py#L46-L68
[ "def", "get_issue_generator", "(", "self", ",", "user_id", ",", "project_id", ",", "project_name", ")", ":", "user_tasks_data", "=", "self", ".", "call_api", "(", "\"/projects/\"", "+", "six", ".", "text_type", "(", "project_id", ")", "+", "\"/user-tasks\"", ")", "for", "key", ",", "task", "in", "enumerate", "(", "user_tasks_data", ")", ":", "assigned_task", "=", "self", ".", "get_task_dict", "(", "project_id", ",", "key", ",", "task", ")", "if", "assigned_task", ":", "log", ".", "debug", "(", "\" Adding '\"", "+", "assigned_task", "[", "'description'", "]", "+", "\"' to task list.\"", ")", "yield", "assigned_task" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
GithubClient._api_url
Build the full url to the API endpoint
bugwarrior/services/github.py
def _api_url(self, path, **context): """ Build the full url to the API endpoint """ if self.host == 'github.com': baseurl = "https://api.github.com" else: baseurl = "https://{}/api/v3".format(self.host) return baseurl + path.format(**context)
def _api_url(self, path, **context): """ Build the full url to the API endpoint """ if self.host == 'github.com': baseurl = "https://api.github.com" else: baseurl = "https://{}/api/v3".format(self.host) return baseurl + path.format(**context)
[ "Build", "the", "full", "url", "to", "the", "API", "endpoint" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L26-L32
[ "def", "_api_url", "(", "self", ",", "path", ",", "*", "*", "context", ")", ":", "if", "self", ".", "host", "==", "'github.com'", ":", "baseurl", "=", "\"https://api.github.com\"", "else", ":", "baseurl", "=", "\"https://{}/api/v3\"", ".", "format", "(", "self", ".", "host", ")", "return", "baseurl", "+", "path", ".", "format", "(", "*", "*", "context", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
GithubClient.get_query
Run a generic issue/PR query
bugwarrior/services/github.py
def get_query(self, query): """Run a generic issue/PR query""" url = self._api_url( "/search/issues?q={query}&per_page=100", query=query) return self._getter(url, subkey='items')
def get_query(self, query): """Run a generic issue/PR query""" url = self._api_url( "/search/issues?q={query}&per_page=100", query=query) return self._getter(url, subkey='items')
[ "Run", "a", "generic", "issue", "/", "PR", "query" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L40-L44
[ "def", "get_query", "(", "self", ",", "query", ")", ":", "url", "=", "self", ".", "_api_url", "(", "\"/search/issues?q={query}&per_page=100\"", ",", "query", "=", "query", ")", "return", "self", ".", "_getter", "(", "url", ",", "subkey", "=", "'items'", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
GithubClient._getter
Pagination utility. Obnoxious.
bugwarrior/services/github.py
def _getter(self, url, subkey=None): """ Pagination utility. Obnoxious. """ kwargs = {} if 'basic' in self.auth: kwargs['auth'] = self.auth['basic'] results = [] link = dict(next=url) while 'next' in link: response = self.session.get(link['next'], **kwargs) # Warn about the mis-leading 404 error code. See: # https://github.com/ralphbean/bugwarrior/issues/374 if response.status_code == 404 and 'token' in self.auth: log.warn("A '404' from github may indicate an auth " "failure. Make sure both that your token is correct " "and that it has 'public_repo' and not 'public " "access' rights.") json_res = self.json_response(response) if subkey is not None: json_res = json_res[subkey] results += json_res link = self._link_field_to_dict(response.headers.get('link', None)) return results
def _getter(self, url, subkey=None): """ Pagination utility. Obnoxious. """ kwargs = {} if 'basic' in self.auth: kwargs['auth'] = self.auth['basic'] results = [] link = dict(next=url) while 'next' in link: response = self.session.get(link['next'], **kwargs) # Warn about the mis-leading 404 error code. See: # https://github.com/ralphbean/bugwarrior/issues/374 if response.status_code == 404 and 'token' in self.auth: log.warn("A '404' from github may indicate an auth " "failure. Make sure both that your token is correct " "and that it has 'public_repo' and not 'public " "access' rights.") json_res = self.json_response(response) if subkey is not None: json_res = json_res[subkey] results += json_res link = self._link_field_to_dict(response.headers.get('link', None)) return results
[ "Pagination", "utility", ".", "Obnoxious", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L74-L104
[ "def", "_getter", "(", "self", ",", "url", ",", "subkey", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "'basic'", "in", "self", ".", "auth", ":", "kwargs", "[", "'auth'", "]", "=", "self", ".", "auth", "[", "'basic'", "]", "results", "=", "[", "]", "link", "=", "dict", "(", "next", "=", "url", ")", "while", "'next'", "in", "link", ":", "response", "=", "self", ".", "session", ".", "get", "(", "link", "[", "'next'", "]", ",", "*", "*", "kwargs", ")", "# Warn about the mis-leading 404 error code. See:", "# https://github.com/ralphbean/bugwarrior/issues/374", "if", "response", ".", "status_code", "==", "404", "and", "'token'", "in", "self", ".", "auth", ":", "log", ".", "warn", "(", "\"A '404' from github may indicate an auth \"", "\"failure. Make sure both that your token is correct \"", "\"and that it has 'public_repo' and not 'public \"", "\"access' rights.\"", ")", "json_res", "=", "self", ".", "json_response", "(", "response", ")", "if", "subkey", "is", "not", "None", ":", "json_res", "=", "json_res", "[", "subkey", "]", "results", "+=", "json_res", "link", "=", "self", ".", "_link_field_to_dict", "(", "response", ".", "headers", ".", "get", "(", "'link'", ",", "None", ")", ")", "return", "results" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
GithubClient._link_field_to_dict
Utility for ripping apart github's Link header field. It's kind of ugly.
bugwarrior/services/github.py
def _link_field_to_dict(field): """ Utility for ripping apart github's Link header field. It's kind of ugly. """ if not field: return dict() return dict([ ( part.split('; ')[1][5:-1], part.split('; ')[0][1:-1], ) for part in field.split(', ') ])
def _link_field_to_dict(field): """ Utility for ripping apart github's Link header field. It's kind of ugly. """ if not field: return dict() return dict([ ( part.split('; ')[1][5:-1], part.split('; ')[0][1:-1], ) for part in field.split(', ') ])
[ "Utility", "for", "ripping", "apart", "github", "s", "Link", "header", "field", ".", "It", "s", "kind", "of", "ugly", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L107-L120
[ "def", "_link_field_to_dict", "(", "field", ")", ":", "if", "not", "field", ":", "return", "dict", "(", ")", "return", "dict", "(", "[", "(", "part", ".", "split", "(", "'; '", ")", "[", "1", "]", "[", "5", ":", "-", "1", "]", ",", "part", ".", "split", "(", "'; '", ")", "[", "0", "]", "[", "1", ":", "-", "1", "]", ",", ")", "for", "part", "in", "field", ".", "split", "(", "', '", ")", "]", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
GithubService.get_owned_repo_issues
Grab all the issues
bugwarrior/services/github.py
def get_owned_repo_issues(self, tag): """ Grab all the issues """ issues = {} for issue in self.client.get_issues(*tag.split('/')): issues[issue['url']] = (tag, issue) return issues
def get_owned_repo_issues(self, tag): """ Grab all the issues """ issues = {} for issue in self.client.get_issues(*tag.split('/')): issues[issue['url']] = (tag, issue) return issues
[ "Grab", "all", "the", "issues" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L328-L333
[ "def", "get_owned_repo_issues", "(", "self", ",", "tag", ")", ":", "issues", "=", "{", "}", "for", "issue", "in", "self", ".", "client", ".", "get_issues", "(", "*", "tag", ".", "split", "(", "'/'", ")", ")", ":", "issues", "[", "issue", "[", "'url'", "]", "]", "=", "(", "tag", ",", "issue", ")", "return", "issues" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
GithubService.get_query
Grab all issues matching a github query
bugwarrior/services/github.py
def get_query(self, query): """ Grab all issues matching a github query """ issues = {} for issue in self.client.get_query(query): url = issue['html_url'] try: repo = self.get_repository_from_issue(issue) except ValueError as e: log.critical(e) else: issues[url] = (repo, issue) return issues
def get_query(self, query): """ Grab all issues matching a github query """ issues = {} for issue in self.client.get_query(query): url = issue['html_url'] try: repo = self.get_repository_from_issue(issue) except ValueError as e: log.critical(e) else: issues[url] = (repo, issue) return issues
[ "Grab", "all", "issues", "matching", "a", "github", "query" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L335-L346
[ "def", "get_query", "(", "self", ",", "query", ")", ":", "issues", "=", "{", "}", "for", "issue", "in", "self", ".", "client", ".", "get_query", "(", "query", ")", ":", "url", "=", "issue", "[", "'html_url'", "]", "try", ":", "repo", "=", "self", ".", "get_repository_from_issue", "(", "issue", ")", "except", "ValueError", "as", "e", ":", "log", ".", "critical", "(", "e", ")", "else", ":", "issues", "[", "url", "]", "=", "(", "repo", ",", "issue", ")", "return", "issues" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
GithubService._reqs
Grab all the pull requests
bugwarrior/services/github.py
def _reqs(self, tag): """ Grab all the pull requests """ return [ (tag, i) for i in self.client.get_pulls(*tag.split('/')) ]
def _reqs(self, tag): """ Grab all the pull requests """ return [ (tag, i) for i in self.client.get_pulls(*tag.split('/')) ]
[ "Grab", "all", "the", "pull", "requests" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L389-L394
[ "def", "_reqs", "(", "self", ",", "tag", ")", ":", "return", "[", "(", "tag", ",", "i", ")", "for", "i", "in", "self", ".", "client", ".", "get_pulls", "(", "*", "tag", ".", "split", "(", "'/'", ")", ")", "]" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
_aggregate_issues
This worker function is separated out from the main :func:`aggregate_issues` func only so that we can use multiprocessing on it for speed reasons.
bugwarrior/services/__init__.py
def _aggregate_issues(conf, main_section, target, queue, service_name): """ This worker function is separated out from the main :func:`aggregate_issues` func only so that we can use multiprocessing on it for speed reasons. """ start = time.time() try: service = get_service(service_name)(conf, main_section, target) issue_count = 0 for issue in service.issues(): queue.put(issue) issue_count += 1 except SystemExit as e: log.critical(str(e)) queue.put((SERVICE_FINISHED_ERROR, (target, e))) except BaseException as e: if hasattr(e, 'request') and e.request: # Exceptions raised by requests library have the HTTP request # object stored as attribute. The request can have hooks attached # to it, and we need to remove them, as there can be unpickleable # methods. There is no one left to call these hooks anyway. e.request.hooks = {} log.exception("Worker for [%s] failed: %s" % (target, e)) queue.put((SERVICE_FINISHED_ERROR, (target, e))) else: queue.put((SERVICE_FINISHED_OK, (target, issue_count, ))) finally: duration = time.time() - start log.info("Done with [%s] in %fs" % (target, duration))
def _aggregate_issues(conf, main_section, target, queue, service_name): """ This worker function is separated out from the main :func:`aggregate_issues` func only so that we can use multiprocessing on it for speed reasons. """ start = time.time() try: service = get_service(service_name)(conf, main_section, target) issue_count = 0 for issue in service.issues(): queue.put(issue) issue_count += 1 except SystemExit as e: log.critical(str(e)) queue.put((SERVICE_FINISHED_ERROR, (target, e))) except BaseException as e: if hasattr(e, 'request') and e.request: # Exceptions raised by requests library have the HTTP request # object stored as attribute. The request can have hooks attached # to it, and we need to remove them, as there can be unpickleable # methods. There is no one left to call these hooks anyway. e.request.hooks = {} log.exception("Worker for [%s] failed: %s" % (target, e)) queue.put((SERVICE_FINISHED_ERROR, (target, e))) else: queue.put((SERVICE_FINISHED_OK, (target, issue_count, ))) finally: duration = time.time() - start log.info("Done with [%s] in %fs" % (target, duration))
[ "This", "worker", "function", "is", "separated", "out", "from", "the", "main", ":", "func", ":", "aggregate_issues", "func", "only", "so", "that", "we", "can", "use", "multiprocessing", "on", "it", "for", "speed", "reasons", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/__init__.py#L483-L513
[ "def", "_aggregate_issues", "(", "conf", ",", "main_section", ",", "target", ",", "queue", ",", "service_name", ")", ":", "start", "=", "time", ".", "time", "(", ")", "try", ":", "service", "=", "get_service", "(", "service_name", ")", "(", "conf", ",", "main_section", ",", "target", ")", "issue_count", "=", "0", "for", "issue", "in", "service", ".", "issues", "(", ")", ":", "queue", ".", "put", "(", "issue", ")", "issue_count", "+=", "1", "except", "SystemExit", "as", "e", ":", "log", ".", "critical", "(", "str", "(", "e", ")", ")", "queue", ".", "put", "(", "(", "SERVICE_FINISHED_ERROR", ",", "(", "target", ",", "e", ")", ")", ")", "except", "BaseException", "as", "e", ":", "if", "hasattr", "(", "e", ",", "'request'", ")", "and", "e", ".", "request", ":", "# Exceptions raised by requests library have the HTTP request", "# object stored as attribute. The request can have hooks attached", "# to it, and we need to remove them, as there can be unpickleable", "# methods. There is no one left to call these hooks anyway.", "e", ".", "request", ".", "hooks", "=", "{", "}", "log", ".", "exception", "(", "\"Worker for [%s] failed: %s\"", "%", "(", "target", ",", "e", ")", ")", "queue", ".", "put", "(", "(", "SERVICE_FINISHED_ERROR", ",", "(", "target", ",", "e", ")", ")", ")", "else", ":", "queue", ".", "put", "(", "(", "SERVICE_FINISHED_OK", ",", "(", "target", ",", "issue_count", ",", ")", ")", ")", "finally", ":", "duration", "=", "time", ".", "time", "(", ")", "-", "start", "log", ".", "info", "(", "\"Done with [%s] in %fs\"", "%", "(", "target", ",", "duration", ")", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
aggregate_issues
Return all issues from every target.
bugwarrior/services/__init__.py
def aggregate_issues(conf, main_section, debug): """ Return all issues from every target. """ log.info("Starting to aggregate remote issues.") # Create and call service objects for every target in the config targets = aslist(conf.get(main_section, 'targets')) queue = multiprocessing.Queue() log.info("Spawning %i workers." % len(targets)) processes = [] if debug: for target in targets: _aggregate_issues( conf, main_section, target, queue, conf.get(target, 'service') ) else: for target in targets: proc = multiprocessing.Process( target=_aggregate_issues, args=(conf, main_section, target, queue, conf.get(target, 'service')) ) proc.start() processes.append(proc) # Sleep for 1 second here to try and avoid a race condition where # all N workers start up and ask the gpg-agent process for # information at the same time. This causes gpg-agent to fumble # and tell some of our workers some incomplete things. time.sleep(1) currently_running = len(targets) while currently_running > 0: issue = queue.get(True) if isinstance(issue, tuple): completion_type, args = issue if completion_type == SERVICE_FINISHED_ERROR: target, e = args log.info("Terminating workers") for process in processes: process.terminate() raise RuntimeError( "critical error in target '{}'".format(target)) currently_running -= 1 continue yield issue log.info("Done aggregating remote issues.")
def aggregate_issues(conf, main_section, debug): """ Return all issues from every target. """ log.info("Starting to aggregate remote issues.") # Create and call service objects for every target in the config targets = aslist(conf.get(main_section, 'targets')) queue = multiprocessing.Queue() log.info("Spawning %i workers." % len(targets)) processes = [] if debug: for target in targets: _aggregate_issues( conf, main_section, target, queue, conf.get(target, 'service') ) else: for target in targets: proc = multiprocessing.Process( target=_aggregate_issues, args=(conf, main_section, target, queue, conf.get(target, 'service')) ) proc.start() processes.append(proc) # Sleep for 1 second here to try and avoid a race condition where # all N workers start up and ask the gpg-agent process for # information at the same time. This causes gpg-agent to fumble # and tell some of our workers some incomplete things. time.sleep(1) currently_running = len(targets) while currently_running > 0: issue = queue.get(True) if isinstance(issue, tuple): completion_type, args = issue if completion_type == SERVICE_FINISHED_ERROR: target, e = args log.info("Terminating workers") for process in processes: process.terminate() raise RuntimeError( "critical error in target '{}'".format(target)) currently_running -= 1 continue yield issue log.info("Done aggregating remote issues.")
[ "Return", "all", "issues", "from", "every", "target", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/__init__.py#L516-L568
[ "def", "aggregate_issues", "(", "conf", ",", "main_section", ",", "debug", ")", ":", "log", ".", "info", "(", "\"Starting to aggregate remote issues.\"", ")", "# Create and call service objects for every target in the config", "targets", "=", "aslist", "(", "conf", ".", "get", "(", "main_section", ",", "'targets'", ")", ")", "queue", "=", "multiprocessing", ".", "Queue", "(", ")", "log", ".", "info", "(", "\"Spawning %i workers.\"", "%", "len", "(", "targets", ")", ")", "processes", "=", "[", "]", "if", "debug", ":", "for", "target", "in", "targets", ":", "_aggregate_issues", "(", "conf", ",", "main_section", ",", "target", ",", "queue", ",", "conf", ".", "get", "(", "target", ",", "'service'", ")", ")", "else", ":", "for", "target", "in", "targets", ":", "proc", "=", "multiprocessing", ".", "Process", "(", "target", "=", "_aggregate_issues", ",", "args", "=", "(", "conf", ",", "main_section", ",", "target", ",", "queue", ",", "conf", ".", "get", "(", "target", ",", "'service'", ")", ")", ")", "proc", ".", "start", "(", ")", "processes", ".", "append", "(", "proc", ")", "# Sleep for 1 second here to try and avoid a race condition where", "# all N workers start up and ask the gpg-agent process for", "# information at the same time. This causes gpg-agent to fumble", "# and tell some of our workers some incomplete things.", "time", ".", "sleep", "(", "1", ")", "currently_running", "=", "len", "(", "targets", ")", "while", "currently_running", ">", "0", ":", "issue", "=", "queue", ".", "get", "(", "True", ")", "if", "isinstance", "(", "issue", ",", "tuple", ")", ":", "completion_type", ",", "args", "=", "issue", "if", "completion_type", "==", "SERVICE_FINISHED_ERROR", ":", "target", ",", "e", "=", "args", "log", ".", "info", "(", "\"Terminating workers\"", ")", "for", "process", "in", "processes", ":", "process", ".", "terminate", "(", ")", "raise", "RuntimeError", "(", "\"critical error in target '{}'\"", ".", "format", "(", "target", ")", ")", "currently_running", "-=", "1", "continue", "yield", "issue", "log", ".", "info", "(", "\"Done aggregating remote issues.\"", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
IssueService._get_config_or_default
Return a main config value, or default if it does not exist.
bugwarrior/services/__init__.py
def _get_config_or_default(self, key, default, as_type=lambda x: x): """Return a main config value, or default if it does not exist.""" if self.main_config.has_option(self.main_section, key): return as_type(self.main_config.get(self.main_section, key)) return default
def _get_config_or_default(self, key, default, as_type=lambda x: x): """Return a main config value, or default if it does not exist.""" if self.main_config.has_option(self.main_section, key): return as_type(self.main_config.get(self.main_section, key)) return default
[ "Return", "a", "main", "config", "value", "or", "default", "if", "it", "does", "not", "exist", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/__init__.py#L74-L79
[ "def", "_get_config_or_default", "(", "self", ",", "key", ",", "default", ",", "as_type", "=", "lambda", "x", ":", "x", ")", ":", "if", "self", ".", "main_config", ".", "has_option", "(", "self", ".", "main_section", ",", "key", ")", ":", "return", "as_type", "(", "self", ".", "main_config", ".", "get", "(", "self", ".", "main_section", ",", "key", ")", ")", "return", "default" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
IssueService.get_templates
Get any defined templates for configuration values. Users can override the value of any Taskwarrior field using this feature on a per-key basis. The key should be the name of the field to you would like to configure the value of, followed by '_template', and the value should be a Jinja template generating the field's value. As context variables, all fields on the taskwarrior record are available. For example, to prefix the returned project name for tickets returned by a service with 'workproject_', you could add an entry reading: project_template = workproject_{{project}} Or, if you'd simply like to override the returned project name for all tickets incoming from a specific service, you could add an entry like: project_template = myprojectname The above would cause all issues to recieve a project name of 'myprojectname', regardless of what the project name of the generated issue was.
bugwarrior/services/__init__.py
def get_templates(self): """ Get any defined templates for configuration values. Users can override the value of any Taskwarrior field using this feature on a per-key basis. The key should be the name of the field to you would like to configure the value of, followed by '_template', and the value should be a Jinja template generating the field's value. As context variables, all fields on the taskwarrior record are available. For example, to prefix the returned project name for tickets returned by a service with 'workproject_', you could add an entry reading: project_template = workproject_{{project}} Or, if you'd simply like to override the returned project name for all tickets incoming from a specific service, you could add an entry like: project_template = myprojectname The above would cause all issues to recieve a project name of 'myprojectname', regardless of what the project name of the generated issue was. """ templates = {} for key in six.iterkeys(Task.FIELDS): template_key = '%s_template' % key if template_key in self.config: templates[key] = self.config.get(template_key) return templates
def get_templates(self): """ Get any defined templates for configuration values. Users can override the value of any Taskwarrior field using this feature on a per-key basis. The key should be the name of the field to you would like to configure the value of, followed by '_template', and the value should be a Jinja template generating the field's value. As context variables, all fields on the taskwarrior record are available. For example, to prefix the returned project name for tickets returned by a service with 'workproject_', you could add an entry reading: project_template = workproject_{{project}} Or, if you'd simply like to override the returned project name for all tickets incoming from a specific service, you could add an entry like: project_template = myprojectname The above would cause all issues to recieve a project name of 'myprojectname', regardless of what the project name of the generated issue was. """ templates = {} for key in six.iterkeys(Task.FIELDS): template_key = '%s_template' % key if template_key in self.config: templates[key] = self.config.get(template_key) return templates
[ "Get", "any", "defined", "templates", "for", "configuration", "values", "." ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/__init__.py#L82-L114
[ "def", "get_templates", "(", "self", ")", ":", "templates", "=", "{", "}", "for", "key", "in", "six", ".", "iterkeys", "(", "Task", ".", "FIELDS", ")", ":", "template_key", "=", "'%s_template'", "%", "key", "if", "template_key", "in", "self", ".", "config", ":", "templates", "[", "key", "]", "=", "self", ".", "config", ".", "get", "(", "template_key", ")", "return", "templates" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
IssueService.validate_config
Validate generic options for a particular target
bugwarrior/services/__init__.py
def validate_config(cls, service_config, target): """ Validate generic options for a particular target """ if service_config.has_option(target, 'only_if_assigned'): die("[%s] has an 'only_if_assigned' option. Should be " "'%s.only_if_assigned'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'also_unassigned'): die("[%s] has an 'also_unassigned' option. Should be " "'%s.also_unassigned'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'default_priority'): die("[%s] has a 'default_priority' option. Should be " "'%s.default_priority'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'add_tags'): die("[%s] has an 'add_tags' option. Should be " "'%s.add_tags'." % (target, cls.CONFIG_PREFIX))
def validate_config(cls, service_config, target): """ Validate generic options for a particular target """ if service_config.has_option(target, 'only_if_assigned'): die("[%s] has an 'only_if_assigned' option. Should be " "'%s.only_if_assigned'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'also_unassigned'): die("[%s] has an 'also_unassigned' option. Should be " "'%s.also_unassigned'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'default_priority'): die("[%s] has a 'default_priority' option. Should be " "'%s.default_priority'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'add_tags'): die("[%s] has an 'add_tags' option. Should be " "'%s.add_tags'." % (target, cls.CONFIG_PREFIX))
[ "Validate", "generic", "options", "for", "a", "particular", "target" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/__init__.py#L161-L174
[ "def", "validate_config", "(", "cls", ",", "service_config", ",", "target", ")", ":", "if", "service_config", ".", "has_option", "(", "target", ",", "'only_if_assigned'", ")", ":", "die", "(", "\"[%s] has an 'only_if_assigned' option. Should be \"", "\"'%s.only_if_assigned'.\"", "%", "(", "target", ",", "cls", ".", "CONFIG_PREFIX", ")", ")", "if", "service_config", ".", "has_option", "(", "target", ",", "'also_unassigned'", ")", ":", "die", "(", "\"[%s] has an 'also_unassigned' option. Should be \"", "\"'%s.also_unassigned'.\"", "%", "(", "target", ",", "cls", ".", "CONFIG_PREFIX", ")", ")", "if", "service_config", ".", "has_option", "(", "target", ",", "'default_priority'", ")", ":", "die", "(", "\"[%s] has a 'default_priority' option. Should be \"", "\"'%s.default_priority'.\"", "%", "(", "target", ",", "cls", ".", "CONFIG_PREFIX", ")", ")", "if", "service_config", ".", "has_option", "(", "target", ",", "'add_tags'", ")", ":", "die", "(", "\"[%s] has an 'add_tags' option. Should be \"", "\"'%s.add_tags'.\"", "%", "(", "target", ",", "cls", ".", "CONFIG_PREFIX", ")", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
IssueService.include
Return true if the issue in question should be included
bugwarrior/services/__init__.py
def include(self, issue): """ Return true if the issue in question should be included """ only_if_assigned = self.config.get('only_if_assigned', None) if only_if_assigned: owner = self.get_owner(issue) include_owners = [only_if_assigned] if self.config.get('also_unassigned', None, asbool): include_owners.append(None) return owner in include_owners only_if_author = self.config.get('only_if_author', None) if only_if_author: return self.get_author(issue) == only_if_author return True
def include(self, issue): """ Return true if the issue in question should be included """ only_if_assigned = self.config.get('only_if_assigned', None) if only_if_assigned: owner = self.get_owner(issue) include_owners = [only_if_assigned] if self.config.get('also_unassigned', None, asbool): include_owners.append(None) return owner in include_owners only_if_author = self.config.get('only_if_author', None) if only_if_author: return self.get_author(issue) == only_if_author return True
[ "Return", "true", "if", "the", "issue", "in", "question", "should", "be", "included" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/__init__.py#L176-L194
[ "def", "include", "(", "self", ",", "issue", ")", ":", "only_if_assigned", "=", "self", ".", "config", ".", "get", "(", "'only_if_assigned'", ",", "None", ")", "if", "only_if_assigned", ":", "owner", "=", "self", ".", "get_owner", "(", "issue", ")", "include_owners", "=", "[", "only_if_assigned", "]", "if", "self", ".", "config", ".", "get", "(", "'also_unassigned'", ",", "None", ",", "asbool", ")", ":", "include_owners", ".", "append", "(", "None", ")", "return", "owner", "in", "include_owners", "only_if_author", "=", "self", ".", "config", ".", "get", "(", "'only_if_author'", ",", "None", ")", "if", "only_if_author", ":", "return", "self", ".", "get_author", "(", "issue", ")", "==", "only_if_author", "return", "True" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
make_table
Make a RST-compatible table From http://stackoverflow.com/a/12539081
bugwarrior/docs/generate_service_template.py
def make_table(grid): """ Make a RST-compatible table From http://stackoverflow.com/a/12539081 """ cell_width = 2 + max( reduce( lambda x, y: x+y, [[len(item) for item in row] for row in grid], [] ) ) num_cols = len(grid[0]) rst = table_div(num_cols, cell_width, 0) header_flag = 1 for row in grid: rst = rst + '| ' + '| '.join( [normalize_cell(x, cell_width-1) for x in row] ) + '|\n' rst = rst + table_div(num_cols, cell_width, header_flag) header_flag = 0 return rst
def make_table(grid): """ Make a RST-compatible table From http://stackoverflow.com/a/12539081 """ cell_width = 2 + max( reduce( lambda x, y: x+y, [[len(item) for item in row] for row in grid], [] ) ) num_cols = len(grid[0]) rst = table_div(num_cols, cell_width, 0) header_flag = 1 for row in grid: rst = rst + '| ' + '| '.join( [normalize_cell(x, cell_width-1) for x in row] ) + '|\n' rst = rst + table_div(num_cols, cell_width, header_flag) header_flag = 0 return rst
[ "Make", "a", "RST", "-", "compatible", "table" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/docs/generate_service_template.py#L12-L32
[ "def", "make_table", "(", "grid", ")", ":", "cell_width", "=", "2", "+", "max", "(", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "[", "[", "len", "(", "item", ")", "for", "item", "in", "row", "]", "for", "row", "in", "grid", "]", ",", "[", "]", ")", ")", "num_cols", "=", "len", "(", "grid", "[", "0", "]", ")", "rst", "=", "table_div", "(", "num_cols", ",", "cell_width", ",", "0", ")", "header_flag", "=", "1", "for", "row", "in", "grid", ":", "rst", "=", "rst", "+", "'| '", "+", "'| '", ".", "join", "(", "[", "normalize_cell", "(", "x", ",", "cell_width", "-", "1", ")", "for", "x", "in", "row", "]", ")", "+", "'|\\n'", "rst", "=", "rst", "+", "table_div", "(", "num_cols", ",", "cell_width", ",", "header_flag", ")", "header_flag", "=", "0", "return", "rst" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
get_service_password
Retrieve the sensitive password for a service by: * retrieving password from a secure store (@oracle:use_keyring, default) * asking the password from the user (@oracle:ask_password, interactive) * executing a command and use the output as password (@oracle:eval:<command>) Note that the keyring may or may not be locked which requires that the user provides a password (interactive mode). :param service: Service name, may be key into secure store (as string). :param username: Username for the service (as string). :param oracle: Hint which password oracle strategy to use. :return: Retrieved password (as string) .. seealso:: https://bitbucket.org/kang/python-keyring-lib
bugwarrior/config.py
def get_service_password(service, username, oracle=None, interactive=False): """ Retrieve the sensitive password for a service by: * retrieving password from a secure store (@oracle:use_keyring, default) * asking the password from the user (@oracle:ask_password, interactive) * executing a command and use the output as password (@oracle:eval:<command>) Note that the keyring may or may not be locked which requires that the user provides a password (interactive mode). :param service: Service name, may be key into secure store (as string). :param username: Username for the service (as string). :param oracle: Hint which password oracle strategy to use. :return: Retrieved password (as string) .. seealso:: https://bitbucket.org/kang/python-keyring-lib """ import getpass password = None if not oracle or oracle == "@oracle:use_keyring": keyring = get_keyring() password = keyring.get_password(service, username) if interactive and password is None: # -- LEARNING MODE: Password is not stored in keyring yet. oracle = "@oracle:ask_password" password = get_service_password(service, username, oracle, interactive=True) if password: keyring.set_password(service, username, password) elif interactive and oracle == "@oracle:ask_password": prompt = "%s password: " % service password = getpass.getpass(prompt) elif oracle.startswith('@oracle:eval:'): command = oracle[13:] return oracle_eval(command) if password is None: die("MISSING PASSWORD: oracle='%s', interactive=%s for service=%s" % (oracle, interactive, service)) return password
def get_service_password(service, username, oracle=None, interactive=False): """ Retrieve the sensitive password for a service by: * retrieving password from a secure store (@oracle:use_keyring, default) * asking the password from the user (@oracle:ask_password, interactive) * executing a command and use the output as password (@oracle:eval:<command>) Note that the keyring may or may not be locked which requires that the user provides a password (interactive mode). :param service: Service name, may be key into secure store (as string). :param username: Username for the service (as string). :param oracle: Hint which password oracle strategy to use. :return: Retrieved password (as string) .. seealso:: https://bitbucket.org/kang/python-keyring-lib """ import getpass password = None if not oracle or oracle == "@oracle:use_keyring": keyring = get_keyring() password = keyring.get_password(service, username) if interactive and password is None: # -- LEARNING MODE: Password is not stored in keyring yet. oracle = "@oracle:ask_password" password = get_service_password(service, username, oracle, interactive=True) if password: keyring.set_password(service, username, password) elif interactive and oracle == "@oracle:ask_password": prompt = "%s password: " % service password = getpass.getpass(prompt) elif oracle.startswith('@oracle:eval:'): command = oracle[13:] return oracle_eval(command) if password is None: die("MISSING PASSWORD: oracle='%s', interactive=%s for service=%s" % (oracle, interactive, service)) return password
[ "Retrieve", "the", "sensitive", "password", "for", "a", "service", "by", ":" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/config.py#L52-L95
[ "def", "get_service_password", "(", "service", ",", "username", ",", "oracle", "=", "None", ",", "interactive", "=", "False", ")", ":", "import", "getpass", "password", "=", "None", "if", "not", "oracle", "or", "oracle", "==", "\"@oracle:use_keyring\"", ":", "keyring", "=", "get_keyring", "(", ")", "password", "=", "keyring", ".", "get_password", "(", "service", ",", "username", ")", "if", "interactive", "and", "password", "is", "None", ":", "# -- LEARNING MODE: Password is not stored in keyring yet.", "oracle", "=", "\"@oracle:ask_password\"", "password", "=", "get_service_password", "(", "service", ",", "username", ",", "oracle", ",", "interactive", "=", "True", ")", "if", "password", ":", "keyring", ".", "set_password", "(", "service", ",", "username", ",", "password", ")", "elif", "interactive", "and", "oracle", "==", "\"@oracle:ask_password\"", ":", "prompt", "=", "\"%s password: \"", "%", "service", "password", "=", "getpass", ".", "getpass", "(", "prompt", ")", "elif", "oracle", ".", "startswith", "(", "'@oracle:eval:'", ")", ":", "command", "=", "oracle", "[", "13", ":", "]", "return", "oracle_eval", "(", "command", ")", "if", "password", "is", "None", ":", "die", "(", "\"MISSING PASSWORD: oracle='%s', interactive=%s for service=%s\"", "%", "(", "oracle", ",", "interactive", ",", "service", ")", ")", "return", "password" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b
test
oracle_eval
Retrieve password from the given command
bugwarrior/config.py
def oracle_eval(command): """ Retrieve password from the given command """ p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() if p.returncode == 0: return p.stdout.readline().strip().decode('utf-8') else: die( "Error retrieving password: `{command}` returned '{error}'".format( command=command, error=p.stderr.read().strip()))
def oracle_eval(command): """ Retrieve password from the given command """ p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() if p.returncode == 0: return p.stdout.readline().strip().decode('utf-8') else: die( "Error retrieving password: `{command}` returned '{error}'".format( command=command, error=p.stderr.read().strip()))
[ "Retrieve", "password", "from", "the", "given", "command" ]
ralphbean/bugwarrior
python
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/config.py#L98-L108
[ "def", "oracle_eval", "(", "command", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "command", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "p", ".", "wait", "(", ")", "if", "p", ".", "returncode", "==", "0", ":", "return", "p", ".", "stdout", ".", "readline", "(", ")", ".", "strip", "(", ")", ".", "decode", "(", "'utf-8'", ")", "else", ":", "die", "(", "\"Error retrieving password: `{command}` returned '{error}'\"", ".", "format", "(", "command", "=", "command", ",", "error", "=", "p", ".", "stderr", ".", "read", "(", ")", ".", "strip", "(", ")", ")", ")" ]
b2a5108f7b40cb0c437509b64eaa28f941f7ac8b