id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,200
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
key_diff
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
def key_diff(key_bundle, key_defs): 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
[ "def", "key_diff", "(", "key_bundle", ",", "key_defs", ")", ":", "keys", "=", "key_bundle", ".", "get", "(", ")", "diff", "=", "{", "}", "# My own sorted copy", "key_defs", "=", "order_key_defs", "(", "key_defs", ")", "[", ":", "]", "used", "=", "[", "...
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
[ "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", ...
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L786-L842
16,201
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
update_key_bundle
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
def update_key_bundle(key_bundle, diff): 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
[ "def", "update_key_bundle", "(", "key_bundle", ",", "diff", ")", ":", "try", ":", "_add", "=", "diff", "[", "'add'", "]", "except", "KeyError", ":", "pass", "else", ":", "key_bundle", ".", "extend", "(", "_add", ")", "try", ":", "_del", "=", "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
[ "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", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L845-L869
16,202
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
key_rollover
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
def key_rollover(kb): 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
[ "def", "key_rollover", "(", "kb", ")", ":", "key_spec", "=", "[", "]", "for", "key", "in", "kb", ".", "get", "(", ")", ":", "_spec", "=", "{", "'type'", ":", "key", ".", "kty", ",", "'use'", ":", "[", "key", ".", "use", "]", "}", "if", "key",...
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:
[ "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", ...
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L872-L895
16,203
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
KeyBundle.do_keys
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
def do_keys(self, keys): 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))
[ "def", "do_keys", "(", "self", ",", "keys", ")", ":", "for", "inst", "in", "keys", ":", "typ", "=", "inst", "[", "\"kty\"", "]", "try", ":", "_usage", "=", "harmonize_usage", "(", "inst", "[", "'use'", "]", ")", "except", "KeyError", ":", "_usage", ...
Go from JWK description to binary keys :param keys: :return:
[ "Go", "from", "JWK", "description", "to", "binary", "keys" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L185-L217
16,204
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
KeyBundle.do_remote
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
def do_remote(self): 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
[ "def", "do_remote", "(", "self", ")", ":", "if", "self", ".", "verify_ssl", ":", "args", "=", "{", "\"verify\"", ":", "self", ".", "verify_ssl", "}", "else", ":", "args", "=", "{", "}", "try", ":", "logging", ".", "debug", "(", "'KeyBundle fetch keys f...
Load a JWKS from a webpage :return: True or False if load was successful
[ "Load", "a", "JWKS", "from", "a", "webpage" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L260-L298
16,205
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
KeyBundle._parse_remote_response
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
def _parse_remote_response(self, response): # 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
[ "def", "_parse_remote_response", "(", "self", ",", "response", ")", ":", "# Check if the content type is the right one.", "try", ":", "if", "response", ".", "headers", "[", "\"Content-Type\"", "]", "!=", "'application/json'", ":", "logger", ".", "warning", "(", "'Wr...
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
[ "Parse", "JWKS", "from", "the", "HTTP", "response", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L300-L321
16,206
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
KeyBundle.update
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
def update(self): 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
[ "def", "update", "(", "self", ")", ":", "res", "=", "True", "# An update was successful", "if", "self", ".", "source", ":", "_keys", "=", "self", ".", "_keys", "# just in case", "# reread everything", "self", ".", "_keys", "=", "[", "]", "try", ":", "if", ...
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.
[ "Reload", "the", "keys", "if", "necessary", "This", "is", "a", "forced", "update", "will", "happen", "even", "if", "cache", "time", "has", "not", "elapsed", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L335-L370
16,207
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
KeyBundle.remove_outdated
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
def remove_outdated(self, after, when=0): 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
[ "def", "remove_outdated", "(", "self", ",", "after", ",", "when", "=", "0", ")", ":", "if", "when", ":", "now", "=", "when", "else", ":", "now", "=", "time", ".", "time", "(", ")", "if", "not", "isinstance", "(", "after", ",", "float", ")", ":", ...
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
[ "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...
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L516-L544
16,208
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
KeyBundle.copy
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
def copy(self): 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
[ "def", "copy", "(", "self", ")", ":", "kb", "=", "KeyBundle", "(", ")", "kb", ".", "_keys", "=", "self", ".", "_keys", "[", ":", "]", "kb", ".", "cache_time", "=", "self", ".", "cache_time", "kb", ".", "verify_ssl", "=", "self", ".", "verify_ssl", ...
Make deep copy of this KeyBundle :return: The copy
[ "Make", "deep", "copy", "of", "this", "KeyBundle" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L549-L567
16,209
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/simple_jwt.py
SimpleJWT.unpack
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
def unpack(self, token, **kwargs): 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
[ "def", "unpack", "(", "self", ",", "token", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "token", ",", "str", ")", ":", "try", ":", "token", "=", "token", ".", "encode", "(", "\"utf-8\"", ")", "except", "UnicodeDecodeError", ":", "pass...
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.
[ "Unpacks", "a", "JWT", "into", "its", "parts", "and", "base64", "decodes", "the", "parts", "individually" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/simple_jwt.py#L27-L60
16,210
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/simple_jwt.py
SimpleJWT.pack
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
def pack(self, parts=None, headers=None): 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])
[ "def", "pack", "(", "self", ",", "parts", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "not", "headers", ":", "if", "self", ".", "headers", ":", "headers", "=", "self", ".", "headers", "else", ":", "headers", "=", "{", "'alg'", ":", ...
Packs components into a JWT :param parts: List of parts to pack :param headers: The JWT headers :return:
[ "Packs", "components", "into", "a", "JWT" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/simple_jwt.py#L62-L85
16,211
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/simple_jwt.py
SimpleJWT.verify_header
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
def verify_header(self, key, val): 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
[ "def", "verify_header", "(", "self", ",", "key", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "list", ")", ":", "if", "self", ".", "headers", "[", "key", "]", "in", "val", ":", "return", "True", "else", ":", "return", "False", "else",...
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
[ "Check", "that", "a", "particular", "header", "claim", "is", "present", "and", "has", "a", "specific", "value" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/simple_jwt.py#L108-L128
16,212
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/simple_jwt.py
SimpleJWT.verify_headers
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
def verify_headers(self, check_presence=True, **kwargs): 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
[ "def", "verify_headers", "(", "self", ",", "check_presence", "=", "True", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "try", ":", "_ok", "=", "self", ".", "verify_header", "(", "key", ",...
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.
[ "Check", "that", "a", "set", "of", "particular", "header", "claim", "are", "present", "and", "has", "specific", "values" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/simple_jwt.py#L130-L151
16,213
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/hmac.py
HMACSigner.sign
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
def sign(self, msg, key): h = hmac.HMAC(key, self.algorithm(), default_backend()) h.update(msg) return h.finalize()
[ "def", "sign", "(", "self", ",", "msg", ",", "key", ")", ":", "h", "=", "hmac", ".", "HMAC", "(", "key", ",", "self", ".", "algorithm", "(", ")", ",", "default_backend", "(", ")", ")", "h", ".", "update", "(", "msg", ")", "return", "h", ".", ...
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
[ "Create", "a", "signature", "over", "a", "message", "as", "defined", "in", "RFC7515", "using", "a", "symmetric", "key" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/hmac.py#L23-L34
16,214
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/hmac.py
HMACSigner.verify
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
def verify(self, msg, sig, key): try: h = hmac.HMAC(key, self.algorithm(), default_backend()) h.update(msg) h.verify(sig) return True except: return False
[ "def", "verify", "(", "self", ",", "msg", ",", "sig", ",", "key", ")", ":", "try", ":", "h", "=", "hmac", ".", "HMAC", "(", "key", ",", "self", ".", "algorithm", "(", ")", ",", "default_backend", "(", ")", ")", "h", ".", "update", "(", "msg", ...
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.
[ "Verifies", "whether", "sig", "is", "the", "correct", "message", "authentication", "code", "of", "data", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/hmac.py#L36-L52
16,215
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/jwk.py
ensure_ec_params
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
def ensure_ec_params(jwk_dict, private): 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)
[ "def", "ensure_ec_params", "(", "jwk_dict", ",", "private", ")", ":", "provided", "=", "frozenset", "(", "jwk_dict", ".", "keys", "(", ")", ")", "if", "private", "is", "not", "None", "and", "private", ":", "required", "=", "EC_PUBLIC_REQUIRED", "|", "EC_PR...
Ensure all required EC parameters are present in dictionary
[ "Ensure", "all", "required", "EC", "parameters", "are", "present", "in", "dictionary" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/jwk.py#L35-L42
16,216
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/jwk.py
ensure_rsa_params
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
def ensure_rsa_params(jwk_dict, private): 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)
[ "def", "ensure_rsa_params", "(", "jwk_dict", ",", "private", ")", ":", "provided", "=", "frozenset", "(", "jwk_dict", ".", "keys", "(", ")", ")", "if", "private", "is", "not", "None", "and", "private", ":", "required", "=", "RSA_PUBLIC_REQUIRED", "|", "RSA...
Ensure all required RSA parameters are present in dictionary
[ "Ensure", "all", "required", "RSA", "parameters", "are", "present", "in", "dictionary" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/jwk.py#L45-L52
16,217
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/jwk.py
ensure_params
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
def ensure_params(kty, provided, required): if not required <= provided: missing = required - provided raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(missing))))
[ "def", "ensure_params", "(", "kty", ",", "provided", ",", "required", ")", ":", "if", "not", "required", "<=", "provided", ":", "missing", "=", "required", "-", "provided", "raise", "MissingValue", "(", "'Missing properties for kty={}, {}'", ".", "format", "(", ...
Ensure all required parameters are present in dictionary
[ "Ensure", "all", "required", "parameters", "are", "present", "in", "dictionary" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/jwk.py#L55-L59
16,218
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/jwk.py
jwk_wrap
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
def jwk_wrap(key, use="", kid=""): 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
[ "def", "jwk_wrap", "(", "key", ",", "use", "=", "\"\"", ",", "kid", "=", "\"\"", ")", ":", "if", "isinstance", "(", "key", ",", "rsa", ".", "RSAPublicKey", ")", "or", "isinstance", "(", "key", ",", "rsa", ".", "RSAPrivateKey", ")", ":", "kspec", "=...
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
[ "Instantiate", "a", "Key", "instance", "with", "the", "given", "key" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/jwk.py#L156-L175
16,219
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
update_keyjar
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
def update_keyjar(keyjar): for iss, kbl in keyjar.items(): for kb in kbl: kb.update()
[ "def", "update_keyjar", "(", "keyjar", ")", ":", "for", "iss", ",", "kbl", "in", "keyjar", ".", "items", "(", ")", ":", "for", "kb", "in", "kbl", ":", "kb", ".", "update", "(", ")" ]
Go through the whole key jar, key bundle by key bundle and update them one by one. :param keyjar: The key jar to update
[ "Go", "through", "the", "whole", "key", "jar", "key", "bundle", "by", "key", "bundle", "and", "update", "them", "one", "by", "one", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L698-L707
16,220
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
key_summary
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
def key_summary(keyjar, issuer): 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)
[ "def", "key_summary", "(", "keyjar", ",", "issuer", ")", ":", "try", ":", "kbl", "=", "keyjar", "[", "issuer", "]", "except", "KeyError", ":", "return", "''", "else", ":", "key_list", "=", "[", "]", "for", "kb", "in", "kbl", ":", "for", "key", "in"...
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
[ "Return", "a", "text", "representation", "of", "the", "keyjar", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L710-L732
16,221
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.get
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
def get(self, key_use, key_type="", owner="", kid=None, **kwargs): 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
[ "def", "get", "(", "self", ",", "key_use", ",", "key_type", "=", "\"\"", ",", "owner", "=", "\"\"", ",", "kid", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "key_use", "in", "[", "\"dec\"", ",", "\"enc\"", "]", ":", "use", "=", "\"enc\""...
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
[ "Get", "all", "keys", "that", "matches", "a", "set", "of", "search", "criteria" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L148-L230
16,222
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.get_signing_key
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
def get_signing_key(self, key_type="", owner="", kid=None, **kwargs): return self.get("sig", key_type, owner, kid, **kwargs)
[ "def", "get_signing_key", "(", "self", ",", "key_type", "=", "\"\"", ",", "owner", "=", "\"\"", ",", "kid", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get", "(", "\"sig\"", ",", "key_type", ",", "owner", ",", "kid", ","...
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
[ "Shortcut", "to", "use", "for", "signing", "keys", "only", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L232-L242
16,223
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.keys_by_alg_and_usage
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
def keys_by_alg_and_usage(self, issuer, alg, usage): if usage in ["sig", "ver"]: ktype = jws_alg2keytype(alg) else: ktype = jwe_alg2keytype(alg) return self.get(usage, ktype, issuer)
[ "def", "keys_by_alg_and_usage", "(", "self", ",", "issuer", ",", "alg", ",", "usage", ")", ":", "if", "usage", "in", "[", "\"sig\"", ",", "\"ver\"", "]", ":", "ktype", "=", "jws_alg2keytype", "(", "alg", ")", "else", ":", "ktype", "=", "jwe_alg2keytype",...
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
[ "Find", "all", "keys", "that", "can", "be", "used", "for", "a", "specific", "crypto", "algorithm", "and", "usage", "by", "key", "owner", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L253-L268
16,224
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.get_issuer_keys
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
def get_issuer_keys(self, issuer): res = [] for kbl in self.issuer_keys[issuer]: res.extend(kbl.keys()) return res
[ "def", "get_issuer_keys", "(", "self", ",", "issuer", ")", ":", "res", "=", "[", "]", "for", "kbl", "in", "self", ".", "issuer_keys", "[", "issuer", "]", ":", "res", ".", "extend", "(", "kbl", ".", "keys", "(", ")", ")", "return", "res" ]
Get all the keys that belong to an entity. :param issuer: The entity ID :return: A possibly empty list of keys
[ "Get", "all", "the", "keys", "that", "belong", "to", "an", "entity", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L270-L280
16,225
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.match_owner
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
def match_owner(self, url): for owner in self.issuer_keys.keys(): if owner.startswith(url): return owner raise KeyError("No keys for '{}' in this keyjar".format(url))
[ "def", "match_owner", "(", "self", ",", "url", ")", ":", "for", "owner", "in", "self", ".", "issuer_keys", ".", "keys", "(", ")", ":", "if", "owner", ".", "startswith", "(", "url", ")", ":", "return", "owner", "raise", "KeyError", "(", "\"No keys for '...
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
[ "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", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L311-L324
16,226
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.load_keys
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
def load_keys(self, issuer, jwks_uri='', jwks=None, replace=False): 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))
[ "def", "load_keys", "(", "self", ",", "issuer", ",", "jwks_uri", "=", "''", ",", "jwks", "=", "None", ",", "replace", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"Initiating key bundle for issuer: %s\"", "%", "issuer", ")", "if", "replace", "or"...
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
[ "Fetch", "keys", "from", "another", "server" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L335-L357
16,227
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.find
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
def find(self, source, issuer): try: for kb in self.issuer_keys[issuer]: if kb.source == source: return kb except KeyError: return None return None
[ "def", "find", "(", "self", ",", "source", ",", "issuer", ")", ":", "try", ":", "for", "kb", "in", "self", ".", "issuer_keys", "[", "issuer", "]", ":", "if", "kb", ".", "source", "==", "source", ":", "return", "kb", "except", "KeyError", ":", "retu...
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
[ "Find", "a", "key", "bundle", "based", "on", "the", "source", "of", "the", "keys" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L359-L374
16,228
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.export_jwks_as_json
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
def export_jwks_as_json(self, private=False, issuer=""): return json.dumps(self.export_jwks(private, issuer))
[ "def", "export_jwks_as_json", "(", "self", ",", "private", "=", "False", ",", "issuer", "=", "\"\"", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "export_jwks", "(", "private", ",", "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
[ "Export", "a", "JWKS", "as", "a", "JSON", "document", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L391-L399
16,229
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.import_jwks
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
def import_jwks(self, jwks, issuer): 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)]
[ "def", "import_jwks", "(", "self", ",", "jwks", ",", "issuer", ")", ":", "try", ":", "_keys", "=", "jwks", "[", "\"keys\"", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Not a proper JWKS'", ")", "else", ":", "try", ":", "self", ".", "i...
Imports all the keys that are represented in a JWKS :param jwks: Dictionary representation of a JWKS :param issuer: Who 'owns' the JWKS
[ "Imports", "all", "the", "keys", "that", "are", "represented", "in", "a", "JWKS" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L401-L418
16,230
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.import_jwks_as_json
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
def import_jwks_as_json(self, jwks, issuer): return self.import_jwks(json.loads(jwks), issuer)
[ "def", "import_jwks_as_json", "(", "self", ",", "jwks", ",", "issuer", ")", ":", "return", "self", ".", "import_jwks", "(", "json", ".", "loads", "(", "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
[ "Imports", "all", "the", "keys", "that", "are", "represented", "in", "a", "JWKS", "expressed", "as", "a", "JSON", "object" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L420-L428
16,231
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.get_jwt_decrypt_keys
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
def get_jwt_decrypt_keys(self, jwt, **kwargs): 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
[ "def", "get_jwt_decrypt_keys", "(", "self", ",", "jwt", ",", "*", "*", "kwargs", ")", ":", "try", ":", "_key_type", "=", "jwe_alg2keytype", "(", "jwt", ".", "headers", "[", "'alg'", "]", ")", "except", "KeyError", ":", "_key_type", "=", "''", "try", ":...
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
[ "Get", "decryption", "keys", "from", "this", "keyjar", "based", "on", "information", "carried", "in", "a", "JWE", ".", "These", "keys", "should", "be", "usable", "to", "decrypt", "an", "encrypted", "JWT", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L519-L563
16,232
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.get_jwt_verify_keys
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
def get_jwt_verify_keys(self, jwt, **kwargs): 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
[ "def", "get_jwt_verify_keys", "(", "self", ",", "jwt", ",", "*", "*", "kwargs", ")", ":", "try", ":", "allow_missing_kid", "=", "kwargs", "[", "'allow_missing_kid'", "]", "except", "KeyError", ":", "allow_missing_kid", "=", "False", "try", ":", "_key_type", ...
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
[ "Get", "keys", "from", "this", "key", "jar", "based", "on", "information", "in", "a", "JWS", ".", "These", "keys", "should", "be", "usable", "to", "verify", "the", "signed", "JWT", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L565-L628
16,233
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_jar.py
KeyJar.copy
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
def copy(self): kj = KeyJar() for issuer in self.owners(): kj[issuer] = [kb.copy() for kb in self[issuer]] kj.verify_ssl = self.verify_ssl return kj
[ "def", "copy", "(", "self", ")", ":", "kj", "=", "KeyJar", "(", ")", "for", "issuer", "in", "self", ".", "owners", "(", ")", ":", "kj", "[", "issuer", "]", "=", "[", "kb", ".", "copy", "(", ")", "for", "kb", "in", "self", "[", "issuer", "]", ...
Make deep copy of this key jar. :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
[ "Make", "deep", "copy", "of", "this", "key", "jar", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L630-L641
16,234
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
pick_key
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
def pick_key(keys, use, alg='', key_type='', kid=''): 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
[ "def", "pick_key", "(", "keys", ",", "use", ",", "alg", "=", "''", ",", "key_type", "=", "''", ",", "kid", "=", "''", ")", ":", "res", "=", "[", "]", "if", "not", "key_type", ":", "if", "use", "==", "'sig'", ":", "key_type", "=", "jws_alg2keytype...
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
[ "Based", "on", "given", "criteria", "pick", "out", "the", "keys", "that", "fulfill", "them", "from", "a", "given", "set", "of", "keys", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L33-L75
16,235
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
JWT.pack_init
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
def pack_init(self, recv, aud): 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
[ "def", "pack_init", "(", "self", ",", "recv", ",", "aud", ")", ":", "argv", "=", "{", "'iss'", ":", "self", ".", "iss", ",", "'iat'", ":", "utc_time_sans_frac", "(", ")", "}", "if", "self", ".", "lifetime", ":", "argv", "[", "'exp'", "]", "=", "a...
Gather initial information for the payload. :return: A dictionary with claims and values
[ "Gather", "initial", "information", "for", "the", "payload", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L155-L169
16,236
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
JWT.pack_key
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
def pack_key(self, owner_id='', kid=''): 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]
[ "def", "pack_key", "(", "self", ",", "owner_id", "=", "''", ",", "kid", "=", "''", ")", ":", "keys", "=", "pick_key", "(", "self", ".", "my_keys", "(", "owner_id", ",", "'sig'", ")", ",", "'sig'", ",", "alg", "=", "self", ".", "alg", ",", "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
[ "Find", "a", "key", "to", "be", "used", "for", "signing", "the", "Json", "Web", "Token" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L171-L185
16,237
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
JWT._verify
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
def _verify(self, rj, token): keys = self.key_jar.get_jwt_verify_keys(rj.jwt) return rj.verify_compact(token, keys)
[ "def", "_verify", "(", "self", ",", "rj", ",", "token", ")", ":", "keys", "=", "self", ".", "key_jar", ".", "get_jwt_verify_keys", "(", "rj", ".", "jwt", ")", "return", "rj", ".", "verify_compact", "(", "token", ",", "keys", ")" ]
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
[ "Verify", "a", "signed", "JSON", "Web", "Token" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L242-L251
16,238
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
JWT._decrypt
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
def _decrypt(self, rj, token): 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)
[ "def", "_decrypt", "(", "self", ",", "rj", ",", "token", ")", ":", "if", "self", ".", "iss", ":", "keys", "=", "self", ".", "key_jar", ".", "get_jwt_decrypt_keys", "(", "rj", ".", "jwt", ",", "aud", "=", "self", ".", "iss", ")", "else", ":", "key...
Decrypt an encrypted JsonWebToken :param rj: :py:class:`cryptojwt.jwe.JWE` instance :param token: The encrypted JsonWebToken :return:
[ "Decrypt", "an", "encrypted", "JsonWebToken" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L253-L265
16,239
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
JWT.verify_profile
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
def verify_profile(msg_cls, info, **kwargs): _msg = msg_cls(**info) if not _msg.verify(**kwargs): raise VerificationError() return _msg
[ "def", "verify_profile", "(", "msg_cls", ",", "info", ",", "*", "*", "kwargs", ")", ":", "_msg", "=", "msg_cls", "(", "*", "*", "info", ")", "if", "not", "_msg", ".", "verify", "(", "*", "*", "kwargs", ")", ":", "raise", "VerificationError", "(", "...
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.
[ "If", "a", "message", "type", "is", "known", "for", "this", "JSON", "document", ".", "Verify", "that", "the", "document", "complies", "with", "the", "message", "specifications", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L268-L282
16,240
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
JWT.unpack
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
def unpack(self, token): 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
[ "def", "unpack", "(", "self", ",", "token", ")", ":", "if", "not", "token", ":", "raise", "KeyError", "_jwe_header", "=", "_jws_header", "=", "None", "# Check if it's an encrypted JWT", "darg", "=", "{", "}", "if", "self", ".", "allowed_enc_encs", ":", "darg...
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.
[ "Unpack", "a", "received", "signed", "or", "signed", "and", "encrypted", "Json", "Web", "Token" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L284-L367
16,241
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/jws.py
factory
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
def factory(token, alg=''): _jw = JWS(alg=alg) if _jw.is_jws(token): return _jw else: return None
[ "def", "factory", "(", "token", ",", "alg", "=", "''", ")", ":", "_jw", "=", "JWS", "(", "alg", "=", "alg", ")", "if", "_jw", ".", "is_jws", "(", "token", ")", ":", "return", "_jw", "else", ":", "return", "None" ]
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
[ "Instantiate", "an", "JWS", "instance", "if", "the", "token", "is", "a", "signed", "JWT", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/jws.py#L434-L447
16,242
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/jws.py
JWS.sign_compact
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
def sign_compact(self, keys=None, protected=None, **kwargs): _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")])
[ "def", "sign_compact", "(", "self", ",", "keys", "=", "None", ",", "protected", "=", "None", ",", "*", "*", "kwargs", ")", ":", "_headers", "=", "self", ".", "_header", "_headers", ".", "update", "(", "kwargs", ")", "key", ",", "xargs", ",", "_alg", ...
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
[ "Produce", "a", "JWS", "using", "the", "JWS", "Compact", "Serialization" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/jws.py#L106-L143
16,243
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/jws.py
JWS.verify_compact
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
def verify_compact(self, jws=None, keys=None, allow_none=False, sigalg=None): return self.verify_compact_verbose(jws, keys, allow_none, sigalg)['msg']
[ "def", "verify_compact", "(", "self", ",", "jws", "=", "None", ",", "keys", "=", "None", ",", "allow_none", "=", "False", ",", "sigalg", "=", "None", ")", ":", "return", "self", ".", "verify_compact_verbose", "(", "jws", ",", "keys", ",", "allow_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
[ "Verify", "a", "JWT", "signature" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/jws.py#L145-L157
16,244
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/jws.py
JWS.verify_compact_verbose
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
def verify_compact_verbose(self, jws=None, keys=None, allow_none=False, sigalg=None): 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()
[ "def", "verify_compact_verbose", "(", "self", ",", "jws", "=", "None", ",", "keys", "=", "None", ",", "allow_none", "=", "False", ",", "sigalg", "=", "None", ")", ":", "if", "jws", ":", "jwt", "=", "JWSig", "(", ")", ".", "unpack", "(", "jws", ")",...
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
[ "Verify", "a", "JWT", "signature", "and", "return", "dict", "with", "validation", "results" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/jws.py#L159-L250
16,245
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/jws.py
JWS.sign_json
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
def sign_json(self, keys=None, headers=None, flatten=False): 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)
[ "def", "sign_json", "(", "self", ",", "keys", "=", "None", ",", "headers", "=", "None", ",", "flatten", "=", "False", ")", ":", "def", "create_signature", "(", "protected", ",", "unprotected", ")", ":", "protected_headers", "=", "protected", "or", "{", "...
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.
[ "Produce", "JWS", "using", "the", "JWS", "JSON", "Serialization" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/jws.py#L252-L293
16,246
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/jws.py
JWS._is_json_serialized_jws
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
def _is_json_serialized_jws(self, json_jws): 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
[ "def", "_is_json_serialized_jws", "(", "self", ",", "json_jws", ")", ":", "json_ser_keys", "=", "{", "\"payload\"", ",", "\"signatures\"", "}", "flattened_json_ser_keys", "=", "{", "\"payload\"", ",", "\"signature\"", "}", "if", "not", "json_ser_keys", ".", "issub...
Check if we've got a JSON serialized signed JWT. :param json_jws: The message :return: True/False
[ "Check", "if", "we", "ve", "got", "a", "JSON", "serialized", "signed", "JWT", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/jws.py#L360-L373
16,247
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/jws.py
JWS._is_compact_jws
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
def _is_compact_jws(self, jws): 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
[ "def", "_is_compact_jws", "(", "self", ",", "jws", ")", ":", "try", ":", "jwt", "=", "JWSig", "(", ")", ".", "unpack", "(", "jws", ")", "except", "Exception", "as", "err", ":", "logger", ".", "warning", "(", "'Could not parse JWS: {}'", ".", "format", ...
Check if we've got a compact signed JWT :param jws: The message :return: True/False
[ "Check", "if", "we", "ve", "got", "a", "compact", "signed", "JWT" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/jws.py#L375-L399
16,248
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/rsa.py
RSASigner.sign
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
def sign(self, msg, key): 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
[ "def", "sign", "(", "self", ",", "msg", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "rsa", ".", "RSAPrivateKey", ")", ":", "raise", "TypeError", "(", "\"The key must be an instance of rsa.RSAPrivateKey\"", ")", "sig", "=", "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
[ "Create", "a", "signature", "over", "a", "message", "as", "defined", "in", "RFC7515", "using", "an", "RSA", "key" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/rsa.py#L14-L29
16,249
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/rsa.py
RSASigner.verify
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
def verify(self, msg, signature, key): 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
[ "def", "verify", "(", "self", ",", "msg", ",", "signature", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "rsa", ".", "RSAPublicKey", ")", ":", "raise", "TypeError", "(", "\"The public key must be an instance of RSAPublicKey\"", ")", "try",...
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
[ "Verifies", "whether", "signature", "is", "a", "valid", "signature", "for", "message" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/rsa.py#L31-L53
16,250
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
generate_and_store_rsa_key
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
def generate_and_store_rsa_key(key_size=2048, filename='rsa.key', passphrase=''): 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
[ "def", "generate_and_store_rsa_key", "(", "key_size", "=", "2048", ",", "filename", "=", "'rsa.key'", ",", "passphrase", "=", "''", ")", ":", "private_key", "=", "rsa", ".", "generate_private_key", "(", "public_exponent", "=", "65537", ",", "key_size", "=", "k...
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
[ "Generate", "a", "private", "RSA", "key", "and", "store", "a", "PEM", "representation", "of", "it", "in", "a", "file", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L29-L60
16,251
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
import_public_rsa_key_from_file
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
def import_public_rsa_key_from_file(filename): with open(filename, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) return public_key
[ "def", "import_public_rsa_key_from_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "key_file", ":", "public_key", "=", "serialization", ".", "load_pem_public_key", "(", "key_file", ".", "read", "(", ")", ",", "backe...
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
[ "Read", "a", "public", "RSA", "key", "from", "a", "PEM", "file", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L80-L93
16,252
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
import_rsa_key
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
def import_rsa_key(pem_data): 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()
[ "def", "import_rsa_key", "(", "pem_data", ")", ":", "if", "not", "pem_data", ".", "startswith", "(", "PREFIX", ")", ":", "pem_data", "=", "bytes", "(", "'{}\\n{}\\n{}'", ".", "format", "(", "PREFIX", ",", "pem_data", ",", "POSTFIX", ")", ",", "'utf-8'", ...
Extract an RSA key from a PEM-encoded X.509 certificate :param pem_data: RSA key encoded in standard form :return: rsa.RSAPublicKey instance
[ "Extract", "an", "RSA", "key", "from", "a", "PEM", "-", "encoded", "X", ".", "509", "certificate" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L96-L109
16,253
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
rsa_eq
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
def rsa_eq(key1, key2): 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
[ "def", "rsa_eq", "(", "key1", ",", "key2", ")", ":", "pn1", "=", "key1", ".", "public_numbers", "(", ")", "pn2", "=", "key2", ".", "public_numbers", "(", ")", "# Check if two RSA keys are in fact the same", "if", "pn1", "==", "pn2", ":", "return", "True", ...
Only works for RSAPublic Keys :param key1: :param key2: :return:
[ "Only", "works", "for", "RSAPublic", "Keys" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L117-L131
16,254
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
der_cert
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
def der_cert(der_data): if isinstance(der_data, str): der_data = bytes(der_data, 'utf-8') return x509.load_der_x509_certificate(der_data, default_backend())
[ "def", "der_cert", "(", "der_data", ")", ":", "if", "isinstance", "(", "der_data", ",", "str", ")", ":", "der_data", "=", "bytes", "(", "der_data", ",", "'utf-8'", ")", "return", "x509", ".", "load_der_x509_certificate", "(", "der_data", ",", "default_backen...
Load a DER encoded certificate :param der_data: DER-encoded certificate :return: A cryptography.x509.certificate instance
[ "Load", "a", "DER", "encoded", "certificate" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L189-L198
16,255
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
load_x509_cert
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
def load_x509_cert(url, httpc, spec2key, **get_args): 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 []
[ "def", "load_x509_cert", "(", "url", ",", "httpc", ",", "spec2key", ",", "*", "*", "get_args", ")", ":", "try", ":", "r", "=", "httpc", "(", "'GET'", ",", "url", ",", "allow_redirects", "=", "True", ",", "*", "*", "get_args", ")", "if", "r", ".", ...
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)
[ "Get", "and", "transform", "a", "X509", "cert", "into", "a", "key", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L201-L226
16,256
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
cmp_public_numbers
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
def cmp_public_numbers(pn1, pn2): if pn1.n == pn2.n: if pn1.e == pn2.e: return True return False
[ "def", "cmp_public_numbers", "(", "pn1", ",", "pn2", ")", ":", "if", "pn1", ".", "n", "==", "pn2", ".", "n", ":", "if", "pn1", ".", "e", "==", "pn2", ".", "e", ":", "return", "True", "return", "False" ]
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.
[ "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", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L229-L241
16,257
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
cmp_private_numbers
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
def cmp_private_numbers(pn1, pn2): 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
[ "def", "cmp_private_numbers", "(", "pn1", ",", "pn2", ")", ":", "if", "not", "cmp_public_numbers", "(", "pn1", ".", "public_numbers", ",", "pn2", ".", "public_numbers", ")", ":", "return", "False", "for", "param", "in", "[", "'d'", ",", "'p'", ",", "'q'"...
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.
[ "Compare", "2", "sets", "of", "private", "numbers", ".", "This", "is", "for", "comparing", "2", "private", "RSA", "keys", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L244-L259
16,258
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
RSAKey.deserialize
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
def deserialize(self): # 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()
[ "def", "deserialize", "(", "self", ")", ":", "# 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", ...
Based on a text based representation of an RSA key this method instantiates a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or RSAPublicKey instance
[ "Based", "on", "a", "text", "based", "representation", "of", "an", "RSA", "key", "this", "method", "instantiates", "a", "cryptography", ".", "hazmat", ".", "primitives", ".", "asymmetric", ".", "rsa", ".", "RSAPrivateKey", "or", "RSAPublicKey", "instance" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L340-L400
16,259
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
RSAKey.serialize
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
def serialize(self, private=False): 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
[ "def", "serialize", "(", "self", ",", "private", "=", "False", ")", ":", "if", "not", "self", ".", "priv_key", "and", "not", "self", ".", "pub_key", ":", "raise", "SerializationNotPossible", "(", ")", "res", "=", "self", ".", "common", "(", ")", "publi...
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
[ "Given", "a", "cryptography", ".", "hazmat", ".", "primitives", ".", "asymmetric", ".", "rsa", ".", "RSAPrivateKey", "or", "RSAPublicKey", "instance", "construct", "the", "JWK", "representation", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L402-L432
16,260
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/rsa.py
RSAKey.load_key
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
def load_key(self, key): 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
[ "def", "load_key", "(", "self", ",", "key", ")", ":", "self", ".", "_serialize", "(", "key", ")", "if", "isinstance", "(", "key", ",", "rsa", ".", "RSAPrivateKey", ")", ":", "self", ".", "priv_key", "=", "key", "self", ".", "pub_key", "=", "key", "...
Load a RSA key. Try to serialize the key before binding it to this instance. :param key: An RSA key instance
[ "Load", "a", "RSA", "key", ".", "Try", "to", "serialize", "the", "key", "before", "binding", "it", "to", "this", "instance", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L449-L464
16,261
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/dsa.py
ECDSASigner.sign
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
def sign(self, msg, key): 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)
[ "def", "sign", "(", "self", ",", "msg", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "ec", ".", "EllipticCurvePrivateKey", ")", ":", "raise", "TypeError", "(", "\"The private key must be an instance of \"", "\"ec.EllipticCurvePrivateKey\"", ")...
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:
[ "Create", "a", "signature", "over", "a", "message", "as", "defined", "in", "RFC7515", "using", "an", "Elliptic", "curve", "key" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/dsa.py#L31-L53
16,262
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/dsa.py
ECDSASigner._cross_check
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
def _cross_check(self, pub_key): 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))
[ "def", "_cross_check", "(", "self", ",", "pub_key", ")", ":", "if", "self", ".", "curve_name", "!=", "pub_key", ".", "curve", ".", "name", ":", "raise", "ValueError", "(", "\"The curve in private key {} and in algorithm {} don't \"", "\"match\"", ".", "format", "(...
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
[ "In", "Ecdsa", "both", "the", "key", "and", "the", "algorithm", "define", "the", "curve", ".", "Therefore", "we", "must", "cross", "check", "them", "to", "make", "sure", "they", "re", "the", "same", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/dsa.py#L87-L98
16,263
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/dsa.py
ECDSASigner._split_raw_signature
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
def _split_raw_signature(sig): 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
[ "def", "_split_raw_signature", "(", "sig", ")", ":", "c_length", "=", "len", "(", "sig", ")", "//", "2", "r", "=", "int_from_bytes", "(", "sig", "[", ":", "c_length", "]", ",", "byteorder", "=", "'big'", ")", "s", "=", "int_from_bytes", "(", "sig", "...
Split raw signature into components :param sig: The signature :return: A 2-tuple
[ "Split", "raw", "signature", "into", "components" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/dsa.py#L101-L111
16,264
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/utils.py
alg2keytype
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
def alg2keytype(alg): 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
[ "def", "alg2keytype", "(", "alg", ")", ":", "if", "not", "alg", "or", "alg", ".", "lower", "(", ")", "==", "\"none\"", ":", "return", "\"none\"", "elif", "alg", ".", "startswith", "(", "\"RS\"", ")", "or", "alg", ".", "startswith", "(", "\"PS\"", ")"...
Go from algorithm name to key type. :param alg: The algorithm name :return: The key type
[ "Go", "from", "algorithm", "name", "to", "key", "type", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/utils.py#L36-L52
16,265
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwe_ec.py
ecdh_derive_key
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
def ecdh_derive_key(key, epk, apu, apv, alg, dk_len): # 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)
[ "def", "ecdh_derive_key", "(", "key", ",", "epk", ",", "apu", ",", "apv", ",", "alg", ",", "dk_len", ")", ":", "# Compute shared secret", "shared_key", "=", "key", ".", "exchange", "(", "ec", ".", "ECDH", "(", ")", ",", "epk", ")", "# Derive the key", ...
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
[ "ECDH", "key", "derivation", "as", "defined", "by", "JWA" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe_ec.py#L23-L43
16,266
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwe_ec.py
JWE_EC.encrypt
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
def encrypt(self, key=None, iv="", cek="", **kwargs): _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])
[ "def", "encrypt", "(", "self", ",", "key", "=", "None", ",", "iv", "=", "\"\"", ",", "cek", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "_msg", "=", "as_bytes", "(", "self", ".", "msg", ")", "_args", "=", "self", ".", "_dict", "try", ":", ...
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
[ "Produces", "a", "JWE", "as", "defined", "in", "RFC7516", "using", "an", "Elliptic", "curve", "key" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe_ec.py#L181-L214
16,267
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwe_rsa.py
JWE_RSA.encrypt
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
def encrypt(self, key, iv="", cek="", **kwargs): _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])
[ "def", "encrypt", "(", "self", ",", "key", ",", "iv", "=", "\"\"", ",", "cek", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "_msg", "=", "as_bytes", "(", "self", ".", "msg", ")", "if", "\"zip\"", "in", "self", ":", "if", "self", "[", "\"zip\...
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
[ "Produces", "a", "JWE", "as", "defined", "in", "RFC7516", "using", "RSA", "algorithms" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe_rsa.py#L22-L72
16,268
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwe_rsa.py
JWE_RSA.decrypt
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
def decrypt(self, token, key, cek=None): 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
[ "def", "decrypt", "(", "self", ",", "token", ",", "key", ",", "cek", "=", "None", ")", ":", "if", "not", "isinstance", "(", "token", ",", "JWEnc", ")", ":", "jwe", "=", "JWEnc", "(", ")", ".", "unpack", "(", "token", ")", "else", ":", "jwe", "=...
Decrypts a JWT :param token: The JWT :param key: A key to use for decrypting :param cek: Ephemeral cipher key :return: The decrypted message
[ "Decrypts", "a", "JWT" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe_rsa.py#L74-L119
16,269
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwe.py
JWE.encrypt
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
def encrypt(self, keys=None, cek="", iv="", **kwargs): _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
[ "def", "encrypt", "(", "self", ",", "keys", "=", "None", ",", "cek", "=", "\"\"", ",", "iv", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "_alg", "=", "self", "[", "\"alg\"", "]", "# Find Usable Keys", "if", "keys", ":", "keys", "=", "self", "...
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
[ "Encrypt", "a", "payload" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe.py#L64-L124
16,270
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/utils.py
base64url_to_long
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
def base64url_to_long(data): _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))
[ "def", "base64url_to_long", "(", "data", ")", ":", "_data", "=", "as_bytes", "(", "data", ")", "_d", "=", "base64", ".", "urlsafe_b64decode", "(", "_data", "+", "b'=='", ")", "# verify that it's base64url encoded and not just base64", "# that is no '+' and '/' character...
Stricter then base64_to_long since it really checks that it's base64url encoded :param data: The base64 string :return:
[ "Stricter", "then", "base64_to_long", "since", "it", "really", "checks", "that", "it", "s", "base64url", "encoded" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/utils.py#L51-L65
16,271
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/utils.py
b64d
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
def b64d(b): 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)
[ "def", "b64d", "(", "b", ")", ":", "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"...
Decode some base64-encoded bytes. Raises BadSyntax if the string contains invalid characters or padding. :param b: bytes
[ "Decode", "some", "base64", "-", "encoded", "bytes", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/utils.py#L94-L112
16,272
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/utils.py
deser
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
def deser(val): if isinstance(val, str): _val = val.encode("utf-8") else: _val = val return base64_to_long(_val)
[ "def", "deser", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "_val", "=", "val", ".", "encode", "(", "\"utf-8\"", ")", "else", ":", "_val", "=", "val", "return", "base64_to_long", "(", "_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.
[ "Deserialize", "from", "a", "string", "representation", "of", "an", "long", "integer", "to", "the", "python", "representation", "of", "a", "long", "integer", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/utils.py#L185-L198
16,273
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/__init__.py
JWK.common
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
def common(self): 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
[ "def", "common", "(", "self", ")", ":", "res", "=", "{", "\"kty\"", ":", "self", ".", "kty", "}", "if", "self", ".", "use", ":", "res", "[", "\"use\"", "]", "=", "self", ".", "use", "if", "self", ".", "kid", ":", "res", "[", "\"kid\"", "]", "...
Return the set of parameters that are common to all types of keys. :return: Dictionary
[ "Return", "the", "set", "of", "parameters", "that", "are", "common", "to", "all", "types", "of", "keys", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/__init__.py#L82-L95
16,274
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/__init__.py
JWK.verify
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
def verify(self): 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
[ "def", "verify", "(", "self", ")", ":", "for", "param", "in", "self", ".", "longs", ":", "item", "=", "getattr", "(", "self", ",", "param", ")", "if", "not", "item", "or", "isinstance", "(", "item", ",", "str", ")", ":", "continue", "if", "isinstan...
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
[ "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", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/__init__.py#L124-L152
16,275
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/utils.py
concat_sha256
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
def concat_sha256(secret, dk_len, other_info): 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]
[ "def", "concat_sha256", "(", "secret", ",", "dk_len", ",", "other_info", ")", ":", "dkm", "=", "b''", "dk_bytes", "=", "int", "(", "ceil", "(", "dk_len", "/", "8.0", ")", ")", "counter", "=", "0", "while", "len", "(", "dkm", ")", "<", "dk_bytes", "...
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
[ "The", "Concat", "KDF", "using", "SHA256", "as", "the", "hash", "function", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/utils.py#L98-L121
16,276
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwx.py
JWx.pick_keys
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
def pick_keys(self, keys, use="", alg=""): 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
[ "def", "pick_keys", "(", "self", ",", "keys", ",", "use", "=", "\"\"", ",", "alg", "=", "\"\"", ")", ":", "if", "not", "alg", ":", "alg", "=", "self", "[", "\"alg\"", "]", "if", "alg", "==", "\"none\"", ":", "return", "[", "]", "_k", "=", "self...
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
[ "The", "assumption", "is", "that", "upper", "layer", "has", "made", "certain", "you", "only", "get", "keys", "you", "can", "use", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwx.py#L175-L228
16,277
ska-sa/katcp-python
scratchpad/basic_server.py
MyServer.setup_sensors
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
def setup_sensors(self): 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)
[ "def", "setup_sensors", "(", "self", ")", ":", "self", ".", "_add_result", "=", "Sensor", ".", "float", "(", "\"add.result\"", ",", "\"Last ?add result.\"", ",", "\"\"", ",", "[", "-", "10000", ",", "10000", "]", ")", "self", ".", "_add_result", ".", "se...
Setup some server sensors.
[ "Setup", "some", "server", "sensors", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/scratchpad/basic_server.py#L29-L50
16,278
ska-sa/katcp-python
scratchpad/basic_server.py
MyServer.request_add
def request_add(self, req, x, y): """Add two numbers""" r = x + y self._add_result.set_value(r) return ("ok", r)
python
def request_add(self, req, x, y): r = x + y self._add_result.set_value(r) return ("ok", r)
[ "def", "request_add", "(", "self", ",", "req", ",", "x", ",", "y", ")", ":", "r", "=", "x", "+", "y", "self", ".", "_add_result", ".", "set_value", "(", "r", ")", "return", "(", "\"ok\"", ",", "r", ")" ]
Add two numbers
[ "Add", "two", "numbers" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/scratchpad/basic_server.py#L54-L58
16,279
ska-sa/katcp-python
scratchpad/basic_server.py
MyServer.request_time
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
def request_time(self, req): r = time.time() self._time_result.set_value(r) return ("ok", r)
[ "def", "request_time", "(", "self", ",", "req", ")", ":", "r", "=", "time", ".", "time", "(", ")", "self", ".", "_time_result", ".", "set_value", "(", "r", ")", "return", "(", "\"ok\"", ",", "r", ")" ]
Return the current time in ms since the Unix Epoch.
[ "Return", "the", "current", "time", "in", "ms", "since", "the", "Unix", "Epoch", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/scratchpad/basic_server.py#L62-L66
16,280
ska-sa/katcp-python
scratchpad/basic_server.py
MyServer.request_eval
def request_eval(self, req, expression): """Evaluate a Python expression.""" r = str(eval(expression)) self._eval_result.set_value(r) return ("ok", r)
python
def request_eval(self, req, expression): r = str(eval(expression)) self._eval_result.set_value(r) return ("ok", r)
[ "def", "request_eval", "(", "self", ",", "req", ",", "expression", ")", ":", "r", "=", "str", "(", "eval", "(", "expression", ")", ")", "self", ".", "_eval_result", ".", "set_value", "(", "r", ")", "return", "(", "\"ok\"", ",", "r", ")" ]
Evaluate a Python expression.
[ "Evaluate", "a", "Python", "expression", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/scratchpad/basic_server.py#L70-L74
16,281
ska-sa/katcp-python
scratchpad/basic_server.py
MyServer.request_set_sensor_inactive
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
def request_set_sensor_inactive(self, req, sensor_name): sensor = self.get_sensor(sensor_name) ts, status, value = sensor.read() sensor.set_value(value, sensor.INACTIVE, ts) return('ok',)
[ "def", "request_set_sensor_inactive", "(", "self", ",", "req", ",", "sensor_name", ")", ":", "sensor", "=", "self", ".", "get_sensor", "(", "sensor_name", ")", "ts", ",", "status", ",", "value", "=", "sensor", ".", "read", "(", ")", "sensor", ".", "set_v...
Set sensor status to inactive
[ "Set", "sensor", "status", "to", "inactive" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/scratchpad/basic_server.py#L97-L102
16,282
ska-sa/katcp-python
scratchpad/basic_server.py
MyServer.request_set_sensor_unreachable
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
def request_set_sensor_unreachable(self, req, sensor_name): sensor = self.get_sensor(sensor_name) ts, status, value = sensor.read() sensor.set_value(value, sensor.UNREACHABLE, ts) return('ok',)
[ "def", "request_set_sensor_unreachable", "(", "self", ",", "req", ",", "sensor_name", ")", ":", "sensor", "=", "self", ".", "get_sensor", "(", "sensor_name", ")", "ts", ",", "status", ",", "value", "=", "sensor", ".", "read", "(", ")", "sensor", ".", "se...
Set sensor status to unreachable
[ "Set", "sensor", "status", "to", "unreachable" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/scratchpad/basic_server.py#L106-L111
16,283
ska-sa/katcp-python
scratchpad/basic_server.py
MyServer.request_raw_reverse
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
def request_raw_reverse(self, req, msg): # 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)
[ "def", "request_raw_reverse", "(", "self", ",", "req", ",", "msg", ")", ":", "# msg is a katcp.Message.request object", "reversed_args", "=", "msg", ".", "arguments", "[", ":", ":", "-", "1", "]", "# req.make_reply() makes a katcp.Message.reply using the correct request",...
A raw request handler to demonstrate the calling convention if @request decoraters are not used. Reverses the message arguments.
[ "A", "raw", "request", "handler", "to", "demonstrate", "the", "calling", "convention", "if" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/scratchpad/basic_server.py#L113-L122
16,284
ska-sa/katcp-python
katcp/resource_client.py
transform_future
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
def transform_future(transformation, 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
[ "def", "transform_future", "(", "transformation", ",", "future", ")", ":", "new_future", "=", "tornado_Future", "(", ")", "def", "_transform", "(", "f", ")", ":", "assert", "f", "is", "future", "if", "f", ".", "exc_info", "(", ")", "is", "not", "None", ...
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.
[ "Returns", "a", "new", "future", "that", "will", "resolve", "with", "a", "transformed", "value" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L44-L67
16,285
ska-sa/katcp-python
katcp/resource_client.py
monitor_resource_sync_state
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
def monitor_resource_sync_state(resource, callback, exit_event=None): 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)
[ "def", "monitor_resource_sync_state", "(", "resource", ",", "callback", ",", "exit_event", "=", "None", ")", ":", "exit_event", "=", "exit_event", "or", "AsyncEvent", "(", ")", "callback", "(", "False", ")", "# Initial condition, assume resource is not connected", "wh...
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
[ "Coroutine", "that", "monitors", "a", "KATCPResource", "s", "sync", "state", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1717-L1740
16,286
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResource.until_state
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
def until_state(self, state, timeout=None): return self._state.until_state(state, timeout=timeout)
[ "def", "until_state", "(", "self", ",", "state", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_state", ".", "until_state", "(", "state", ",", "timeout", "=", "timeout", ")" ]
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.
[ "Future", "that", "resolves", "when", "a", "certain", "client", "state", "is", "attained" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L371-L382
16,287
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResource.start
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
def start(self): # 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())
[ "def", "start", "(", "self", ")", ":", "# 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", "(", "hos...
Start the client and connect
[ "Start", "the", "client", "and", "connect" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L407-L426
16,288
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceSensorsManager._get_strategy_cache_key
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
def _get_strategy_cache_key(self, sensor_name): # 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
[ "def", "_get_strategy_cache_key", "(", "self", ",", "sensor_name", ")", ":", "# try for a direct match first, otherwise do full comparison", "if", "sensor_name", "in", "self", ".", "_strategy_cache", ":", "return", "sensor_name", "else", ":", "escaped_name", "=", "resourc...
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.
[ "Lookup", "sensor", "name", "in", "cache", "allowing", "names", "in", "escaped", "form" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L763-L788
16,289
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceSensorsManager.get_sampling_strategy
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
def get_sampling_strategy(self, sensor_name): 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
[ "def", "get_sampling_strategy", "(", "self", ",", "sensor_name", ")", ":", "cache_key", "=", "self", ".", "_get_strategy_cache_key", "(", "sensor_name", ")", "cached", "=", "self", ".", "_strategy_cache", ".", "get", "(", "cache_key", ")", "if", "not", "cached...
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
[ "Get", "the", "current", "sampling", "strategy", "for", "the", "named", "sensor" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L804-L825
16,290
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceSensorsManager.set_sampling_strategy
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
def set_sampling_strategy(self, sensor_name, strategy_and_params): 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)
[ "def", "set_sampling_strategy", "(", "self", ",", "sensor_name", ",", "strategy_and_params", ")", ":", "try", ":", "strategy_and_params", "=", "resource", ".", "normalize_strategy_parameters", "(", "strategy_and_params", ")", "self", ".", "_strategy_cache", "[", "sens...
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.
[ "Set", "the", "sampling", "strategy", "for", "the", "named", "sensor" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L828-L866
16,291
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceSensorsManager.reapply_sampling_strategies
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
def reapply_sampling_strategies(self): 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)
[ "def", "reapply_sampling_strategies", "(", "self", ")", ":", "check_sensor", "=", "self", ".", "_inspecting_client", ".", "future_check_sensor", "for", "sensor_name", ",", "strategy", "in", "list", "(", "self", ".", "_strategy_cache", ".", "items", "(", ")", ")"...
Reapply all sensor strategies using cached values
[ "Reapply", "all", "sensor", "strategies", "using", "cached", "values" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L889-L906
16,292
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceRequest.issue_request
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
def issue_request(self, *args, **kwargs): 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)
[ "def", "issue_request", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "kwargs", ".", "pop", "(", "'timeout'", ",", "None", ")", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "timeout_hint", "kwar...
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
[ "Issue", "the", "wrapped", "request", "to", "the", "server", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L941-L971
16,293
ska-sa/katcp-python
katcp/resource_client.py
ClientGroup.wait
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
def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None, max_grace_period=1.0): 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))
[ "def", "wait", "(", "self", ",", "sensor_name", ",", "condition_or_value", ",", "timeout", "=", "5.0", ",", "quorum", "=", "None", ",", "max_grace_period", "=", "1.0", ")", ":", "if", "quorum", "is", "None", ":", "quorum", "=", "len", "(", "self", ".",...
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
[ "Wait", "for", "sensor", "present", "on", "all", "group", "clients", "to", "satisfy", "a", "condition", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1169-L1249
16,294
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.set_ioloop
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
def set_ioloop(self, ioloop=None): ioloop = ioloop or tornado.ioloop.IOLoop.current() self.ioloop = ioloop for res in dict.values(self.children): res.set_ioloop(ioloop)
[ "def", "set_ioloop", "(", "self", ",", "ioloop", "=", "None", ")", ":", "ioloop", "=", "ioloop", "or", "tornado", ".", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "self", ".", "ioloop", "=", "ioloop", "for", "res", "in", "dict", ".", "values",...
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()
[ "Set", "the", "tornado", "ioloop", "to", "use" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1381-L1390
16,295
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.is_connected
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
def is_connected(self): return all([r.is_connected() for r in dict.values(self.children)])
[ "def", "is_connected", "(", "self", ")", ":", "return", "all", "(", "[", "r", ".", "is_connected", "(", ")", "for", "r", "in", "dict", ".", "values", "(", "self", ".", "children", ")", "]", ")" ]
Indication of the connection state of all children
[ "Indication", "of", "the", "connection", "state", "of", "all", "children" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1392-L1394
16,296
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.until_synced
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
def until_synced(self, timeout=None): futures = [r.until_synced(timeout) for r in dict.values(self.children)] yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError)
[ "def", "until_synced", "(", "self", ",", "timeout", "=", "None", ")", ":", "futures", "=", "[", "r", ".", "until_synced", "(", "timeout", ")", "for", "r", "in", "dict", ".", "values", "(", "self", ".", "children", ")", "]", "yield", "tornado", ".", ...
Return a tornado Future; resolves when all subordinate clients are synced
[ "Return", "a", "tornado", "Future", ";", "resolves", "when", "all", "subordinate", "clients", "are", "synced" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1402-L1405
16,297
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.until_not_synced
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
def until_not_synced(self, timeout=None): yield until_any(*[r.until_not_synced() for r in dict.values(self.children)], timeout=timeout)
[ "def", "until_not_synced", "(", "self", ",", "timeout", "=", "None", ")", ":", "yield", "until_any", "(", "*", "[", "r", ".", "until_not_synced", "(", ")", "for", "r", "in", "dict", ".", "values", "(", "self", ".", "children", ")", "]", ",", "timeout...
Return a tornado Future; resolves when any subordinate client is not synced
[ "Return", "a", "tornado", "Future", ";", "resolves", "when", "any", "subordinate", "client", "is", "not", "synced" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1408-L1411
16,298
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.until_any_child_in_state
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
def until_any_child_in_state(self, state, timeout=None): return until_any(*[r.until_state(state) for r in dict.values(self.children)], timeout=timeout)
[ "def", "until_any_child_in_state", "(", "self", ",", "state", ",", "timeout", "=", "None", ")", ":", "return", "until_any", "(", "*", "[", "r", ".", "until_state", "(", "state", ")", "for", "r", "in", "dict", ".", "values", "(", "self", ".", "children"...
Return a tornado Future; resolves when any client is in specified state
[ "Return", "a", "tornado", "Future", ";", "resolves", "when", "any", "client", "is", "in", "specified", "state" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1413-L1416
16,299
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.until_all_children_in_state
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
def until_all_children_in_state(self, state, timeout=None): futures = [r.until_state(state, timeout=timeout) for r in dict.values(self.children)] yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError)
[ "def", "until_all_children_in_state", "(", "self", ",", "state", ",", "timeout", "=", "None", ")", ":", "futures", "=", "[", "r", ".", "until_state", "(", "state", ",", "timeout", "=", "timeout", ")", "for", "r", "in", "dict", ".", "values", "(", "self...
Return a tornado Future; resolves when all clients are in specified state
[ "Return", "a", "tornado", "Future", ";", "resolves", "when", "all", "clients", "are", "in", "specified", "state" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1419-L1423