Example #1
0
    def primitive(self, primitive_class: Type[P]) -> P:
        """Returns a wrapped primitive from this KeysetHandle.

    Uses the KeyManager and the PrimitiveWrapper objects in the global
    registry.Registry
    to create the primitive. This function is the most common way of creating a
    primitive.

    Args:
      primitive_class: The class of the primitive.

    Returns:
      The primitive.
    Raises:
      tink.TinkError if creation of the primitive fails, for example if
      primitive_class cannot be used with this KeysetHandle.
    """
        _validate_keyset(self._keyset)
        pset = primitive_set.PrimitiveSet(primitive_class)
        for key in self._keyset.key:
            if key.status == tink_pb2.ENABLED:
                primitive = registry.Registry.primitive(
                    key.key_data, primitive_class)
                entry = pset.add_primitive(primitive, key)
                if key.key_id == self._keyset.primary_key_id:
                    pset.set_primary(entry)
        return registry.Registry.wrap(pset)
Example #2
0
    def register_primitive_wrapper(
            cls, wrapper: primitive_wrapper.PrimitiveWrapper) -> None:
        """Tries to register a PrimitiveWrapper.

    Args:
      wrapper: A PrimitiveWrapper object.
    Raises:
      Error if a different wrapper has already been registered for the same
      Primitive.
    """
        if (wrapper.primitive_class() in cls._wrappers and type(
                cls._wrappers[wrapper.primitive_class()]) != type(wrapper)):  # pylint: disable=unidiomatic-typecheck
            raise tink_error.TinkError(
                'A wrapper for primitive {} has already been added.'.format(
                    wrapper.primitive_class().__name__))
        wrapped = wrapper.wrap(
            pset_module.PrimitiveSet(wrapper.primitive_class()))
        if not isinstance(wrapped, wrapper.primitive_class()):
            raise tink_error.TinkError(
                'Wrapper for primitive {} generates incompatible primitive of type {}'
                .format(wrapper.primitive_class().__name__,
                        type(wrapped).__name__))
        cls._wrappers[wrapper.primitive_class()] = wrapper