code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if text.startswith("0"): base = 16 if text.startswith("0x") else 8 else: base = 10 try: return int(text, base) except (ValueError, TypeError): raise InvalidArgument(text)
def from_yang(self, text: str) -> Optional[int]
Override the superclass method.
3.332372
3.092169
1.077681
# create input structure if 'structure' in self.inputs: self.inputs.structure.export(folder.get_abs_path(self._DEFAULT_COORDS_FILE_NAME), fileformat="xyz") # create cp2k input file inp = Cp2kInput(self.inputs.parameters.get_dict()) inp.add_keyword("GLOBAL/PROJECT", self._DEFAULT_PROJECT_NAME) if 'structure' in self.inputs: for i, letter in enumerate('ABC'): inp.add_keyword('FORCE_EVAL/SUBSYS/CELL/' + letter, '{:<15} {:<15} {:<15}'.format(*self.inputs.structure.cell[i])) topo = "FORCE_EVAL/SUBSYS/TOPOLOGY" inp.add_keyword(topo + "/COORD_FILE_NAME", self._DEFAULT_COORDS_FILE_NAME) inp.add_keyword(topo + "/COORD_FILE_FORMAT", "XYZ") with io.open(folder.get_abs_path(self._DEFAULT_INPUT_FILE), mode="w", encoding="utf-8") as fobj: fobj.write(inp.render()) if 'settings' in self.inputs: settings = self.inputs.settings.get_dict() else: settings = {} # create code info codeinfo = CodeInfo() codeinfo.cmdline_params = settings.pop('cmdline', []) + ["-i", self._DEFAULT_INPUT_FILE] codeinfo.stdout_name = self._DEFAULT_OUTPUT_FILE codeinfo.join_files = True codeinfo.code_uuid = self.inputs.code.uuid # create calc info calcinfo = CalcInfo() calcinfo.stdin_name = self._DEFAULT_INPUT_FILE calcinfo.uuid = self.uuid calcinfo.cmdline_params = codeinfo.cmdline_params calcinfo.stdin_name = self._DEFAULT_INPUT_FILE calcinfo.stdout_name = self._DEFAULT_OUTPUT_FILE calcinfo.codes_info = [codeinfo] # file lists calcinfo.remote_symlink_list = [] if 'file' in self.inputs: calcinfo.local_copy_list = [] for fobj in self.inputs.file.values(): calcinfo.local_copy_list.append((fobj.uuid, fobj.filename, fobj.filename)) calcinfo.remote_copy_list = [] calcinfo.retrieve_list = [self._DEFAULT_OUTPUT_FILE, self._DEFAULT_RESTART_FILE_NAME] calcinfo.retrieve_list += settings.pop('additional_retrieve_list', []) # symlinks if 'parent_calc_folder' in self.inputs: comp_uuid = self.inputs.parent_calc_folder.computer.uuid remote_path = self.inputs.parent_calc_folder.get_remote_path() symlink = (comp_uuid, remote_path, self._DEFAULT_PARENT_CALC_FLDR_NAME) calcinfo.remote_symlink_list.append(symlink) # check for left over settings if settings: raise InputValidationError("The following keys have been found " + "in the settings input node {}, ".format(self.pk) + "but were not understood: " + ",".join(settings.keys())) return calcinfo
def prepare_for_submission(self, folder)
Create the input files from the input nodes passed to this instance of the `CalcJob`. :param folder: an `aiida.common.folders.Folder` to temporarily write files on disk :return: `aiida.common.datastructures.CalcInfo` instance
2.374986
2.334998
1.017125
if len(kwpath) == 1: params[kwpath[0]] = value elif kwpath[0] not in params.keys(): new_subsection = {} params[kwpath[0]] = new_subsection self._add_keyword_low(kwpath[1:], value, new_subsection) else: self._add_keyword_low(kwpath[1:], value, params[kwpath[0]])
def _add_keyword_low(self, kwpath, value, params)
Adds keyword
1.885959
1.885017
1.0005
for key, val in sorted(params.items()): if key.upper() != key: raise InputValidationError("keyword '%s' not upper case" % key) if key.startswith('@') or key.startswith('$'): raise InputValidationError("CP2K preprocessor not supported") if isinstance(val, dict): output.append('%s&%s %s' % (' ' * indent, key, val.pop('_', ''))) self._render_section(output, val, indent + 3) output.append('%s&END %s' % (' ' * indent, key)) elif isinstance(val, list): for listitem in val: self._render_section(output, {key: listitem}, indent) elif isinstance(val, bool): val_str = '.true.' if val else '.false.' output.append('%s%s %s' % (' ' * indent, key, val_str)) else: output.append('%s%s %s' % (' ' * indent, key, val))
def _render_section(self, output, params, indent=0)
It takes a dictionary and recurses through. For key-value pair it checks whether the value is a dictionary and prepends the key with & It passes the valued to the same function, increasing the indentation If the value is a list, I assume that this is something the user wants to store repetitively eg: dict['KEY'] = ['val1', 'val2'] ===> KEY val1 KEY val2 or dict['KIND'] = [{'_': 'Ba', 'ELEMENT':'Ba'}, {'_': 'Ti', 'ELEMENT':'Ti'}, {'_': 'O', 'ELEMENT':'O'}] ====> &KIND Ba ELEMENT Ba &END KIND &KIND Ti ELEMENT Ti &END KIND &KIND O ELEMENT O &END KIND
2.576964
2.424704
1.062796
cursor = connections[router.db_for_read(models[0])].cursor() cursor.execute(query, params) rows = cursor.fetchall() for row in rows: row_iter = iter(row) yield [model_class(**dict((a, next(row_iter)) for a in model_to_fields[model_class])) for model_class in models]
def multi_raw(query, params, models, model_to_fields)
Scoop multiple model instances out of the DB at once, given a query that returns all fields of each. Return an iterable of sequences of model instances parallel to the ``models`` sequence of classes. For example:: [(<User such-and-such>, <Watch such-and-such>), ...]
3.063291
3.773238
0.811847
server_relative = ('%s?s=%s' % (reverse('tidings.unsubscribe', args=[self.pk]), self.secret)) return 'https://%s%s' % (Site.objects.get_current().domain, server_relative)
def unsubscribe_url(self)
Return the absolute URL to visit to delete me.
5.624005
4.990369
1.126972
Watch.objects.filter(email=user.email).update(email=None, user=user)
def claim_watches(user)
Attach any anonymous watches having a user's email to that user. Call this from your user registration process if you like.
6.268571
6.116328
1.024891
key = kwargs.pop('key', lambda a: a) reverse = kwargs.pop('reverse', False) min_or_max = max if reverse else min rows = [iter(iterable) for iterable in iterables if iterable] next_values = {} by_key = [] def gather_next_value(row, index): try: next_value = next(row) except StopIteration: pass else: next_values[index] = next_value by_key.append((key(next_value), index)) for index, row in enumerate(rows): gather_next_value(row, index) while by_key: key_value, index = min_or_max(by_key) by_key.remove((key_value, index)) next_value = next_values.pop(index) yield next_value gather_next_value(rows[index], index)
def collate(*iterables, **kwargs)
Return an iterable ordered collation of the already-sorted items from each of ``iterables``, compared by kwarg ``key``. If ``reverse=True`` is passed, iterables must return their results in descending order rather than ascending.
2.319694
2.270504
1.021664
if isinstance(data, string_types): # Return a CRC32 value identical across Python versions and platforms # by stripping the sign bit as on # http://docs.python.org/library/zlib.html. return crc32(data.encode('utf-8')) & 0xffffffff else: return int(data)
def hash_to_unsigned(data)
If ``data`` is a string or unicode string, return an unsigned 4-byte int hash of it. If ``data`` is already an int that fits those parameters, return it verbatim. If ``data`` is an int outside that range, behavior is undefined at the moment. We rely on the ``PositiveIntegerField`` on :class:`~tidings.models.WatchFilter` to scream if the int is too long for the field. We use CRC32 to do the hashing. Though CRC32 is not a good general-purpose hash function, it has no collisions on a dictionary of 38,470 English words, which should be fine for the small sets that :class:`WatchFilters <tidings.models.WatchFilter>` are designed to enumerate. As a bonus, it is fast and available as a built-in function in some DBs. If your set of filter values is very large or has different CRC32 distribution properties than English words, you might want to do your own hashing in your :class:`~tidings.events.Event` subclass and pass ints when specifying filter values.
5.803123
5.783436
1.003404
template = loader.get_template(template_path) context = Context(vars) for u, w in users_and_watches: context['user'] = u # Arbitrary single watch for compatibility with 0.1 # TODO: remove. context['watch'] = w[0] context['watches'] = w yield EmailMessage(subject, template.render(context), from_email, [u.email], **extra_kwargs)
def emails_with_users_and_watches( subject, template_path, vars, users_and_watches, from_email=settings.TIDINGS_FROM_ADDRESS, **extra_kwargs)
Return iterable of EmailMessages with user and watch values substituted. A convenience function for generating emails by repeatedly rendering a Django template with the given ``vars`` plus a ``user`` and ``watches`` key for each pair in ``users_and_watches`` :arg template_path: path to template file :arg vars: a map which becomes the Context passed in to the template :arg extra_kwargs: additional kwargs to pass into EmailMessage constructor
3.456722
3.629393
0.952424
path = getattr(settings, setting_name, None) if path: try: return import_string(path) except ImportError: raise ImproperlyConfigured('%s: No such path.' % path) else: return fallback
def import_from_setting(setting_name, fallback)
Return the resolution of an import path stored in a Django setting. :arg setting_name: The name of the setting holding the import path :arg fallback: An alternate object to use if the setting is empty or doesn't exist Raise ImproperlyConfigured if a path is given that can't be resolved.
3.391834
3.561337
0.952405
from aiida.engine import ExitCode from aiida.common import NotExistent try: out_folder = self.retrieved except NotExistent: return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER self._parse_stdout(out_folder) try: structure = self._parse_trajectory(out_folder) self.out('output_structure', structure) except Exception: # pylint: disable=broad-except pass return ExitCode(0)
def parse(self, **kwargs)
Receives in input a dictionary of retrieved nodes. Does all the logic here.
2.576245
2.556347
1.007784
fname = self.node.load_process_class()._DEFAULT_OUTPUT_FILE # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise OutputParsingError("Cp2k output file not retrieved") result_dict = {'exceeded_walltime': False} abs_fn = os.path.join(out_folder._repository._get_base_folder().abspath, fname) # pylint: disable=protected-access with io.open(abs_fn, mode="r", encoding="utf-8") as fobj: lines = fobj.readlines() for i_line, line in enumerate(lines): if line.startswith(' ENERGY| '): result_dict['energy'] = float(line.split()[8]) result_dict['energy_units'] = "a.u." if 'The number of warnings for this run is' in line: result_dict['nwarnings'] = int(line.split()[-1]) if 'exceeded requested execution time' in line: result_dict['exceeded_walltime'] = True if "KPOINTS| Band Structure Calculation" in line: from aiida.orm import BandsData bnds = BandsData() kpoints, labels, bands = self._parse_bands(lines, i_line) bnds.set_kpoints(kpoints) bnds.labels = labels bnds.set_bands(bands, units='eV') self.out('output_bands', bnds) if 'nwarnings' not in result_dict: raise OutputParsingError("CP2K did not finish properly.") self.out('output_parameters', Dict(dict=result_dict))
def _parse_stdout(self, out_folder)
CP2K output parser
3.358644
3.13741
1.070515
kpoints = [] labels = [] bands_s1 = [] bands_s2 = [] known_kpoints = {} pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL) selected_lines = lines[n_start:] for current_line, line in enumerate(selected_lines): splitted = line.split() if "KPOINTS| Special K-Point" in line: kpoint = tuple(map(float, splitted[-3:])) if " ".join(splitted[-5:-3]) != "not specified": label = splitted[-4] known_kpoints[kpoint] = label elif pattern.match(line): spin = int(splitted[3]) kpoint = tuple(map(float, splitted[-3:])) kpoint_n_lines = int(math.ceil(int(selected_lines[current_line + 1]) / 4.)) band = list( map(float, ' '.join(selected_lines[current_line + 2:current_line + 2 + kpoint_n_lines]).split())) if spin == 1: if kpoint in known_kpoints: labels.append((len(kpoints), known_kpoints[kpoint])) kpoints.append(kpoint) bands_s1.append(band) elif spin == 2: bands_s2.append(band) if bands_s2: bands = [bands_s1, bands_s2] else: bands = bands_s1 return np.array(kpoints), labels, np.array(bands)
def _parse_bands(lines, n_start)
Parse band structure from cp2k output
3.011166
2.942184
1.023446
fname = self.node.load_process_class()._DEFAULT_RESTART_FILE_NAME # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise Exception # not every run type produces a trajectory # read restart file abs_fn = os.path.join(out_folder._repository._get_base_folder().abspath, fname) # pylint: disable=protected-access with io.open(abs_fn, mode="r", encoding="utf-8") as fobj: content = fobj.read() # parse coordinate section match = re.search(r'\n\s*&COORD\n(.*?)\n\s*&END COORD\n', content, DOTALL) coord_lines = [line.strip().split() for line in match.group(1).splitlines()] symbols = [line[0] for line in coord_lines] positions_str = [line[1:] for line in coord_lines] positions = np.array(positions_str, np.float64) # parse cell section match = re.search(r'\n\s*&CELL\n(.*?)\n\s*&END CELL\n', content, re.DOTALL) cell_lines = [line.strip().split() for line in match.group(1).splitlines()] cell_str = [line[1:] for line in cell_lines if line[0] in 'ABC'] cell = np.array(cell_str, np.float64) # create StructureData atoms = ase.Atoms(symbols=symbols, positions=positions, cell=cell) return StructureData(ase=atoms)
def _parse_trajectory(self, out_folder)
CP2K trajectory parser
2.872838
2.754361
1.043014
ext = getattr(settings, 'TIDINGS_TEMPLATE_EXTENSION', 'html') # Grab the watch and secret; complain if either is wrong: try: watch = Watch.objects.get(pk=watch_id) # 's' is for 'secret' but saves wrapping in mails secret = request.GET.get('s') if secret != watch.secret: raise Watch.DoesNotExist except Watch.DoesNotExist: return render(request, 'tidings/unsubscribe_error.' + ext) if request.method == 'POST': watch.delete() return render(request, 'tidings/unsubscribe_success.' + ext) return render(request, 'tidings/unsubscribe.' + ext)
def unsubscribe(request, watch_id)
Unsubscribe from (i.e. delete) the watch of ID ``watch_id``. Expects an ``s`` querystring parameter matching the watch's secret. GET will result in a confirmation page (or a failure page if the secret is wrong). POST will actually delete the watch (again, if the secret is correct). Uses these templates: * tidings/unsubscribe.html - Asks user to confirm deleting a watch * tidings/unsubscribe_error.html - Shown when a watch is not found * tidings/unsubscribe_success.html - Shown when a watch is deleted The shipped templates assume a ``head_title`` and a ``content`` block in a ``base.html`` template. The template extension can be changed from the default ``html`` using the setting :data:`~django.conf.settings.TIDINGS_TEMPLATE_EXTENSION`.
4.128608
3.618794
1.14088
def ensure_user_has_email(user, cluster_email): # Some of these cases shouldn't happen, but we're tolerant. if not getattr(user, 'email', ''): user = EmailUser(cluster_email) return user # TODO: Do this instead with clever SQL that somehow returns just the # best row for each email. cluster_email = '' # email of current cluster favorite_user = None # best user in cluster so far watches = [] # all watches in cluster for u, w in users_and_watches: # w always has at least 1 Watch. All the emails are the same. row_email = u.email or w[0].email if cluster_email.lower() != row_email.lower(): # Starting a new cluster. if cluster_email != '': # Ship the favorites from the previous cluster: yield (ensure_user_has_email(favorite_user, cluster_email), watches) favorite_user, watches = u, [] cluster_email = row_email elif ((not favorite_user.email or not u.is_authenticated) and u.email and u.is_authenticated): favorite_user = u watches.extend(w) if favorite_user is not None: yield ensure_user_has_email(favorite_user, cluster_email), watches
def _unique_by_email(users_and_watches)
Given a sequence of (User/EmailUser, [Watch, ...]) pairs clustered by email address (which is never ''), yield from each cluster a single pair like this:: (User/EmailUser, [Watch, Watch, ...]). The User/Email is that of... (1) the first incoming pair where the User has an email and is not anonymous, or, if there isn't such a user... (2) the first pair. The list of Watches consists of all those found in the cluster. Compares email addresses case-insensitively.
4.833209
4.466372
1.082133
if delay: # Tasks don't receive the `self` arg implicitly. self._fire_task.apply_async( args=(self,), kwargs={'exclude': exclude}, serializer='pickle') else: self._fire_task(self, exclude=exclude)
def fire(self, exclude=None, delay=True)
Notify everyone watching the event. We are explicit about sending notifications; we don't just key off creation signals, because the receiver of a ``post_save`` signal has no idea what just changed, so it doesn't know which notifications to send. Also, we could easily send mail accidentally: for instance, during tests. If we want implicit event firing, we can always register a signal handler that calls :meth:`fire()`. :arg exclude: If a saved user is passed in, that user will not be notified, though anonymous notifications having the same email address may still be sent. A sequence of users may also be passed in. :arg delay: If True (default), the event is handled asynchronously with Celery. This requires the pickle task serializer, which is no longer the default starting in Celery 4.0. If False, the event is processed immediately.
5.760839
5.89357
0.977479
connection = mail.get_connection(fail_silently=True) # Warning: fail_silently swallows errors thrown by the generators, too. connection.open() for m in self._mails(self._users_watching(exclude=exclude)): connection.send_messages([m])
def _fire_task(self, exclude=None)
Build and send the emails as a celery task.
8.716096
7.472419
1.166436
for k in iterkeys(filters): if k not in cls.filters: # Mirror "unexpected keyword argument" message: raise TypeError("%s got an unsupported filter type '%s'" % (cls.__name__, k))
def _validate_filters(cls, filters)
Raise a TypeError if ``filters`` contains any keys inappropriate to this event class.
7.962244
7.452926
1.068338
# If we have trouble distinguishing subsets and such, we could store a # number_of_filters on the Watch. cls._validate_filters(filters) if isinstance(user_or_email, string_types): user_condition = Q(email=user_or_email) elif user_or_email.is_authenticated: user_condition = Q(user=user_or_email) else: return Watch.objects.none() # Filter by stuff in the Watch row: watches = getattr(Watch, 'uncached', Watch.objects).filter( user_condition, Q(content_type=ContentType.objects.get_for_model( cls.content_type)) if cls.content_type else Q(), Q(object_id=object_id) if object_id else Q(), event_type=cls.event_type).extra( where=['(SELECT count(*) FROM tidings_watchfilter WHERE ' 'tidings_watchfilter.watch_id=' 'tidings_watch.id)=%s'], params=[len(filters)]) # Optimization: If the subselect ends up being slow, store the number # of filters in each Watch row or try a GROUP BY. # Apply 1-to-many filters: for k, v in iteritems(filters): watches = watches.filter(filters__name=k, filters__value=hash_to_unsigned(v)) return watches
def _watches_belonging_to_user(cls, user_or_email, object_id=None, **filters)
Return a QuerySet of watches having the given user or email, having (only) the given filters, and having the event_type and content_type attrs of the class. Matched Watches may be either confirmed and unconfirmed. They may include duplicates if the get-then-create race condition in :meth:`notify()` allowed them to be created. If you pass an email, it will be matched against only the email addresses of anonymous watches. At the moment, the only integration point planned between anonymous and registered watches is the claiming of anonymous watches of the same email address on user registration confirmation. If you pass the AnonymousUser, this will return an empty QuerySet.
4.765862
4.884731
0.975665
return cls._watches_belonging_to_user(user_or_email_, object_id=object_id, **filters).exists()
def is_notifying(cls, user_or_email_, object_id=None, **filters)
Return whether the user/email is watching this event (either active or inactive watches), conditional on meeting the criteria in ``filters``. Count only watches that match the given filters exactly--not ones which match merely a superset of them. This lets callers distinguish between watches which overlap in scope. Equivalently, this lets callers check whether :meth:`notify()` has been called with these arguments. Implementations in subclasses may take different arguments--for example, to assume certain filters--though most will probably just use this. However, subclasses should clearly document what filters they supports and the meaning of each. Passing this an ``AnonymousUser`` always returns ``False``. This means you can always pass it ``request.user`` in a view and get a sensible response.
5.046373
4.788548
1.053842
# A test-for-existence-then-create race condition exists here, but it # doesn't matter: de-duplication on fire() and deletion of all matches # on stop_notifying() nullify its effects. try: # Pick 1 if >1 are returned: watch = cls._watches_belonging_to_user( user_or_email_, object_id=object_id, **filters)[0:1].get() except Watch.DoesNotExist: create_kwargs = {} if cls.content_type: create_kwargs['content_type'] = \ ContentType.objects.get_for_model(cls.content_type) create_kwargs['email' if isinstance(user_or_email_, string_types) else 'user'] = user_or_email_ # Letters that can't be mistaken for other letters or numbers in # most fonts, in case people try to type these: distinguishable_letters = \ 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ' secret = ''.join(random.choice(distinguishable_letters) for x in range(10)) # Registered users don't need to confirm, but anonymous users do. is_active = ('user' in create_kwargs or not settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES) if object_id: create_kwargs['object_id'] = object_id watch = Watch.objects.create( secret=secret, is_active=is_active, event_type=cls.event_type, **create_kwargs) for k, v in iteritems(filters): WatchFilter.objects.create(watch=watch, name=k, value=hash_to_unsigned(v)) # Send email for inactive watches. if not watch.is_active: email = watch.user.email if watch.user else watch.email message = cls._activation_email(watch, email) try: message.send() except SMTPException as e: watch.delete() raise ActivationRequestFailed(e.recipients) return watch
def notify(cls, user_or_email_, object_id=None, **filters)
Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()` on it if you're so inclined. Implementations in subclasses may take different arguments; see the docstring of :meth:`is_notifying()`. Send an activation email if an anonymous watch is created and :data:`~django.conf.settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES` is ``True``. If the activation request fails, raise a ActivationRequestFailed exception. Calling :meth:`notify()` twice for an anonymous user will send the email each time.
4.999435
4.371515
1.143639
return super(InstanceEvent, cls).notify(user_or_email, object_id=instance.pk)
def notify(cls, user_or_email, instance)
Create, save, and return a watch which fires when something happens to ``instance``.
6.448715
6.641132
0.971027
super(InstanceEvent, cls).stop_notifying(user_or_email, object_id=instance.pk)
def stop_notifying(cls, user_or_email, instance)
Delete the watch created by notify.
5.999866
5.429719
1.105005
return super(InstanceEvent, cls).is_notifying(user_or_email, object_id=instance.pk)
def is_notifying(cls, user_or_email, instance)
Check if the watch created by notify exists.
5.810083
5.094923
1.140367
return self._users_watching_by_filter(object_id=self.instance.pk, **kwargs)
def _users_watching(self, **kwargs)
Return users watching this instance.
8.32948
7.074586
1.177381
if not self._crypter: return b'' try: plaintext = self._crypter.decrypt(self._ciphertext, **self._decrypt_params) return plaintext except Exception as e: exc_info = sys.exc_info() six.reraise( ValueError('Invalid ciphertext "%s", error: %s' % (self._ciphertext, e)), None, exc_info[2] )
def decrypt(self)
Decrypt decrypts the secret and returns the plaintext. Calling decrypt() may incur side effects such as a call to a remote service for decryption.
3.432196
3.421018
1.003267
if not iv: raise ValueError('Missing Nonce') return self.key.encrypt(iv, msg, auth_data)
def encrypt(self, msg, iv='', auth_data=None)
Encrypts and authenticates the data provided as well as authenticating the associated_data. :param msg: The message to be encrypted :param iv: MUST be present, at least 96-bit long :param auth_data: Associated data :return: The cipher text bytes with the 16 byte tag appended.
7.998465
9.712939
0.823485
if not iv: raise ValueError('Missing Nonce') return self.key.decrypt(iv, cipher_text+tag, auth_data)
def decrypt(self, cipher_text, iv='', auth_data=None, tag=b'')
Decrypts the data and authenticates the associated_data (if provided). :param cipher_text: The data to decrypt including tag :param iv: Initialization Vector :param auth_data: Associated data :param tag: Authentication tag :return: The original plaintext
7.074733
9.0806
0.779104
iv = self._generate_iv(enc_alg, iv) if enc_alg in ["A192GCM", "A128GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) ctx, tag = split_ctx_and_tag(aes.encrypt(msg, iv, auth_data)) elif enc_alg in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: aes = AES_CBCEncrypter(key=key) ctx, tag = aes.encrypt(msg, iv, auth_data) else: raise NotSupportedAlgorithm(enc_alg) return ctx, tag, aes.key
def enc_setup(self, enc_alg, msg, auth_data=b'', key=None, iv="")
Encrypt JWE content. :param enc_alg: The JWE "enc" value specifying the encryption algorithm :param msg: The plain text message :param auth_data: Additional authenticated data :param key: Key (CEK) :return: Tuple (ciphertext, tag), both as bytes
2.367037
2.413227
0.98086
if enc in ["A128GCM", "A192GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) elif enc in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: aes = AES_CBCEncrypter(key=key) else: raise Exception("Unsupported encryption algorithm %s" % enc) try: return aes.decrypt(ctxt, iv=iv, auth_data=auth_data, tag=tag) except DecryptionFailed: raise
def _decrypt(enc, key, ctxt, iv, tag, auth_data=b'')
Decrypt JWE content. :param enc: The JWE "enc" value specifying the encryption algorithm :param key: Key (CEK) :param iv : Initialization vector :param auth_data: Additional authenticated data (AAD) :param ctxt : Ciphertext :param tag: Authentication tag :return: plain text message or None if decryption failed
1.920214
1.912379
1.004097
hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend()) hasher.update(msg) digest = hasher.finalize() sig = key.sign( digest, padding.PSS( mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH), utils.Prehashed(self.hash_algorithm())) return sig
def sign(self, msg, key)
Create a signature over a message :param msg: The message :param key: The key :return: A signature
1.760473
2.043518
0.861491
try: key.verify(signature, msg, padding.PSS(mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH), self.hash_algorithm()) except InvalidSignature as err: raise BadSignature(err) else: return True
def verify(self, msg, signature, key)
Verify a message signature :param msg: The message :param sig: A signature :param key: A ec.EllipticCurvePublicKey to use for the verification. :raises: BadSignature if the signature can't be verified. :return: True
2.485387
2.630635
0.944786
_msg = as_bytes(self.msg) _args = self._dict try: _args["kid"] = kwargs["kid"] except KeyError: pass jwe = JWEnc(**_args) # If no iv and cek are given generate them iv = self._generate_iv(self["enc"], iv) cek = self._generate_key(self["enc"], cek) if isinstance(key, SYMKey): try: kek = key.key.encode('utf8') except AttributeError: kek = key.key elif isinstance(key, bytes): kek = key else: kek = intarr2str(key) # The iv for this function must be 64 bit # Which is certainly different from the one above jek = aes_key_wrap(kek, cek, default_backend()) _enc = self["enc"] _auth_data = jwe.b64_encode_header() ctxt, tag, cek = self.enc_setup(_enc, _msg, auth_data=_auth_data, key=cek, iv=iv) return jwe.pack(parts=[jek, iv, ctxt, tag])
def encrypt(self, key, iv="", cek="", **kwargs)
Produces a JWE as defined in RFC7516 using symmetric keys :param key: Shared symmetric key :param iv: Initialization vector :param cek: Content master key :param kwargs: Extra keyword arguments, just ignore for now. :return:
6.126093
6.250346
0.980121
ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) return ecpn.public_key(default_backend())
def ec_construct_public(num)
Given a set of values on public attributes build a elliptic curve public key instance. :param num: A dictionary with public attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey instance.
7.495883
7.448659
1.00634
pub_ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) priv_ecpn = ec.EllipticCurvePrivateNumbers(num['d'], pub_ecpn) return priv_ecpn.private_key(default_backend())
def ec_construct_private(num)
Given a set of values on public and private attributes build a elliptic curve private key instance. :param num: A dictionary with public and private attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance.
4.944014
5.015231
0.9858
with open(filename, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=passphrase, backend=default_backend()) return private_key
def import_private_key_from_file(filename, passphrase=None)
Read a private Elliptic Curve 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.ec.EllipticCurvePrivateKey instance
1.73572
2.283231
0.760203
if isinstance(self.x, (str, bytes)): _x = deser(self.x) else: raise ValueError('"x" MUST be a string') if isinstance(self.y, (str, bytes)): _y = deser(self.y) else: raise ValueError('"y" MUST be a string') if self.d: try: if isinstance(self.d, (str, bytes)): _d = deser(self.d) self.priv_key = ec_construct_private( {'x': _x, 'y': _y, 'crv': self.crv, 'd': _d}) self.pub_key = self.priv_key.public_key() except ValueError as err: raise DeSerializationNotPossible(str(err)) else: self.pub_key = ec_construct_public( {'x': _x, 'y': _y, 'crv': self.crv})
def deserialize(self)
Starting with information gathered from the on-the-wire representation of an elliptic curve key (a JWK) initiate an cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey or EllipticCurvePrivateKey instance. So we have to get from having:: { "kty":"EC", "crv":"P-256", "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", "d":"870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE" } to having a key that can be used for signing/verifying and/or encrypting/decrypting. If 'd' has value then we're dealing with a private key otherwise a public key. 'x' and 'y' MUST have values. If self.pub_key or self.priv_key has a value beforehand this will be overwrite. x, y and d (if present) must be strings or bytes.
2.669589
2.051059
1.301566
if self.priv_key: self._serialize(self.priv_key) else: self._serialize(self.pub_key) res = self.common() res.update({ "crv": self.crv, "x": self.x, "y": self.y }) if private and self.d: res["d"] = self.d return res
def serialize(self, private=False)
Go from a cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey or EllipticCurvePublicKey instance to a JWK representation. :param private: Whether we should include the private attributes or not. :return: A JWK as a dictionary
3.118153
3.152856
0.988993
self._serialize(key) if isinstance(key, ec.EllipticCurvePrivateKey): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
def load_key(self, key)
Load an Elliptic curve key :param key: An elliptic curve key instance, private or public. :return: Reference to this instance
3.484919
3.212251
1.084884
try: size = spec['size'] except KeyError: size = 2048 kb = KeyBundle(keytype="RSA") if 'use' in spec: for use in harmonize_usage(spec["use"]): _key = new_rsa_key(use=use, key_size=size) kb.append(_key) else: _key = new_rsa_key(key_size=size) kb.append(_key) return kb
def rsa_init(spec)
Initiates a :py:class:`oidcmsg.keybundle.KeyBundle` instance containing newly minted RSA keys according to a spec. Example of specification:: {'size':2048, 'use': ['enc', 'sig'] } Using the spec above 2 RSA keys would be minted, one for encryption and one for signing. :param spec: :return: KeyBundle
3.580727
2.863155
1.250623
kb = KeyBundle(keytype="EC") if 'use' in spec: for use in spec["use"]: eck = new_ec_key(crv=spec['crv'], use=use) kb.append(eck) else: eck = new_ec_key(crv=spec['crv']) kb.append(eck) return kb
def ec_init(spec)
Initiate a key bundle with an elliptic curve key. :param spec: Key specifics of the form:: {"type": "EC", "crv": "P-256", "use": ["sig"]} :return: A KeyBundle instance
3.856128
2.983623
1.292431
usage = harmonize_usage(usage) if typ.lower() == "jwks": kb = KeyBundle(source=filename, fileformat="jwks", keyusage=usage) elif typ.lower() == 'der': kb = KeyBundle(source=filename, fileformat="der", keyusage=usage) else: raise UnknownKeyType("Unsupported key type") return kb
def keybundle_from_local_file(filename, typ, usage)
Create a KeyBundle based on the content in a local file :param filename: Name of the file :param typ: Type of content :param usage: What the key should be used for :return: The created KeyBundle
3.779077
4.448425
0.849531
keys = [] for kb in kbl: keys.extend([k.serialize(private) for k in kb.keys() if k.kty != 'oct' and not k.inactive_since]) res = {"keys": keys} try: f = open(target, 'w') except IOError: (head, tail) = os.path.split(target) os.makedirs(head) f = open(target, 'w') _txt = json.dumps(res) f.write(_txt) f.close()
def dump_jwks(kbl, target, private=False)
Write a JWK to a file. Will ignore symmetric keys !! :param kbl: List of KeyBundles :param target: Name of the file to which everything should be written :param private: Should also the private parts be exported
3.208036
3.204661
1.001053
kid = 0 tot_kb = KeyBundle() for spec in key_conf: typ = spec["type"].upper() if typ == "RSA": if "key" in spec: error_to_catch = (OSError, IOError, DeSerializationNotPossible) try: kb = KeyBundle(source="file://%s" % spec["key"], fileformat="der", keytype=typ, keyusage=spec["use"]) except error_to_catch: kb = rsa_init(spec) except Exception: raise else: kb = rsa_init(spec) elif typ == "EC": kb = ec_init(spec) else: continue if 'kid' in spec and len(kb) == 1: ks = kb.keys() ks[0].kid = spec['kid'] else: for k in kb.keys(): if kid_template: k.kid = kid_template % kid kid += 1 else: k.add_kid() tot_kb.extend(kb.keys()) return tot_kb
def build_key_bundle(key_conf, kid_template="")
Builds a :py:class:`oidcmsg.key_bundle.KeyBundle` instance based on a key specification. An example of such a specification:: keys = [ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"], "kid": "ec.1"}, {"type": "EC", "crv": "P-256", "use": ["enc"], "kid": "ec.2"} ] Keys in this specification are: type The type of key. Presently only 'rsa' and 'ec' supported. key A name of a file where a key can be found. Only works with PEM encoded RSA keys use What the key should be used for crv The elliptic curve that should be used. Only applies to elliptic curve keys :-) kid Key ID, can only be used with one usage type is specified. If there are more the one usage type specified 'kid' will just be ignored. :param key_conf: The key configuration :param kid_template: A template by which to build the key IDs. If no kid_template is given then the built-in function add_kid() will be used. :return: A KeyBundle instance
3.740525
3.584463
1.043538
_l = _cmp(kd1['type'], kd2['type']) if _l: return _l if kd1['type'] == 'EC': _l = _cmp(kd1['crv'], kd2['crv']) if _l: return _l _l = _cmp(kd1['type'], kd2['type']) if _l: return _l _l = _cmp(kd1['use'][0], kd2['use'][0]) if _l: return _l try: _kid1 = kd1['kid'] except KeyError: _kid1 = None try: _kid2 = kd2['kid'] except KeyError: _kid2 = None if _kid1 and _kid2: return _cmp(_kid1, _kid2) elif _kid1: return -1 elif _kid2: return 1 return 0
def sort_func(kd1, kd2)
Compares 2 key descriptions :param kd1: First key description :param kd2: Second key description :return: -1,0,1 depending on whether kd1 le,eq or gt then kd2
1.816988
1.854367
0.979843
_int = [] # First make sure all defs only reference one usage for kd in key_def: if len(kd['use']) > 1: for _use in kd['use']: _kd = kd.copy() _kd['use'] = _use _int.append(_kd) else: _int.append(kd) _int.sort(key=cmp_to_key(sort_func)) return _int
def order_key_defs(key_def)
Sort a set of key definitions. A key definition that defines more then one usage type are splitted into as many definitions as the number of usage types specified. One key definition per usage type. :param key_def: A set of key definitions :return: The set of definitions as a sorted list
4.269741
3.932526
1.08575
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)
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
3.35395
3.255303
1.030304
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)
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
3.17608
3.036461
1.045981
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)
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:
4.619861
4.561673
1.012756
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)
Go from JWK description to binary keys :param keys: :return:
4.547682
4.109363
1.106663
_info = json.loads(open(filename).read()) if 'keys' in _info: self.do_keys(_info["keys"]) else: self.do_keys([_info]) self.last_updated = time.time()
def do_local_jwk(self, filename)
Load a JWKS from a local file :param filename:
3.688111
4.152516
0.888163
_bkey = import_private_rsa_key_from_file(filename) if keytype.lower() != 'rsa': raise NotImplemented('No support for DER decoding of that key type') if not keyusage: keyusage = ["enc", "sig"] else: keyusage = harmonize_usage(keyusage) for use in keyusage: _key = RSAKey().load_key(_bkey) _key.use = use if kid: _key.kid = kid self._keys.append(_key) self.last_updated = time.time()
def do_local_der(self, filename, keytype, keyusage=None, kid='')
Load a DER encoded file amd create a key from it. :param filename: :param keytype: Presently only 'rsa' supported :param keyusage: encryption ('enc') or signing ('sig') or both
4.272693
4.669602
0.915001
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)
Load a JWKS from a webpage :return: True or False if load was successful
3.652983
3.339961
1.09372
# 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)
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
4.119063
3.693604
1.115188
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)
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.
5.295059
4.599444
1.151239
self._uptodate() _typs = [typ.lower(), typ.upper()] if typ: _keys = [k for k in self._keys if k.kty in _typs] else: _keys = self._keys if only_active: return [k for k in _keys if not k.inactive_since] else: return _keys
def get(self, typ="", only_active=True)
Return a list of keys. Either all keys or only keys of a specific type :param typ: Type of key (rsa, ec, oct, ..) :return: If typ is undefined all the keys as a dictionary otherwise the appropriate keys in a list
3.776907
3.583304
1.054029
_typs = [typ.lower(), typ.upper()] self._keys = [k for k in self._keys if not k.kty in _typs]
def remove_keys_by_type(self, typ)
Remove keys that are of a specific type. :param typ: Type of key (rsa, ec, oct, ..)
5.081658
5.699463
0.891603
self._uptodate() keys = list() for k in self._keys: if private: key = k.serialize(private) else: key = k.serialize() for k, v in key.items(): key[k] = as_unicode(v) keys.append(key) return json.dumps({"keys": keys})
def jwks(self, private=False)
Create a JWKS as a JSON document :param private: Whether private key information should be included. :return: A JWKS JSON representation of the keys in this bundle
3.76744
3.470186
1.085659
for key in self._keys: if key.kid == kid: return key # Try updating since there might have been an update to the key file self.update() for key in self._keys: if key.kid == kid: return key return None
def get_key_with_kid(self, kid)
Return the key that has a specific key ID (kid) :param kid: The Key ID :return: The key or None
3.665838
3.759259
0.975149
self._uptodate() return [key.kid for key in self._keys if key.kid != ""]
def kids(self)
Return a list of key IDs. Note that this list may be shorter then the list of keys. The reason might be that there are some keys with no key ID. :return: A list of all the key IDs that exists in this bundle
11.280932
9.92121
1.137052
k = self.get_key_with_kid(kid) k.inactive_since = time.time()
def mark_as_inactive(self, kid)
Mark a specific key as inactive based on the keys KeyID :param kid: The Key Identifier
6.081429
6.483853
0.937934
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)
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
3.555563
3.512596
1.012232
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)
Make deep copy of this KeyBundle :return: The copy
4.312537
4.174925
1.032962
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)
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.
3.973441
3.739454
1.062572
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)
Packs components into a JWT :param parts: List of parts to pack :param headers: The JWT headers :return:
4.244497
4.075251
1.04153
_msg = as_unicode(self.part[1]) # If not JSON web token assume JSON if "cty" in self.headers and self.headers["cty"].lower() != "jwt": pass else: try: _msg = json.loads(_msg) except ValueError: pass return _msg
def payload(self)
Picks out the payload from the different parts of the signed/encrypted JSON Web Token. If the content type is said to be 'jwt' deserialize the payload into a Python object otherwise return as-is. :return: The payload
6.95435
5.446902
1.276753
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)
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
2.356021
2.127734
1.107291
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)
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.
2.821946
2.994569
0.942355
h = hmac.HMAC(key, self.algorithm(), default_backend()) h.update(msg) return h.finalize()
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
3.624155
4.986012
0.726864
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)
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.
3.039654
3.0439
0.998605
parser = argparse.ArgumentParser(description='JSON Web Key (JWK) Generator') parser.add_argument('--kty', dest='kty', metavar='type', help='Key type', required=True) parser.add_argument('--size', dest='keysize', type=int, metavar='size', help='Key size') parser.add_argument('--crv', dest='crv', metavar='curve', help='EC curve', choices=NIST2SEC.keys(), default=DEFAULT_EC_CURVE) parser.add_argument('--exp', dest='rsa_exp', type=int, metavar='exponent', help=f'RSA public key exponent (default {DEFAULT_RSA_EXP})', default=DEFAULT_RSA_EXP) parser.add_argument('--kid', dest='kid', metavar='id', help='Key ID') args = parser.parse_args() if args.kty.upper() == 'RSA': if args.keysize is None: args.keysize = DEFAULT_RSA_KEYSIZE jwk = new_rsa_key(public_exponent=args.rsa_exp, key_size=args.keysize, kid=args.kid) elif args.kty.upper() == 'EC': if args.crv not in NIST2SEC: print("Unknown curve: {0}".format(args.crv), file=sys.stderr) exit(1) jwk = new_ec_key(crv=args.crv, kid=args.kid) elif args.kty.upper() == 'SYM': if args.keysize is None: args.keysize = DEFAULT_SYM_KEYSIZE randomkey = os.urandom(args.keysize) jwk = SYMKey(key=randomkey, kid=args.kid) else: print(f"Unknown key type: {args.kty}", file=sys.stderr) exit(1) jwk_dict = jwk.serialize(private=True) print(json.dumps(jwk_dict, sort_keys=True, indent=4)) print("SHA-256: " + jwk.thumbprint('SHA-256').decode(), file=sys.stderr)
def main()
Main function
1.901134
1.902822
0.999113
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)
Ensure all required EC parameters are present in dictionary
4.289735
4.100015
1.046273
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)
Ensure all required RSA parameters are present in dictionary
4.474551
4.195601
1.066486
if not required <= provided: missing = required - provided raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(missing))))
def ensure_params(kty, provided, required)
Ensure all required parameters are present in dictionary
8.07702
7.602066
1.062477
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="")
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
2.358998
2.5124
0.938942
if keyjar is None: keyjar = KeyJar() tot_kb = build_key_bundle(key_conf, kid_template) keyjar.add_kb(owner, tot_kb) return keyjar
def build_keyjar(key_conf, kid_template="", keyjar=None, owner='')
Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to an existing KeyJar based on a key specification. An example of such a specification:: keys = [ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"], "kid": "ec.1"}, {"type": "EC", "crv": "P-256", "use": ["enc"], "kid": "ec.2"} ] Keys in this specification are: type The type of key. Presently only 'rsa' and 'ec' supported. key A name of a file where a key can be found. Only works with PEM encoded RSA keys use What the key should be used for crv The elliptic curve that should be used. Only applies to elliptic curve keys :-) kid Key ID, can only be used with one usage type is specified. If there are more the one usage type specified 'kid' will just be ignored. :param key_conf: The key configuration :param kid_template: A template by which to build the key IDs. If no kid_template is given then the built-in function add_kid() will be used. :param keyjar: If an KeyJar instance the new keys are added to this key jar. :param owner: The default owner of the keys in the key jar. :return: A KeyJar instance
3.471442
4.560318
0.761228
for iss, kbl in keyjar.items(): for kb in kbl: kb.update()
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
9.122293
12.39145
0.736176
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)
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
2.980742
2.90664
1.025494
if not url: raise KeyError("No url given") if "/localhost:" in url or "/localhost/" in url: kb = self.keybundle_cls(source=url, verify_ssl=False, httpc=self.httpc, **kwargs) else: kb = self.keybundle_cls(source=url, verify_ssl=self.verify_ssl, httpc=self.httpc, **kwargs) kb.update() self.add_kb(issuer, kb) return kb
def add_url(self, issuer, url, **kwargs)
Add a set of keys by url. This method will create a :py:class:`oidcmsg.key_bundle.KeyBundle` instance with the url as source specification. If no file format is given it's assumed that what's on the other side is a JWKS. :param issuer: Who issued the keys :param url: Where can the key/-s be found :param kwargs: extra parameters for instantiating KeyBundle :return: A :py:class:`oidcmsg.oauth2.keybundle.KeyBundle` instance
3.866093
2.992986
1.291718
if issuer not in self.issuer_keys: self.issuer_keys[issuer] = [] if usage is None: self.issuer_keys[issuer].append( self.keybundle_cls([{"kty": "oct", "key": key}])) else: for use in usage: self.issuer_keys[issuer].append( self.keybundle_cls([{"kty": "oct", "key": key, "use": use}]))
def add_symmetric(self, issuer, key, usage=None)
Add a symmetric key. This is done by wrapping it in a key bundle cloak since KeyJar does not handle keys directly but only through key bundles. :param issuer: Owner of the key :param key: The key :param usage: What the key can be used for signing/signature verification (sig) and/or encryption/decryption (enc)
2.445776
2.409992
1.014848
try: self.issuer_keys[issuer].append(kb) except KeyError: self.issuer_keys[issuer] = [kb]
def add_kb(self, issuer, kb)
Add a key bundle and bind it to an identifier :param issuer: Owner of the keys in the key bundle :param kb: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance
2.678459
2.755965
0.971877
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)
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
3.071672
2.938896
1.045179
return self.get("sig", key_type, owner, kid, **kwargs)
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
6.502878
9.433654
0.689328
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)
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
4.700485
6.713624
0.700141
res = [] for kbl in self.issuer_keys[issuer]: res.extend(kbl.keys()) return res
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
5.433113
6.759787
0.80374
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)
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
9.267327
8.152917
1.136689
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)
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
3.722389
3.975529
0.936326
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)
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
4.497743
3.828118
1.174923
keys = [] for kb in self.issuer_keys[issuer]: keys.extend([k.serialize(private) for k in kb.keys() if k.inactive_since == 0]) return {"keys": keys}
def export_jwks(self, private=False, issuer="")
Produces a dictionary that later can be easily mapped into a JSON string representing a JWKS. :param private: Whether it should be the private keys or the public :param issuer: The entity ID. :return: A dictionary with one key: 'keys'
6.606859
7.568307
0.872964
return json.dumps(self.export_jwks(private, issuer))
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
4.544883
6.689253
0.679431
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)
Imports all the keys that are represented in a JWKS :param jwks: Dictionary representation of a JWKS :param issuer: Who 'owns' the JWKS
3.033484
3.201476
0.947527
return self.import_jwks(json.loads(jwks), issuer)
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
4.050263
6.583095
0.615252
for iss in list(self.owners()): _kbl = [] for kb in self.issuer_keys[iss]: kb.remove_outdated(self.remove_after, when=when) if len(kb): _kbl.append(kb) if _kbl: self.issuer_keys[iss] = _kbl else: del self.issuer_keys[iss]
def remove_outdated(self, when=0)
Goes through the complete list of issuers and for each of them removes outdated keys. Outdated keys are keys that has been marked as inactive at a time that is longer ago then some set number of seconds (when). If when=0 the the base time is set to now. The number of seconds a carried in the remove_after parameter in the key jar. :param when: To facilitate testing
4.452516
4.402082
1.011457
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)
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
3.840777
3.613256
1.062969
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)
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
4.153517
3.978692
1.04394
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)
Make deep copy of this key jar. :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
6.476182
5.252692
1.232926
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='')
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
2.284404
2.345074
0.974129
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)
Gather initial information for the payload. :return: A dictionary with claims and values
5.393167
5.59275
0.964314