_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q16200 | key_diff | train | def key_diff(key_bundle, key_defs):
"""
Creates a difference dictionary with keys that should added and keys that
should be deleted from a Key Bundle to get it updated to a state that
mirrors What is in the key_defs specification.
:param key_bundle: The original KeyBundle
:param key_defs: A set of key definitions
:return: A dictionary with possible keys 'add' and 'del'. The values
for the keys are lists of :py:class:`cryptojwt.jwk.JWK` instances
"""
keys = key_bundle.get()
diff = {}
# My own sorted copy
key_defs = order_key_defs(key_defs)[:]
used = []
for key in keys:
match = False
for kd in key_defs:
if key.use not in kd['use']:
continue
if key.kty != kd['type']:
continue
if key.kty == 'EC':
# special test only for EC | python | {
"resource": ""
} |
q16201 | update_key_bundle | train | def update_key_bundle(key_bundle, diff):
"""
Apply a diff specification to a KeyBundle.
The keys that are to be added are added.
The keys that should be deleted are marked as inactive.
:param key_bundle: The original KeyBundle
| python | {
"resource": ""
} |
q16202 | key_rollover | train | def key_rollover(kb):
"""
A nifty function that lets you do a key rollover that encompasses creating
a completely new set of keys. One new per every old one. With the same
specifications as the old one.
All the old ones are marked as inactive.
| python | {
"resource": ""
} |
q16203 | KeyBundle.do_keys | train | def do_keys(self, keys):
"""
Go from JWK description to binary keys
:param keys:
:return:
"""
for inst in keys:
typ = inst["kty"]
try:
_usage = harmonize_usage(inst['use'])
except KeyError:
_usage = ['']
else:
del inst['use']
flag = 0
for _use in _usage:
for _typ in [typ, typ.lower(), typ.upper()]:
try:
_key = K2C[_typ](use=_use, **inst)
except KeyError:
continue
except JWKException as err:
| python | {
"resource": ""
} |
q16204 | KeyBundle.do_remote | train | def do_remote(self):
"""
Load a JWKS from a webpage
:return: True or False if load was successful
"""
if self.verify_ssl:
args = {"verify": self.verify_ssl}
else:
args = {}
try:
logging.debug('KeyBundle fetch keys from: {}'.format(self.source))
r = self.httpc('GET', self.source, **args)
except Exception as err:
logger.error(err)
raise UpdateFailed(
REMOTE_FAILED.format(self.source, str(err)))
| python | {
"resource": ""
} |
q16205 | KeyBundle._parse_remote_response | train | def _parse_remote_response(self, response):
"""
Parse JWKS from the HTTP response.
Should be overriden by subclasses for adding support of e.g. signed
JWKS.
:param response: HTTP response from the 'jwks_uri' endpoint
:return: response parsed as JSON
"""
# Check if the content type is the right one.
try:
if response.headers["Content-Type"] != 'application/json':
logger.warning('Wrong Content_type ({})'.format(
| python | {
"resource": ""
} |
q16206 | KeyBundle.update | train | def update(self):
"""
Reload the keys if necessary
This is a forced update, will happen even if cache time has not elapsed.
Replaced keys will be marked as inactive and not removed.
"""
res = True # An update was successful
if self.source:
_keys = self._keys # just in case
# reread everything
self._keys = []
try:
if self.remote is False:
if self.fileformat in ["jwks", "jwk"]:
self.do_local_jwk(self.source)
elif self.fileformat == "der":
self.do_local_der(self.source, self.keytype,
self.keyusage)
else:
| python | {
"resource": ""
} |
q16207 | KeyBundle.remove_outdated | train | def remove_outdated(self, after, when=0):
"""
Remove keys that should not be available any more.
Outdated means that the key was marked as inactive at a time
that was longer ago then what is given in 'after'.
:param after: The length of time the key will remain in the KeyBundle
before it should be removed.
| python | {
"resource": ""
} |
q16208 | KeyBundle.copy | train | def copy(self):
"""
Make deep copy of this KeyBundle
:return: The copy
"""
kb = KeyBundle()
kb._keys = self._keys[:]
kb.cache_time = self.cache_time
kb.verify_ssl = self.verify_ssl
if self.source:
kb.source = self.source | python | {
"resource": ""
} |
q16209 | SimpleJWT.unpack | train | def unpack(self, token, **kwargs):
"""
Unpacks a JWT into its parts and base64 decodes the parts
individually
:param token: The JWT
:param kwargs: A possible empty set of claims to verify the header
against.
"""
if isinstance(token, str):
try:
token = token.encode("utf-8")
except UnicodeDecodeError:
pass
| python | {
"resource": ""
} |
q16210 | SimpleJWT.pack | train | def pack(self, parts=None, headers=None):
"""
Packs components into a JWT
:param parts: List of parts to pack
:param headers: The JWT headers
:return:
"""
if not headers:
if self.headers:
headers = self.headers
else:
headers = {'alg': 'none'}
logging.debug('JWT header: {}'.format(headers))
if not parts:
return ".".join([a.decode() for | python | {
"resource": ""
} |
q16211 | SimpleJWT.verify_header | train | def verify_header(self, key, val):
"""
Check that a particular header claim is present and has a specific value
:param key: The claim
:param val: The value of the claim
:raises: KeyError if the claim is not present in the header
:return: True if the claim exists in the header and has the prescribed
value
"""
if isinstance(val, list):
if self.headers[key] in val:
| python | {
"resource": ""
} |
q16212 | SimpleJWT.verify_headers | train | def verify_headers(self, check_presence=True, **kwargs):
"""
Check that a set of particular header claim are present and has
specific values
:param kwargs: The claim/value sets as a dictionary
:return: True if the claim that appears in the header has the
prescribed values. If a claim is not present in the header and
check_presence is True then False is returned.
"""
for key, val in kwargs.items():
try:
| python | {
"resource": ""
} |
q16213 | HMACSigner.sign | train | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using a
symmetric key
:param msg: The message
:param key: The key
:return: A signature
| python | {
"resource": ""
} |
q16214 | HMACSigner.verify | train | def verify(self, msg, sig, key):
"""
Verifies whether sig is the correct message authentication code of data.
:param msg: The data
:param sig: The message authentication code to verify against data.
:param key: The key to use
:return: Returns true if the mac was valid otherwise it will raise an
Exception.
"""
try:
| python | {
"resource": ""
} |
q16215 | ensure_ec_params | train | def ensure_ec_params(jwk_dict, private):
"""Ensure all required EC parameters are present in dictionary"""
provided = frozenset(jwk_dict.keys())
if private is not None and private:
| python | {
"resource": ""
} |
q16216 | ensure_rsa_params | train | def ensure_rsa_params(jwk_dict, private):
"""Ensure all required RSA parameters are present in dictionary"""
provided = frozenset(jwk_dict.keys())
if private is not None and private:
| python | {
"resource": ""
} |
q16217 | ensure_params | train | def ensure_params(kty, provided, required):
"""Ensure all required parameters are present in dictionary"""
if not required <= provided:
missing | python | {
"resource": ""
} |
q16218 | jwk_wrap | train | def jwk_wrap(key, use="", kid=""):
"""
Instantiate a Key instance with the given key
:param key: The keys to wrap
:param use: What the key are expected to be use for
:param kid: A key id
:return: The Key instance
"""
if isinstance(key, rsa.RSAPublicKey) or isinstance(key, rsa.RSAPrivateKey):
kspec = RSAKey(use=use, kid=kid).load_key(key)
elif isinstance(key, str):
kspec = SYMKey(key=key, use=use, kid=kid)
| python | {
"resource": ""
} |
q16219 | update_keyjar | train | def update_keyjar(keyjar):
"""
Go through the whole key jar, key bundle by key bundle and update them one
by one.
:param keyjar: The key jar | python | {
"resource": ""
} |
q16220 | key_summary | train | def key_summary(keyjar, issuer):
"""
Return a text representation of the keyjar.
:param keyjar: A :py:class:`oidcmsg.key_jar.KeyJar` instance
:param issuer: Which key owner that we are looking at
:return: A text representation of the keys
"""
try:
kbl = keyjar[issuer]
except KeyError:
return ''
else:
key_list = []
for kb in kbl:
for key in kb.keys():
| python | {
"resource": ""
} |
q16221 | KeyJar.get | train | def get(self, key_use, key_type="", owner="", kid=None, **kwargs):
"""
Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:return: A possibly empty list of keys
"""
if key_use in ["dec", "enc"]:
use = "enc"
else:
use = "sig"
_kj = None
if owner != "":
try:
_kj = self.issuer_keys[owner]
except KeyError:
if owner.endswith("/"):
try:
_kj = self.issuer_keys[owner[:-1]]
except KeyError:
pass
else:
try:
_kj = self.issuer_keys[owner + "/"]
except KeyError:
pass
else:
try:
_kj = self.issuer_keys[owner]
except KeyError:
pass
if _kj is None:
return []
lst = []
for bundle in _kj:
if key_type:
if key_use in ['ver', 'dec']:
_bkeys = bundle.get(key_type, only_active=False)
else:
_bkeys = bundle.get(key_type)
else:
_bkeys = bundle.keys()
for key in _bkeys:
if key.inactive_since and key_use != "sig":
# Skip inactive keys unless for signature verification
| python | {
"resource": ""
} |
q16222 | KeyJar.get_signing_key | train | def get_signing_key(self, key_type="", owner="", kid=None, **kwargs):
"""
Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
| python | {
"resource": ""
} |
q16223 | KeyJar.keys_by_alg_and_usage | train | def keys_by_alg_and_usage(self, issuer, alg, usage):
"""
Find all keys that can be used for a specific crypto algorithm and
usage by key owner.
:param issuer: Key owner
:param alg: a crypto algorithm
:param usage: What the key should be used for
:return: A possibly empty list of keys | python | {
"resource": ""
} |
q16224 | KeyJar.get_issuer_keys | train | def get_issuer_keys(self, issuer):
"""
Get all the keys that belong to an entity.
:param issuer: The entity ID
:return: A possibly empty list of keys
"""
res = | python | {
"resource": ""
} |
q16225 | KeyJar.match_owner | train | def match_owner(self, url):
"""
Finds the first entity, with keys in the key jar, with an
identifier that matches the given URL. The match is a leading
substring match.
:param url: A URL
:return: An issue entity ID that exists in the Key jar
| python | {
"resource": ""
} |
q16226 | KeyJar.load_keys | train | def load_keys(self, issuer, jwks_uri='', jwks=None, replace=False):
"""
Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If all previously gathered keys from this provider
should be replace.
:return: Dictionary with usage as key and keys as values
"""
logger.debug("Initiating key bundle for issuer: %s" % issuer)
if replace or issuer not | python | {
"resource": ""
} |
q16227 | KeyJar.find | train | def find(self, source, issuer):
"""
Find a key bundle based on the source of the keys
:param source: A source url
:param issuer: The issuer of keys
:return: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance or None
"""
try:
| python | {
"resource": ""
} |
q16228 | KeyJar.export_jwks_as_json | train | def export_jwks_as_json(self, private=False, issuer=""):
"""
Export a JWKS as a JSON document.
:param private: Whether it should | python | {
"resource": ""
} |
q16229 | KeyJar.import_jwks | train | def import_jwks(self, jwks, issuer):
"""
Imports all the keys that are represented in a JWKS
:param jwks: Dictionary representation of a JWKS
:param issuer: Who 'owns' the JWKS
"""
try:
_keys = jwks["keys"]
except KeyError:
raise ValueError('Not a proper JWKS')
else:
try:
self.issuer_keys[issuer].append(
| python | {
"resource": ""
} |
q16230 | KeyJar.import_jwks_as_json | train | def import_jwks_as_json(self, jwks, issuer):
"""
Imports all the keys that are represented in a JWKS expressed as a
JSON object
:param jwks: JSON representation of a JWKS
| python | {
"resource": ""
} |
q16231 | KeyJar.get_jwt_decrypt_keys | train | def get_jwt_decrypt_keys(self, jwt, **kwargs):
"""
Get decryption keys from this keyjar based on information carried
in a JWE. These keys should be usable to decrypt an encrypted JWT.
:param jwt: A cryptojwt.jwt.JWT instance
:param kwargs: Other key word arguments
:return: list of usable keys
"""
try:
_key_type = jwe_alg2keytype(jwt.headers['alg'])
except KeyError:
_key_type = ''
try:
_kid = jwt.headers['kid']
except KeyError:
logger.info('Missing kid')
_kid = ''
keys = self.get(key_use='enc', owner='', key_type=_key_type)
try:
_aud = kwargs['aud']
except KeyError:
_aud = ''
if _aud:
try:
allow_missing_kid = kwargs['allow_missing_kid'] | python | {
"resource": ""
} |
q16232 | KeyJar.get_jwt_verify_keys | train | def get_jwt_verify_keys(self, jwt, **kwargs):
"""
Get keys from this key jar based on information in a JWS. These keys
should be usable to verify the signed JWT.
:param jwt: A cryptojwt.jwt.JWT instance
:param kwargs: Other key word arguments
:return: list of usable keys
"""
try:
allow_missing_kid = kwargs['allow_missing_kid']
except KeyError:
allow_missing_kid = False
try:
_key_type = jws_alg2keytype(jwt.headers['alg'])
except KeyError:
_key_type = ''
try:
_kid = jwt.headers['kid']
except KeyError:
logger.info('Missing kid')
_kid = ''
try:
nki = kwargs['no_kid_issuer']
except KeyError:
nki = {}
_payload = jwt.payload()
try:
_iss = _payload['iss']
except KeyError:
try:
_iss = kwargs['iss']
except KeyError:
_iss = ''
if _iss:
# First extend the key jar iff allowed
if "jku" in jwt.headers and _iss:
if not self.find(jwt.headers["jku"], _iss):
# This is really questionable
try:
if kwargs["trusting"]:
| python | {
"resource": ""
} |
q16233 | KeyJar.copy | train | def copy(self):
"""
Make deep copy of this key jar.
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
"""
kj = KeyJar()
for issuer in self.owners():
| python | {
"resource": ""
} |
q16234 | pick_key | train | def pick_key(keys, use, alg='', key_type='', kid=''):
"""
Based on given criteria pick out the keys that fulfill them from a
given set of keys.
:param keys: List of keys. These are :py:class:`cryptojwt.jwk.JWK`
instances.
:param use: What the key is going to be used for 'sig'/'enc'
:param alg: crypto algorithm
:param key_type: Type of key 'rsa'/'ec'/'oct'
:param kid: Key ID
:return: A list of keys that match the pattern
"""
res = []
if not key_type:
if use == 'sig':
key_type = jws_alg2keytype(alg)
else:
key_type = jwe_alg2keytype(alg)
for key in keys:
if key.use and key.use != use:
continue
if key.kty == key_type:
if key.kid and kid:
if key.kid == kid:
| python | {
"resource": ""
} |
q16235 | JWT.pack_init | train | def pack_init(self, recv, aud):
"""
Gather initial information for the payload.
:return: A dictionary with claims and values
"""
argv | python | {
"resource": ""
} |
q16236 | JWT.pack_key | train | def pack_key(self, owner_id='', kid=''):
"""
Find a key to be used for signing the Json Web Token
:param owner_id: Owner of the keys to chose from
:param kid: Key ID
:return: One key
"""
keys = pick_key(self.my_keys(owner_id, 'sig'), 'sig', | python | {
"resource": ""
} |
q16237 | JWT._verify | train | def _verify(self, rj, token):
"""
Verify a signed JSON Web Token
:param rj: A :py:class:`cryptojwt.jws.JWS` instance
:param token: The signed JSON Web Token
:return: A verified message
""" | python | {
"resource": ""
} |
q16238 | JWT._decrypt | train | def _decrypt(self, rj, token):
"""
Decrypt an encrypted JsonWebToken
:param rj: :py:class:`cryptojwt.jwe.JWE` instance
:param token: The encrypted JsonWebToken
:return:
"""
if self.iss:
| python | {
"resource": ""
} |
q16239 | JWT.verify_profile | train | def verify_profile(msg_cls, info, **kwargs):
"""
If a message type is known for this JSON document. Verify that the
document complies with the message specifications.
:param msg_cls: The message class. A
:py:class:`oidcmsg.message.Message` instance
:param info: The information in the JSON document as a dictionary
:param kwargs: Extra keyword arguments used when doing | python | {
"resource": ""
} |
q16240 | JWT.unpack | train | def unpack(self, token):
"""
Unpack a received signed or signed and encrypted Json Web Token
:param token: The Json Web Token
:return: If decryption and signature verification work the payload
will be returned as a Message instance if possible.
"""
if not token:
raise KeyError
_jwe_header = _jws_header = None
# Check if it's an encrypted JWT
darg = {}
if self.allowed_enc_encs:
darg['enc'] = self.allowed_enc_encs
if self.allowed_enc_algs:
darg['alg'] = self.allowed_enc_algs
try:
_decryptor = jwe_factory(token, **darg)
except (KeyError, HeaderError):
_decryptor = None
if _decryptor:
# Yes, try to decode
_info = self._decrypt(_decryptor, token)
_jwe_header = _decryptor.jwt.headers
# Try to find out if the information encrypted was a signed JWT
try:
_content_type = _decryptor.jwt.headers['cty']
except KeyError:
_content_type = ''
else:
_content_type = 'jwt'
_info = token
# If I have reason to believe the information I have is a signed JWT
if _content_type.lower() == 'jwt':
# Check that is a signed JWT
if self.allowed_sign_algs:
_verifier = jws_factory(_info, alg=self.allowed_sign_algs)
else:
_verifier = jws_factory(_info)
if _verifier:
_info = self._verify(_verifier, _info)
else:
raise Exception()
_jws_header = _verifier.jwt.headers
else:
# So, not a signed JWT
try:
# A JSON document ?
| python | {
"resource": ""
} |
q16241 | factory | train | def factory(token, alg=''):
"""
Instantiate an JWS instance if the token is a signed JWT.
:param token: The token that might be a signed JWT
:param alg: The expected signature algorithm
:return: A JWS instance | python | {
"resource": ""
} |
q16242 | JWS.sign_compact | train | def sign_compact(self, keys=None, protected=None, **kwargs):
"""
Produce a JWS using the JWS Compact Serialization
:param keys: A dictionary of keys
:param protected: The protected headers (a dictionary)
:param kwargs: claims you want to add to the standard headers
:return: A signed JSON Web Token
"""
_headers = self._header
_headers.update(kwargs)
key, xargs, _alg = self.alg_keys(keys, 'sig', protected)
if "typ" in self:
xargs["typ"] = self["typ"]
_headers.update(xargs)
jwt = JWSig(**_headers)
if _alg == "none":
return jwt.pack(parts=[self.msg, ""])
# All other cases
try:
_signer = SIGNER_ALGS[_alg]
except KeyError:
raise UnknownAlgorithm(_alg)
| python | {
"resource": ""
} |
q16243 | JWS.verify_compact | train | def verify_compact(self, jws=None, keys=None, allow_none=False,
sigalg=None):
"""
Verify a JWT signature
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:param allow_none: If signature algorithm 'none' is | python | {
"resource": ""
} |
q16244 | JWS.verify_compact_verbose | train | def verify_compact_verbose(self, jws=None, keys=None, allow_none=False,
sigalg=None):
"""
Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:param allow_none: If signature algorithm 'none' is allowed
:param sigalg: Expected sigalg
:return: Dictionary with 2 keys 'msg' required, 'key' optional.
The value of 'msg' is the unpacked and verified message.
The value of 'key' is the key used to verify the message
"""
if jws:
jwt = JWSig().unpack(jws)
if len(jwt) != 3:
raise WrongNumberOfParts(len(jwt))
self.jwt = jwt
elif not self.jwt:
raise ValueError('Missing singed JWT')
else:
jwt = self.jwt
try:
_alg = jwt.headers["alg"]
except KeyError:
_alg = None
else:
if _alg is None or _alg.lower() == "none":
if allow_none:
self.msg = jwt.payload()
return {'msg': self.msg}
else:
raise SignerAlgError("none not allowed")
if "alg" in self and self['alg'] and _alg:
if isinstance(self['alg'], list):
if _alg not in self["alg"] :
raise SignerAlgError(
"Wrong signing algorithm, expected {} got {}".format(
self['alg'], _alg))
elif _alg != self['alg']:
raise SignerAlgError(
"Wrong signing algorithm, expected {} got {}".format(
self['alg'], _alg))
if sigalg and sigalg != _alg:
raise SignerAlgError("Expected {0} got {1}".format(
sigalg, jwt.headers["alg"]))
self["alg"] = _alg
if keys:
| python | {
"resource": ""
} |
q16245 | JWS.sign_json | train | def sign_json(self, keys=None, headers=None, flatten=False):
"""
Produce JWS using the JWS JSON Serialization
:param keys: list of keys to use for signing the JWS
:param headers: list of tuples (protected headers, unprotected
headers) for each signature
:return: A signed message using the JSON serialization format.
"""
def create_signature(protected, unprotected):
protected_headers = protected or {}
# always protect the signing alg header
protected_headers.setdefault("alg", self.alg)
_jws = JWS(self.msg, **protected_headers)
encoded_header, payload, signature = _jws.sign_compact(
protected=protected,
keys=keys).split(".")
signature_entry = {"signature": signature}
if unprotected:
signature_entry["header"] = unprotected
if encoded_header:
signature_entry["protected"] = encoded_header
return signature_entry
res = | python | {
"resource": ""
} |
q16246 | JWS._is_json_serialized_jws | train | def _is_json_serialized_jws(self, json_jws):
"""
Check if we've got a JSON serialized signed JWT.
:param json_jws: The message
:return: True/False
"""
| python | {
"resource": ""
} |
q16247 | JWS._is_compact_jws | train | def _is_compact_jws(self, jws):
"""
Check if we've got a compact signed JWT
:param jws: The message
:return: True/False
"""
try:
jwt = JWSig().unpack(jws)
except Exception as err:
logger.warning('Could not parse JWS: {}'.format(err)) | python | {
"resource": ""
} |
q16248 | RSASigner.sign | train | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes
"""
if not isinstance(key, | python | {
"resource": ""
} |
q16249 | RSASigner.verify | train | def verify(self, msg, signature, key):
"""
Verifies whether signature is a valid signature for message
:param msg: the message
:type msg: bytes
:param signature: The signature to be verified
:type signature: bytes
:param key: The key
:return: True is the signature is valid otherwise False
"""
if not isinstance(key, rsa.RSAPublicKey):
raise TypeError(
"The public key must be an instance of RSAPublicKey")
| python | {
"resource": ""
} |
q16250 | generate_and_store_rsa_key | train | def generate_and_store_rsa_key(key_size=2048, filename='rsa.key',
passphrase=''):
"""
Generate a private RSA key and store a PEM representation of it in a
file.
:param key_size: The size of the key, default 2048 bytes.
:param filename: The name of the file to which the key should be written
:param passphrase: If the PEM representation should be protected with a
pass phrase.
:return: A
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance
"""
private_key = rsa.generate_private_key(public_exponent=65537,
key_size=key_size,
backend=default_backend())
with open(filename, "wb") as keyfile:
if passphrase:
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
| python | {
"resource": ""
} |
q16251 | import_public_rsa_key_from_file | train | def import_public_rsa_key_from_file(filename):
"""
Read a public RSA key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file. | python | {
"resource": ""
} |
q16252 | import_rsa_key | train | def import_rsa_key(pem_data):
"""
Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance
"""
if not pem_data.startswith(PREFIX):
pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX),
| python | {
"resource": ""
} |
q16253 | rsa_eq | train | def rsa_eq(key1, key2):
"""
Only works for RSAPublic Keys
:param key1:
:param key2:
:return:
"""
pn1 = key1.public_numbers()
pn2 = key2.public_numbers()
| python | {
"resource": ""
} |
q16254 | der_cert | train | def der_cert(der_data):
"""
Load a DER encoded certificate
:param der_data: DER-encoded certificate
:return: A cryptography.x509.certificate instance
"""
if isinstance(der_data, str):
| python | {
"resource": ""
} |
q16255 | load_x509_cert | train | def load_x509_cert(url, httpc, spec2key, **get_args):
"""
Get and transform a X509 cert into a key.
:param url: Where the X509 cert can be found
:param httpc: HTTP client to use for fetching
:param spec2key: A dictionary over keys already seen
:param get_args: Extra key word arguments to the HTTP GET request
:return: List of 2-tuples (keytype, key)
"""
try:
r = httpc('GET', url, allow_redirects=True, **get_args)
if r.status_code == 200:
cert = str(r.text)
try:
public_key = spec2key[cert] # If I've already seen it
| python | {
"resource": ""
} |
q16256 | cmp_public_numbers | train | def cmp_public_numbers(pn1, pn2):
"""
Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is | python | {
"resource": ""
} |
q16257 | cmp_private_numbers | train | def cmp_private_numbers(pn1, pn2):
"""
Compare 2 sets of private numbers. This is for comparing 2
private RSA keys.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging | python | {
"resource": ""
} |
q16258 | RSAKey.deserialize | train | def deserialize(self):
"""
Based on a text based representation of an RSA key this method
instantiates a
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance
"""
# first look for the public parts of a RSA key
if self.n and self.e:
try:
numbers = {}
# loop over all the parameters that define a RSA key
for param in self.longs:
item = getattr(self, param)
if not item:
continue
else:
try:
val = int(deser(item))
except Exception:
raise
else:
numbers[param] = val
if 'd' in numbers:
self.priv_key = rsa_construct_private(numbers)
| python | {
"resource": ""
} |
q16259 | RSAKey.serialize | train | def serialize(self, private=False):
"""
Given a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance construct the JWK representation.
:param private: Should I do the private part or not
:return: A JWK as a dictionary
"""
if not self.priv_key and not self.pub_key:
raise SerializationNotPossible()
res = self.common()
public_longs = list(set(self.public_members) & set(self.longs))
for param in public_longs:
item = getattr(self, param)
if item:
res[param] | python | {
"resource": ""
} |
q16260 | RSAKey.load_key | train | def load_key(self, key):
"""
Load a RSA key. Try to serialize the key before binding it to this
instance.
:param key: An RSA key instance
"""
self._serialize(key)
if isinstance(key, rsa.RSAPrivateKey):
| python | {
"resource": ""
} |
q16261 | ECDSASigner.sign | train | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using an
Elliptic curve key
:param msg: The message
:param key: An ec.EllipticCurvePrivateKey instance
:return:
"""
if not isinstance(key, ec.EllipticCurvePrivateKey):
raise TypeError(
"The private key must be an instance of "
"ec.EllipticCurvePrivateKey")
self._cross_check(key.public_key())
num_bits = key.curve.key_size
num_bytes = | python | {
"resource": ""
} |
q16262 | ECDSASigner._cross_check | train | def _cross_check(self, pub_key):
"""
In Ecdsa, both the key and the algorithm define the curve.
Therefore, we must cross check them to make sure they're the same.
:param key:
:raises: ValueError is the curves are not the same
"""
if | python | {
"resource": ""
} |
q16263 | ECDSASigner._split_raw_signature | train | def _split_raw_signature(sig):
"""
Split raw signature into components
:param sig: The signature
:return: A 2-tuple | python | {
"resource": ""
} |
q16264 | alg2keytype | train | def alg2keytype(alg):
"""
Go from algorithm name to key type.
:param alg: The algorithm name
:return: The key type
"""
if not alg or alg.lower() == "none":
return "none"
elif alg.startswith("RS") or alg.startswith("PS"):
| python | {
"resource": ""
} |
q16265 | ecdh_derive_key | train | def ecdh_derive_key(key, epk, apu, apv, alg, dk_len):
"""
ECDH key derivation, as defined by JWA
:param key : Elliptic curve private key
:param epk : Elliptic curve public key
:param apu : PartyUInfo
:param apv : PartyVInfo
:param alg : Algorithm identifier
:param dk_len: Length of key to be derived, in bits
:return: The derived key
"""
# Compute shared secret
shared_key = key.exchange(ec.ECDH(), | python | {
"resource": ""
} |
q16266 | JWE_EC.encrypt | train | def encrypt(self, key=None, iv="", cek="", **kwargs):
"""
Produces a JWE as defined in RFC7516 using an Elliptic curve key
:param key: *Not used>, only there to present the same API as
JWE_RSA and JWE_SYM
:param iv: Initialization vector
:param cek: Content master key
:param kwargs: Extra keyword arguments
:return: An encrypted JWT
"""
_msg = as_bytes(self.msg)
_args = self._dict
try:
_args["kid"] = kwargs["kid"]
except KeyError:
pass
if 'params' in kwargs:
if 'apu' in kwargs['params']:
_args['apu'] = kwargs['params']['apu']
if 'apv' in kwargs['params']:
_args['apv'] = kwargs['params']['apv']
if 'epk' in kwargs['params']:
| python | {
"resource": ""
} |
q16267 | JWE_RSA.encrypt | train | def encrypt(self, key, iv="", cek="", **kwargs):
"""
Produces a JWE as defined in RFC7516 using RSA algorithms
:param key: RSA key
:param iv: Initialization vector
:param cek: Content master key
:param kwargs: Extra keyword arguments
:return: A signed payload
"""
_msg = as_bytes(self.msg)
if "zip" in self:
if self["zip"] == "DEF":
_msg = zlib.compress(_msg)
else:
raise ParameterError("Zip has unknown value: %s" % self["zip"])
kwarg_cek = cek or None
_enc = self["enc"]
iv = self._generate_iv(_enc, iv)
cek = self._generate_key(_enc, cek)
self["cek"] = cek
logger.debug("cek: %s, iv: %s" % ([c for c in cek], [c for c in iv]))
_encrypt = RSAEncrypter(self.with_digest).encrypt
_alg = self["alg"]
if kwarg_cek:
jwe_enc_key = ''
elif _alg == "RSA-OAEP":
jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_padding')
elif _alg == "RSA-OAEP-256":
| python | {
"resource": ""
} |
q16268 | JWE_RSA.decrypt | train | def decrypt(self, token, key, cek=None):
""" Decrypts a JWT
:param token: The JWT
:param key: A key to use for decrypting
:param cek: Ephemeral cipher key
:return: The decrypted message
"""
if not isinstance(token, JWEnc):
jwe = JWEnc().unpack(token)
else:
jwe = token
self.jwt = jwe.encrypted_key()
jek = jwe.encrypted_key()
_decrypt = RSAEncrypter(self.with_digest).decrypt
_alg = jwe.headers["alg"]
if cek:
pass
elif _alg == "RSA-OAEP":
cek = _decrypt(jek, key, 'pkcs1_oaep_padding')
elif _alg == "RSA-OAEP-256":
cek = _decrypt(jek, key, 'pkcs1_oaep_256_padding')
elif _alg == "RSA1_5":
cek = _decrypt(jek, key)
else:
raise NotSupportedAlgorithm(_alg)
self["cek"] = cek
enc = jwe.headers["enc"]
if enc not in SUPPORTED["enc"]:
| python | {
"resource": ""
} |
q16269 | JWE.encrypt | train | def encrypt(self, keys=None, cek="", iv="", **kwargs):
"""
Encrypt a payload
:param keys: A set of possibly usable keys
:param cek: Content master key
:param iv: Initialization vector
:param kwargs: Extra key word arguments
:return: Encrypted message
"""
_alg = self["alg"]
# Find Usable Keys
if keys:
keys = self.pick_keys(keys, use="enc")
else:
keys = self.pick_keys(self._get_keys(), use="enc")
if not keys:
logger.error(KEY_ERR.format(_alg))
raise NoSuitableEncryptionKey(_alg)
# Determine Encryption Class by Algorithm
if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]:
encrypter = JWE_RSA(self.msg, **self._dict)
elif _alg.startswith("A") and _alg.endswith("KW"):
encrypter = JWE_SYM(self.msg, **self._dict)
else: # _alg.startswith("ECDH-ES"):
encrypter = JWE_EC(**self._dict)
cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup(
self.msg, key=keys[0], **self._dict)
kwargs["encrypted_key"] = encrypted_key
kwargs["params"] = params
if cek:
kwargs["cek"] = cek
| python | {
"resource": ""
} |
q16270 | base64url_to_long | train | def base64url_to_long(data):
"""
Stricter then base64_to_long since it really checks that it's
base64url encoded
:param data: The base64 string
:return:
"""
_data = as_bytes(data)
_d = base64.urlsafe_b64decode(_data + | python | {
"resource": ""
} |
q16271 | b64d | train | def b64d(b):
"""Decode some base64-encoded bytes.
Raises BadSyntax if the string contains invalid characters or padding.
:param b: bytes
"""
cb = b.rstrip(b"=") # shouldn't but there you are
# Python's base64 functions ignore invalid characters, so we need to
# check for them explicitly.
if not _b64_re.match(cb):
| python | {
"resource": ""
} |
q16272 | deser | train | def deser(val):
"""
Deserialize from a string representation of an long integer
to the python representation of a long integer.
:param val: The string representation of the long integer.
:return: The long integer.
| python | {
"resource": ""
} |
q16273 | JWK.common | train | def common(self):
"""
Return the set of parameters that are common to all types of keys.
:return: Dictionary
"""
res = {"kty": self.kty}
if self.use:
res["use"] = | python | {
"resource": ""
} |
q16274 | JWK.verify | train | def verify(self):
"""
Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False
"""
for param in self.longs:
item = getattr(self, param)
if not item or isinstance(item, str):
| python | {
"resource": ""
} |
q16275 | concat_sha256 | train | def concat_sha256(secret, dk_len, other_info):
"""
The Concat KDF, using SHA256 as the hash function.
Note: Does not validate that otherInfo meets the requirements of
SP800-56A.
:param secret: The shared secret value
:param dk_len: Length of key to be derived, in bits
:param other_info: Other info to be incorporated | python | {
"resource": ""
} |
q16276 | JWx.pick_keys | train | def pick_keys(self, keys, use="", alg=""):
"""
The assumption is that upper layer has made certain you only get
keys you can use.
:param alg: The crypto algorithm
:param use: What the key should be used for
:param keys: A list of JWK instances
:return: A list of JWK instances that fulfill the requirements
"""
if not alg:
alg = self["alg"]
if alg == "none":
return []
_k = self.alg2keytype(alg)
if _k is None:
logger.error("Unknown algorithm '%s'" % alg)
raise ValueError('Unknown cryptography algorithm')
logger.debug("Picking key by key type={0}".format(_k))
_kty = [_k.lower(), _k.upper(), _k.lower().encode("utf-8"),
_k.upper().encode("utf-8")]
_keys = [k for k in keys if k.kty in _kty]
try:
_kid = self["kid"]
except KeyError:
try:
_kid = self.jwt.headers["kid"]
except (AttributeError, KeyError):
| python | {
"resource": ""
} |
q16277 | MyServer.setup_sensors | train | def setup_sensors(self):
"""Setup some server sensors."""
self._add_result = Sensor.float("add.result",
"Last ?add result.", "", [-10000, 10000])
self._add_result.set_value(0, Sensor.UNREACHABLE)
self._time_result = Sensor.timestamp("time.result",
"Last ?time result.", "")
self._time_result.set_value(0, Sensor.INACTIVE)
| python | {
"resource": ""
} |
q16278 | MyServer.request_add | train | def request_add(self, req, x, y):
"""Add two numbers"""
r = x + y
| python | {
"resource": ""
} |
q16279 | MyServer.request_time | train | def request_time(self, req):
"""Return the current time in ms since the Unix Epoch."""
r = time.time()
| python | {
"resource": ""
} |
q16280 | MyServer.request_eval | train | def request_eval(self, req, expression):
"""Evaluate a Python expression."""
r = str(eval(expression))
| python | {
"resource": ""
} |
q16281 | MyServer.request_set_sensor_inactive | train | def request_set_sensor_inactive(self, req, sensor_name):
"""Set sensor status to inactive"""
sensor = self.get_sensor(sensor_name)
ts, status, value = | python | {
"resource": ""
} |
q16282 | MyServer.request_set_sensor_unreachable | train | def request_set_sensor_unreachable(self, req, sensor_name):
"""Set sensor status to unreachable"""
sensor = self.get_sensor(sensor_name)
ts, | python | {
"resource": ""
} |
q16283 | MyServer.request_raw_reverse | train | def request_raw_reverse(self, req, msg):
"""
A raw request handler to demonstrate the calling convention if
@request decoraters are not used. Reverses the message arguments.
"""
# msg is a katcp.Message.request object
reversed_args = msg.arguments[::-1]
| python | {
"resource": ""
} |
q16284 | transform_future | train | def transform_future(transformation, future):
"""Returns a new future that will resolve with a transformed value
Takes the resolution value of `future` and applies transformation(*future.result())
to it before setting the result of the new future with the transformed value. If
future() resolves with an exception, it is passed through to the new future.
Assumes `future` is a tornado Future.
"""
new_future = tornado_Future()
def _transform(f):
assert f is future
if f.exc_info() is not None:
new_future.set_exc_info(f.exc_info())
| python | {
"resource": ""
} |
q16285 | monitor_resource_sync_state | train | def monitor_resource_sync_state(resource, callback, exit_event=None):
"""Coroutine that monitors a KATCPResource's sync state.
Calls callback(True/False) whenever the resource becomes synced or unsynced. Will
always do an initial callback(False) call. Exits without calling callback() if
exit_event is set
"""
exit_event = exit_event or AsyncEvent()
callback(False) # Initial condition, assume resource is not connected
while not exit_event.is_set():
# Wait for resource to be synced
yield until_any(resource.until_synced(), exit_event.until_set())
if exit_event.is_set():
break # If exit event is | python | {
"resource": ""
} |
q16286 | KATCPClientResource.until_state | train | def until_state(self, state, timeout=None):
"""Future that resolves when a certain client state is attained
Parameters
----------
state : str
Desired state, one of ("disconnected", "syncing", "synced")
| python | {
"resource": ""
} |
q16287 | KATCPClientResource.start | train | def start(self):
"""Start the client and connect"""
# TODO (NM 2015-03-12) Some checking to prevent multiple calls to start()
host, port = self.address
ic = self._inspecting_client = self.inspecting_client_factory(
host, port, self._ioloop_set_to)
self.ioloop = ic.ioloop
if self._preset_protocol_flags:
ic.preset_protocol_flags(self._preset_protocol_flags)
ic.katcp_client.auto_reconnect_delay = self.auto_reconnect_delay
ic.set_state_callback(self._inspecting_client_state_callback)
ic.request_factory = self._request_factory
| python | {
"resource": ""
} |
q16288 | KATCPClientResourceSensorsManager._get_strategy_cache_key | train | def _get_strategy_cache_key(self, sensor_name):
"""Lookup sensor name in cache, allowing names in escaped form
The strategy cache uses the normal KATCP sensor names as the keys.
In order to allow access using an escaped sensor name, this method
tries to find the normal form of the name.
Returns
-------
key : str
If there is a match, the cache key is returned.
If no match, then the sensor_name is returned unchanged.
"""
# try for a direct match first, otherwise do full comparison
if sensor_name in self._strategy_cache:
| python | {
"resource": ""
} |
q16289 | KATCPClientResourceSensorsManager.get_sampling_strategy | train | def get_sampling_strategy(self, sensor_name):
"""Get the current sampling strategy for the named sensor
Parameters
----------
sensor_name : str
Name of the sensor (normal or escaped form)
Returns
-------
strategy : tuple of str | python | {
"resource": ""
} |
q16290 | KATCPClientResourceSensorsManager.set_sampling_strategy | train | def set_sampling_strategy(self, sensor_name, strategy_and_params):
"""Set the sampling strategy for the named sensor
Parameters
----------
sensor_name : str
Name of the sensor
strategy_and_params : seq of str or str
As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the
strategy names and parameters are as defined by the KATCP spec. As
str contains the same elements in space-separated form.
Returns
-------
sensor_strategy : tuple
(success, info) with
success : bool
True if setting succeeded for this sensor, else False
info : tuple
Normalibed sensor strategy and parameters as tuple if
success == True else, sys.exc_info() tuple for the error
that occured.
"""
try:
strategy_and_params = resource.normalize_strategy_parameters(
strategy_and_params)
self._strategy_cache[sensor_name] | python | {
"resource": ""
} |
q16291 | KATCPClientResourceSensorsManager.reapply_sampling_strategies | train | def reapply_sampling_strategies(self):
"""Reapply all sensor strategies using cached values"""
check_sensor = self._inspecting_client.future_check_sensor
for sensor_name, strategy in list(self._strategy_cache.items()):
try:
sensor_exists = yield check_sensor(sensor_name)
if not sensor_exists:
self._logger.warn('Did not set strategy for non-existing sensor {}'
.format(sensor_name))
continue
| python | {
"resource": ""
} |
q16292 | KATCPClientResourceRequest.issue_request | train | def issue_request(self, *args, **kwargs):
"""Issue the wrapped request to the server.
Parameters
----------
*args : list of objects
Arguments to pass on to the request.
Keyword Arguments
-----------------
timeout : float or None, optional
Timeout after this amount of seconds (keyword argument).
mid : None or int, optional
Message identifier to use for the request message. If None, use either
auto-incrementing value or no mid depending on the KATCP protocol version
(mid's were only introduced with KATCP v5) and the value of the `use_mid`
argument. Defaults to None.
| python | {
"resource": ""
} |
q16293 | ClientGroup.wait | train | def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None,
max_grace_period=1.0):
"""Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callable,
condition_or_value(reading) is called, and must return True if its
condition is satisfied. Since the reading is passed in, the value,
status, timestamp or received_timestamp attributes can all be used
in the check.
timeout : float or None
The total timeout in seconds (None means wait forever)
quorum : None or int or float
The number of clients that are required to satisfy the condition,
as either an explicit integer or a float between 0 and 1 indicating
a fraction of the total number of clients, rounded up. If None,
this means that all clients are required (the default). Be warned
that a value of 1.0 (float) indicates all clients while a value
of 1 (int) indicates a single client...
max_grace_period : float or None
After a quorum or initial timeout is reached, wait up to this long
in an attempt to get the rest of the clients to satisfy condition
as well (achieving effectively a full quorum if all clients behave)
Returns
-------
This command returns a tornado Future that resolves with True when a
quorum of clients satisfy the sensor condition, or False if a quorum
is not reached after a given timeout period (including a grace period).
Raises
------
:class:`KATCPSensorError`
If any of the sensors do not have a strategy set, or if the named
sensor is not present
"""
if quorum is None:
quorum = len(self.clients)
elif quorum > 1:
if not isinstance(quorum, int):
raise TypeError('Quorum parameter %r must be an integer '
'if outside range [0, 1]' % (quorum,))
elif isinstance(quorum, float):
quorum = int(math.ceil(quorum * len(self.clients)))
if timeout and max_grace_period:
| python | {
"resource": ""
} |
q16294 | KATCPClientResourceContainer.set_ioloop | train | def set_ioloop(self, ioloop=None):
"""Set the tornado ioloop to use
Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if
ioloop=None. Must be called before start()
"""
ioloop = ioloop | python | {
"resource": ""
} |
q16295 | KATCPClientResourceContainer.is_connected | train | def is_connected(self):
"""Indication of the connection state of all children"""
| python | {
"resource": ""
} |
q16296 | KATCPClientResourceContainer.until_synced | train | def until_synced(self, timeout=None):
"""Return a tornado Future; resolves when all subordinate clients are synced""" | python | {
"resource": ""
} |
q16297 | KATCPClientResourceContainer.until_not_synced | train | def until_not_synced(self, timeout=None):
"""Return a tornado Future; resolves when any subordinate client is not synced"""
| python | {
"resource": ""
} |
q16298 | KATCPClientResourceContainer.until_any_child_in_state | train | def until_any_child_in_state(self, state, timeout=None):
"""Return a tornado Future; resolves when any client is in specified state"""
| python | {
"resource": ""
} |
q16299 | KATCPClientResourceContainer.until_all_children_in_state | train | def until_all_children_in_state(self, state, timeout=None):
"""Return a tornado Future; resolves when all clients are in specified state"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.