_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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 keys if key.crv != kd['crv']: continue try: _kid = kd['kid'] except KeyError: pass else: if key.kid != _kid: continue match = True used.append(kd) key_defs.remove(kd) break if not match: try: diff['del'].append(key) except KeyError: diff['del'] = [key] if key_defs: _kb = build_key_bundle(key_defs) diff['add'] = _kb.keys() return diff
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 :param diff: The difference specification :return: An updated key_bundle """ try: _add = diff['add'] except KeyError: pass else: key_bundle.extend(_add) try: _del = diff['del'] except KeyError: pass else: _now = time.time() for k in _del: k.inactive_since = _now
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. :param kb: :return: """ key_spec = [] for key in kb.get(): _spec = {'type': key.kty, 'use':[key.use]} if key.kty == 'EC': _spec['crv'] = key.crv key_spec.append(_spec) diff = {'del': kb.get()} _kb = build_key_bundle(key_spec) diff['add'] = _kb.keys() update_key_bundle(kb, diff) return kb
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: logger.warning('While loading keys: {}'.format(err)) else: if _key not in self._keys: self._keys.append(_key) flag = 1 break if not flag: logger.warning( 'While loading keys, UnknownKeyType: {}'.format(typ))
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))) if r.status_code == 200: # New content self.time_out = time.time() + self.cache_time self.imp_jwks = self._parse_remote_response(r) if not isinstance(self.imp_jwks, dict) or "keys" not in self.imp_jwks: raise UpdateFailed(MALFORMED.format(self.source)) logger.debug("Loaded JWKS: %s from %s" % (r.text, self.source)) try: self.do_keys(self.imp_jwks["keys"]) except KeyError: logger.error("No 'keys' keyword in JWKS") raise UpdateFailed(MALFORMED.format(self.source)) else: raise UpdateFailed( REMOTE_FAILED.format(self.source, r.status_code)) self.last_updated = time.time() return True
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( response.headers["Content-Type"])) except KeyError: pass logger.debug("Loaded JWKS: %s from %s" % (response.text, self.source)) try: return json.loads(response.text) except ValueError: return None
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: res = self.do_remote() except Exception as err: logger.error('Key bundle update failed: {}'.format(err)) self._keys = _keys # restore return False now = time.time() for _key in _keys: if _key not in self._keys: if not _key.inactive_since: # If already marked don't mess _key.inactive_since = now self._keys.append(_key) return res
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. :param when: To make it easier to test """ if when: now = when else: now = time.time() if not isinstance(after, float): try: after = float(after) except TypeError: raise _kl = [] for k in self._keys: if k.inactive_since and k.inactive_since + after < now: continue else: _kl.append(k) self._keys = _kl
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 kb.fileformat = self.fileformat kb.keytype = self.keytype kb.keyusage = self.keyusage kb.remote = self.remote return kb
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 part = split_token(token) self.b64part = part self.part = [b64d(p) for p in part] self.headers = json.loads(as_unicode(self.part[0])) for key,val in kwargs.items(): if not val and key in self.headers: continue try: _ok = self.verify_header(key,val) except KeyError: raise else: if not _ok: raise HeaderError( 'Expected "{}" to be "{}", was "{}"'.format( key, val, self.headers[key])) return self
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 a in self.b64part]) self.part = [headers] + parts _all = self.b64part = [b64encode_item(headers)] _all.extend([b64encode_item(p) for p in parts]) return ".".join([a.decode() for a in _all])
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: return True else: return False else: if self.headers[key] == val: return True else: return False
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: _ok = self.verify_header(key, val) except KeyError: if check_presence: return False else: pass else: if not _ok: return False return True
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 """ h = hmac.HMAC(key, self.algorithm(), default_backend()) h.update(msg) return h.finalize()
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: h = hmac.HMAC(key, self.algorithm(), default_backend()) h.update(msg) h.verify(sig) return True except: return False
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: required = EC_PUBLIC_REQUIRED | EC_PRIVATE_REQUIRED else: required = EC_PUBLIC_REQUIRED return ensure_params('EC', provided, required)
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: required = RSA_PUBLIC_REQUIRED | RSA_PRIVATE_REQUIRED else: required = RSA_PUBLIC_REQUIRED return ensure_params('RSA', provided, required)
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 = required - provided raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(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) elif isinstance(key, ec.EllipticCurvePublicKey): kspec = ECKey(use=use, kid=kid).load_key(key) else: raise Exception("Unknown key type:key=" + str(type(key))) kspec.serialize() return kspec
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 to update """ for iss, kbl in keyjar.items(): for kb in kbl: kb.update()
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(): if key.inactive_since: key_list.append( '*{}:{}:{}'.format(key.kty, key.use, key.kid)) else: key_list.append( '{}:{}:{}'.format(key.kty, key.use, key.kid)) return ', '.join(key_list)
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 continue if not key.use or use == key.use: if kid: if key.kid == kid: lst.append(key) break else: continue else: lst.append(key) # if elliptic curve, have to check if I have a key of the right curve if key_type == "EC" and "alg" in kwargs: name = "P-{}".format(kwargs["alg"][2:]) # the type _lst = [] for key in lst: if name != key.crv: continue _lst.append(key) lst = _lst if use == 'enc' and key_type == 'oct' and owner != '': # Add my symmetric keys for kb in self.issuer_keys['']: for key in kb.get(key_type): if key.inactive_since: continue if not key.use or key.use == use: lst.append(key) return lst
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 :param kwargs: Extra key word arguments :return: A possibly empty list of keys """ return self.get("sig", key_type, owner, kid, **kwargs)
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 """ if usage in ["sig", "ver"]: ktype = jws_alg2keytype(alg) else: ktype = jwe_alg2keytype(alg) return self.get(usage, ktype, issuer)
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 = [] for kbl in self.issuer_keys[issuer]: res.extend(kbl.keys()) return 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 """ for owner in self.issuer_keys.keys(): if owner.startswith(url): return owner raise KeyError("No keys for '{}' in this keyjar".format(url))
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 in self.issuer_keys: self.issuer_keys[issuer] = [] if jwks_uri: self.add_url(issuer, jwks_uri) elif jwks: # jwks should only be considered if no jwks_uri is present _keys = jwks['keys'] self.issuer_keys[issuer].append(self.keybundle_cls(_keys))
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: for kb in self.issuer_keys[issuer]: if kb.source == source: return kb except KeyError: return None return None
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 be the private keys or the public :param issuer: The entity ID. :return: A JSON representation of a JWKS """ return json.dumps(self.export_jwks(private, issuer))
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( self.keybundle_cls(_keys, verify_ssl=self.verify_ssl)) except KeyError: self.issuer_keys[issuer] = [self.keybundle_cls( _keys, verify_ssl=self.verify_ssl)]
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 :param issuer: Who 'owns' the JWKS """ return self.import_jwks(json.loads(jwks), issuer)
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'] except KeyError: allow_missing_kid = False try: nki = kwargs['no_kid_issuer'] except KeyError: nki = {} keys = self._add_key(keys, _aud, 'enc', _key_type, _kid, nki, allow_missing_kid) # Only want the appropriate keys. keys = [k for k in keys if k.appropriate_for('decrypt')] return keys
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"]: self.add_url(_iss, jwt.headers["jku"]) except KeyError: pass keys = self._add_key([], _iss, 'sig', _key_type, _kid, nki, allow_missing_kid) if _key_type == 'oct': keys.extend(self.get(key_use='sig', owner='', key_type=_key_type)) else: # No issuer, just use all keys I have keys = self.get(key_use='sig', owner='', key_type=_key_type) # Only want the appropriate keys. keys = [k for k in keys if k.appropriate_for('verify')] return keys
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(): kj[issuer] = [kb.copy() for kb in self[issuer]] kj.verify_ssl = self.verify_ssl return kj
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: res.append(key) else: continue if key.alg == '': if alg: if key_type == 'EC': if key.crv == 'P-{}'.format(alg[2:]): res.append(key) continue res.append(key) elif alg and key.alg == alg: res.append(key) else: res.append(key) return res
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 = {'iss': self.iss, 'iat': utc_time_sans_frac()} if self.lifetime: argv['exp'] = argv['iat'] + self.lifetime _aud = self.put_together_aud(recv, aud) if _aud: argv['aud'] = _aud return 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', alg=self.alg, kid=kid) if not keys: raise NoSuitableSigningKeys('kid={}'.format(kid)) return keys[0]
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 """ keys = self.key_jar.get_jwt_verify_keys(rj.jwt) return rj.verify_compact(token, keys)
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: keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt, aud=self.iss) else: keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt) return rj.decrypt(token, keys=keys)
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 the verification. :return: The verified message as a msg_cls instance. """ _msg = msg_cls(**info) if not _msg.verify(**kwargs): raise VerificationError() return _msg
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 ? _info = json.loads(_info) except JSONDecodeError: # Oh, no ! Not JSON return _info except TypeError: try: _info = as_unicode(_info) _info = json.loads(_info) except JSONDecodeError: # Oh, no ! Not JSON return _info # If I know what message class the info should be mapped into if self.msg_cls: _msg_cls = self.msg_cls else: try: # try to find a issuer specific message class _msg_cls = self.iss2msg_cls[_info['iss']] except KeyError: _msg_cls = None if _msg_cls: vp_args = {'skew': self.skew} if self.iss: vp_args['aud'] = self.iss _info = self.verify_profile(_msg_cls, _info, **vp_args) _info.jwe_header = _jwe_header _info.jws_header = _jws_header return _info else: return _info
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 if the token was a signed JWT, otherwise None """ _jw = JWS(alg=alg) if _jw.is_jws(token): return _jw else: return None
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) _input = jwt.pack(parts=[self.msg]) if isinstance(key, AsymmetricKey): sig = _signer.sign(_input.encode("utf-8"), key.private_key()) else: sig = _signer.sign(_input.encode("utf-8"), key.key) logger.debug("Signed message using key with kid=%s" % key.kid) return ".".join([_input, b64encode_item(sig).decode("utf-8")])
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 allowed :param sigalg: Expected sigalg :return: Dictionary with 2 keys 'msg' required, 'key' optional """ return self.verify_compact_verbose(jws, keys, allow_none, sigalg)['msg']
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: _keys = self.pick_keys(keys) else: _keys = self.pick_keys(self._get_keys()) if not _keys: if "kid" in self: raise NoSuitableSigningKeys( "No key with kid: %s" % (self["kid"])) elif "kid" in self.jwt.headers: raise NoSuitableSigningKeys( "No key with kid: %s" % (self.jwt.headers["kid"])) else: raise NoSuitableSigningKeys("No key for algorithm: %s" % _alg) verifier = SIGNER_ALGS[_alg] for key in _keys: if isinstance(key, AsymmetricKey): _key = key.public_key() else: _key = key.key try: if not verifier.verify(jwt.sign_input(), jwt.signature(), _key): continue except (BadSignature, IndexError): pass except (ValueError, TypeError) as err: logger.warning('Exception "{}" caught'.format(err)) else: logger.debug( "Verified message using key with kid=%s" % key.kid) self.msg = jwt.payload() self.key = key return {'msg': self.msg, 'key': key} raise BadSignature()
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 = {"payload": b64e_enc_dec(self.msg, "utf-8", "ascii")} if headers is None: headers = [(dict(alg=self.alg), None)] if flatten and len( headers) == 1: # Flattened JWS JSON Serialization Syntax signature_entry = create_signature(*headers[0]) res.update(signature_entry) else: res["signatures"] = [] for protected, unprotected in headers: signature_entry = create_signature(protected, unprotected) res["signatures"].append(signature_entry) return json.dumps(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 """ json_ser_keys = {"payload", "signatures"} flattened_json_ser_keys = {"payload", "signature"} if not json_ser_keys.issubset( json_jws.keys()) and not flattened_json_ser_keys.issubset( json_jws.keys()): return False return True
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)) return False if "alg" not in jwt.headers: return False if jwt.headers["alg"] is None: jwt.headers["alg"] = "none" if jwt.headers["alg"] not in SIGNER_ALGS: logger.debug("UnknownSignerAlg: %s" % jwt.headers["alg"]) return False self.jwt = jwt return True
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, rsa.RSAPrivateKey): raise TypeError( "The key must be an instance of rsa.RSAPrivateKey") sig = key.sign(msg, self.padding, self.hash) return sig
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") try: key.verify(signature, msg, self.padding, self.hash) except InvalidSignature as err: raise BadSignature(str(err)) except AttributeError: return False else: return True
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, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption( passphrase)) else: pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) keyfile.write(pem) keyfile.close() return private_key
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. :return: A cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance """ with open(filename, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) return public_key
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), 'utf-8') else: pem_data = bytes(pem_data, 'utf-8') cert = x509.load_pem_x509_certificate(pem_data, default_backend()) return cert.public_key()
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() # Check if two RSA keys are in fact the same if pn1 == pn2: return True else: return False
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): der_data = bytes(der_data, 'utf-8') return x509.load_der_x509_certificate(der_data, default_backend())
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 except KeyError: public_key = import_rsa_key(cert) spec2key[cert] = public_key if isinstance(public_key, rsa.RSAPublicKey): return {"rsa": public_key} else: raise Exception("HTTP Get error: %s" % r.status_code) except Exception as err: # not a RSA key logger.warning("Can't load key: %s" % err) return []
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 the sets are the same otherwise False. """ if pn1.n == pn2.n: if pn1.e == pn2.e: return True return False
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 to the 2nd key :return: True is the sets are the same otherwise False. """ if not cmp_public_numbers(pn1.public_numbers, pn2.public_numbers): return False for param in ['d', 'p', 'q']: if getattr(pn1, param) != getattr(pn2, param): return False return True
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) self.pub_key = self.priv_key.public_key() else: self.pub_key = rsa_construct_public(numbers) except ValueError as err: raise DeSerializationNotPossible("%s" % err) if self.x5c: _cert_chain = [] for der_data in self.x5c: _cert_chain.append(der_cert(base64.b64decode(der_data))) if self.x5t: # verify the cert thumbprint if isinstance(self.x5t, bytes): _x5t = self.x5t else: _x5t = self.x5t.encode('ascii') if _x5t != x5t_calculation(self.x5c[0]): raise DeSerializationNotPossible( "The thumbprint 'x5t' does not match the certificate.") if self.pub_key: if not rsa_eq(self.pub_key, _cert_chain[0].public_key()): raise ValueError( 'key described by components and key in x5c not equal') else: self.pub_key = _cert_chain[0].public_key() self._serialize(self.pub_key) if len(self.x5c) > 1: # verify chain pass if not self.priv_key and not self.pub_key: raise DeSerializationNotPossible()
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] = item if private: for param in self.longs: if not private and param in ["d", "p", "q", "dp", "dq", "di", "qi"]: continue item = getattr(self, param) if item: res[param] = item if self.x5c: res['x5c'] = [x.decode('utf-8') for x in self.x5c] return res
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): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
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 = (num_bits + 7) // 8 asn1sig = key.sign(msg, ec.ECDSA(self.hash_algorithm())) # Cryptography returns ASN.1-encoded signature data; decode as JWS # uses raw signatures (r||s) (r, s) = decode_dss_signature(asn1sig) return int_to_bytes(r, num_bytes) + int_to_bytes(s, 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 self.curve_name != pub_key.curve.name: raise ValueError( "The curve in private key {} and in algorithm {} don't " "match".format(pub_key.curve.name, self.curve_name))
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 """ c_length = len(sig) // 2 r = int_from_bytes(sig[:c_length], byteorder='big') s = int_from_bytes(sig[c_length:], byteorder='big') return r, s
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"): return "RSA" elif alg.startswith("HS") or alg.startswith("A"): return "oct" elif alg.startswith("ES") or alg.startswith("ECDH-ES"): return "EC" else: return None
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(), epk) # Derive the key # AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo otherInfo = bytes(alg) + \ struct.pack("!I", len(apu)) + apu + \ struct.pack("!I", len(apv)) + apv + \ struct.pack("!I", dk_len) return concat_sha256(shared_key, dk_len, otherInfo)
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']: _args['epk'] = kwargs['params']['epk'] jwe = JWEnc(**_args) ctxt, tag, cek = super(JWE_EC, self).enc_setup( self["enc"], _msg, auth_data=jwe.b64_encode_header(), key=cek, iv=iv) if 'encrypted_key' in kwargs: return jwe.pack(parts=[kwargs['encrypted_key'], iv, ctxt, tag]) return jwe.pack(parts=[iv, ctxt, tag])
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": jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_256_padding') elif _alg == "RSA1_5": jwe_enc_key = _encrypt(cek, key) else: raise NotSupportedAlgorithm(_alg) jwe = JWEnc(**self.headers()) try: _auth_data = kwargs['auth_data'] except KeyError: _auth_data = jwe.b64_encode_header() ctxt, tag, key = self.enc_setup(_enc, _msg, key=cek, iv=iv, auth_data=_auth_data) return jwe.pack(parts=[jwe_enc_key, iv, ctxt, tag])
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"]: raise NotSupportedAlgorithm(enc) auth_data = jwe.b64_protected_header() msg = self._decrypt(enc, cek, jwe.ciphertext(), auth_data=auth_data, iv=jwe.initialization_vector(), tag=jwe.authentication_tag()) if "zip" in jwe.headers and jwe.headers["zip"] == "DEF": msg = zlib.decompress(msg) return msg
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 if iv: kwargs["iv"] = iv for key in keys: if isinstance(key, SYMKey): _key = key.key elif isinstance(key, ECKey): _key = key.public_key() else: # isinstance(key, RSAKey): _key = key.public_key() if key.kid: encrypter["kid"] = key.kid try: token = encrypter.encrypt(key=_key, **kwargs) self["cek"] = encrypter.cek if 'cek' in encrypter else None except TypeError as err: raise err else: logger.debug( "Encrypted message using key with kid={}".format(key.kid)) return token
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 + b'==') # verify that it's base64url encoded and not just base64 # that is no '+' and '/' characters and not trailing "="s. if [e for e in [b'+', b'/', b'='] if e in _data]: raise ValueError("Not base64url encoded") return intarr2long(struct.unpack('%sB' % len(_d), _d))
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): raise BadSyntax(cb, "base64-encoded data contains illegal characters") if cb == b: b = add_padding(b) return base64.urlsafe_b64decode(b)
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. """ if isinstance(val, str): _val = val.encode("utf-8") else: _val = val return base64_to_long(_val)
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"] = self.use if self.kid: res["kid"] = self.kid if self.alg: res["alg"] = self.alg return res
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): continue if isinstance(item, bytes): item = item.decode('utf-8') setattr(self, param, item) try: _ = base64url_to_long(item) except Exception: return False else: if [e for e in ['+', '/', '='] if e in item]: return False if self.kid: if not isinstance(self.kid, str): raise ValueError("kid of wrong value type") return True
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 (see SP800-56A) :return: The derived key """ dkm = b'' dk_bytes = int(ceil(dk_len / 8.0)) counter = 0 while len(dkm) < dk_bytes: counter += 1 counter_bytes = struct.pack("!I", counter) digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(counter_bytes) digest.update(secret) digest.update(other_info) dkm += digest.finalize() return dkm[:dk_bytes]
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): _kid = None logger.debug("Picking key based on alg={0}, kid={1} and use={2}".format( alg, _kid, use)) pkey = [] for _key in _keys: logger.debug( "Picked: kid:{}, use:{}, kty:{}".format( _key.kid, _key.use, _key.kty)) if _kid: if _kid != _key.kid: continue if use and _key.use and _key.use != use: continue if alg and _key.alg and _key.alg != alg: continue pkey.append(_key) return pkey
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) self._eval_result = Sensor.string("eval.result", "Last ?eval result.", "") self._eval_result.set_value('', Sensor.UNKNOWN) self._fruit_result = Sensor.discrete("fruit.result", "Last ?pick-fruit result.", "", self.FRUIT) self._fruit_result.set_value('apple', Sensor.ERROR) self.add_sensor(self._add_result) self.add_sensor(self._time_result) self.add_sensor(self._eval_result) self.add_sensor(self._fruit_result)
python
{ "resource": "" }
q16278
MyServer.request_add
train
def request_add(self, req, x, y): """Add two numbers""" r = x + y self._add_result.set_value(r) return ("ok", r)
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() self._time_result.set_value(r) return ("ok", r)
python
{ "resource": "" }
q16280
MyServer.request_eval
train
def request_eval(self, req, expression): """Evaluate a Python expression.""" r = str(eval(expression)) self._eval_result.set_value(r) return ("ok", r)
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 = sensor.read() sensor.set_value(value, sensor.INACTIVE, ts) return('ok',)
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, status, value = sensor.read() sensor.set_value(value, sensor.UNREACHABLE, ts) return('ok',)
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] # req.make_reply() makes a katcp.Message.reply using the correct request # name and message ID return req.make_reply(*reversed_args)
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()) else: try: new_future.set_result(transformation(f.result())) except Exception: # An exception here idicates that the transformation was unsuccesful new_future.set_exc_info(sys.exc_info()) future.add_done_callback(_transform) return new_future
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 set we stop without calling callback else: callback(True) # Wait for resource to be un-synced yield until_any(resource.until_not_synced(), exit_event.until_set()) if exit_event.is_set(): break # If exit event is set we stop without calling callback else: callback(False)
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") timeout: float Timeout for operation in seconds. """ return self._state.until_state(state, timeout=timeout)
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 self._sensor_manager = KATCPClientResourceSensorsManager( ic, self.name, logger=self._logger) ic.handle_sensor_value() ic.sensor_factory = self._sensor_manager.sensor_factory # Steal some methods from _sensor_manager self.reapply_sampling_strategies = self._sensor_manager.reapply_sampling_strategies log_future_exceptions(self._logger, ic.connect())
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: return sensor_name else: escaped_name = resource.escape_name(sensor_name) for key in self._strategy_cache: escaped_key = resource.escape_name(key) if escaped_key == escaped_name: return key # no match return sensor_name
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 contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec """ cache_key = self._get_strategy_cache_key(sensor_name) cached = self._strategy_cache.get(cache_key) if not cached: return resource.normalize_strategy_parameters('none') else: return cached
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] = strategy_and_params reply = yield self._inspecting_client.wrapped_request( 'sensor-sampling', sensor_name, *strategy_and_params) if not reply.succeeded: raise KATCPSensorError('Error setting strategy for sensor {0}: \n' '{1!s}'.format(sensor_name, reply)) sensor_strategy = (True, strategy_and_params) except Exception as e: self._logger.exception('Exception found!') sensor_strategy = (False, str(e)) raise tornado.gen.Return(sensor_strategy)
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 result = yield self.set_sampling_strategy(sensor_name, strategy) except KATCPSensorError as e: self._logger.error('Error reapplying strategy for sensor {0}: {1!s}' .format(sensor_name, e)) except Exception: self._logger.exception('Unhandled exception reapplying strategy for ' 'sensor {}'.format(sensor_name), exc_info=True)
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. use_mid : bool Use a mid for the request if True. Returns ------- future object that resolves with an :class:`katcp.resource.KATCPReply` instance """ timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.timeout_hint kwargs['timeout'] = timeout return self._client.wrapped_request(self.name, *args, **kwargs)
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: # Avoid having a grace period longer than or equal to timeout grace_period = min(max_grace_period, timeout / 2.) initial_timeout = timeout - grace_period else: grace_period = max_grace_period initial_timeout = timeout # Build dict of futures instead of list as this will be easier to debug futures = {} for client in self.clients: f = client.wait(sensor_name, condition_or_value, initial_timeout) futures[client.name] = f # No timeout required here as all futures will resolve after timeout initial_results = yield until_some(done_at_least=quorum, **futures) results = dict(initial_results) # Identify stragglers and let them all respond within grace period stragglers = {} for client in self.clients: if not results.get(client.name, False): f = client.wait(sensor_name, condition_or_value, grace_period) stragglers[client.name] = f rest_of_results = yield until_some(**stragglers) results.update(dict(rest_of_results)) class TestableDict(dict): """Dictionary of results that can be tested for overall success.""" def __bool__(self): return sum(self.values()) >= quorum # Was not handled automatrically by futurize, see # https://github.com/PythonCharmers/python-future/issues/282 if sys.version_info[0] == 2: __nonzero__ = __bool__ raise tornado.gen.Return(TestableDict(results))
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 or tornado.ioloop.IOLoop.current() self.ioloop = ioloop for res in dict.values(self.children): res.set_ioloop(ioloop)
python
{ "resource": "" }
q16295
KATCPClientResourceContainer.is_connected
train
def is_connected(self): """Indication of the connection state of all children""" return all([r.is_connected() for r in dict.values(self.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""" futures = [r.until_synced(timeout) for r in dict.values(self.children)] yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError)
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""" yield until_any(*[r.until_not_synced() for r in dict.values(self.children)], timeout=timeout)
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""" return until_any(*[r.until_state(state) for r in dict.values(self.children)], timeout=timeout)
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""" futures = [r.until_state(state, timeout=timeout) for r in dict.values(self.children)] yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError)
python
{ "resource": "" }