signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _encryption_key(self, initial_material, key_info):<EOL>
return self._derive_delegated_key(initial_material, key_info, HkdfInfo.ENCRYPTION)<EOL>
Calculate an encryption key from ``initial_material`` using the requested key info. :param bytes initial_material: Initial material to use with KDF :param KeyInfo key_info: Key information to use to calculate encryption key :returns: Delegated key to use for encryption and decryption :rtype: JceNameLocalDelegatedKey
f5627:c3:m12
def _mac_key(self, initial_material, key_info):<EOL>
return self._derive_delegated_key(initial_material, key_info, HkdfInfo.SIGNING)<EOL>
Calculate an HMAC key from ``initial_material`` using the requested key info. :param bytes initial_material: Initial material to use with KDF :param KeyInfo key_info: Key information to use to calculate HMAC key :returns: Delegated key to use for signature calculation and verification :rtype: JceNameLocalDelegatedKey
f5627:c3:m13
def decryption_materials(self, encryption_context):<EOL>
decryption_material_description = encryption_context.material_description.copy()<EOL>initial_material = self._decrypt_initial_material(encryption_context)<EOL>signing_key_info = KeyInfo.from_material_description(<EOL>material_description=encryption_context.material_description,<EOL>description_key=MaterialDescriptionKeys.ITEM_SIGNATURE_ALGORITHM.value,<EOL>default_algorithm=_DEFAULT_SIGNING_ALGORITHM,<EOL>default_key_length=_DEFAULT_SIGNING_KEY_LENGTH,<EOL>)<EOL>decryption_key_info = KeyInfo.from_material_description(<EOL>material_description=encryption_context.material_description,<EOL>description_key=MaterialDescriptionKeys.CONTENT_ENCRYPTION_ALGORITHM.value,<EOL>default_algorithm=_DEFAULT_CONTENT_ENCRYPTION_ALGORITHM,<EOL>default_key_length=_DEFAULT_CONTENT_KEY_LENGTH,<EOL>)<EOL>return RawDecryptionMaterials(<EOL>verification_key=self._mac_key(initial_material, signing_key_info),<EOL>decryption_key=self._encryption_key(initial_material, decryption_key_info),<EOL>material_description=decryption_material_description,<EOL>)<EOL>
Provide decryption materials. :param EncryptionContext encryption_context: Encryption context for request :returns: Encryption materials :rtype: RawDecryptionMaterials
f5627:c3:m14
def encryption_materials(self, encryption_context):<EOL>
initial_material, encrypted_initial_material = self._generate_initial_material(encryption_context)<EOL>encryption_material_description = encryption_context.material_description.copy()<EOL>encryption_material_description.update(<EOL>{<EOL>_COVERED_ATTR_CTX_KEY: _KEY_COVERAGE,<EOL>MaterialDescriptionKeys.CONTENT_KEY_WRAPPING_ALGORITHM.value: "<STR_LIT>",<EOL>MaterialDescriptionKeys.CONTENT_ENCRYPTION_ALGORITHM.value: self._content_key_info.description,<EOL>MaterialDescriptionKeys.ITEM_SIGNATURE_ALGORITHM.value: self._signing_key_info.description,<EOL>MaterialDescriptionKeys.WRAPPED_DATA_KEY.value: to_str(base64.b64encode(encrypted_initial_material)),<EOL>}<EOL>)<EOL>return RawEncryptionMaterials(<EOL>signing_key=self._mac_key(initial_material, self._signing_key_info),<EOL>encryption_key=self._encryption_key(initial_material, self._content_key_info),<EOL>material_description=encryption_material_description,<EOL>)<EOL>
Provide encryption materials. :param EncryptionContext encryption_context: Encryption context for request :returns: Encryption materials :rtype: RawEncryptionMaterials
f5627:c3:m15
def decryption_materials(self, encryption_context):<EOL>
raise AttributeError("<STR_LIT>")<EOL>
Return decryption materials. :param EncryptionContext encryption_context: Encryption context for request :raises AttributeError: if no decryption materials are available
f5628:c0:m0
def encryption_materials(self, encryption_context):<EOL>
raise AttributeError("<STR_LIT>")<EOL>
Return encryption materials. :param EncryptionContext encryption_context: Encryption context for request :raises AttributeError: if no encryption materials are available
f5628:c0:m1
def refresh(self):<EOL>
Ask this instance to refresh the cryptographic materials. .. note:: Default behavior is to do nothing.
f5628:c0:m2
def decryption_materials(self, encryption_context):<EOL>
if self._decryption_materials is None:<EOL><INDENT>return super(StaticCryptographicMaterialsProvider, self).decryption_materials(encryption_context)<EOL><DEDENT>return self._decryption_materials<EOL>
Return the static decryption materials. :param EncryptionContext encryption_context: Encryption context for request (not used by :class:`StaticCryptographicMaterialsProvider`) :raises AttributeError: if no decryption materials are available
f5629:c0:m1
def encryption_materials(self, encryption_context):<EOL>
if self._encryption_materials is None:<EOL><INDENT>return super(StaticCryptographicMaterialsProvider, self).encryption_materials(encryption_context)<EOL><DEDENT>return self._encryption_materials<EOL>
Return the static encryption materials. :param EncryptionContext encryption_context: Encryption context for request (not used by :class:`StaticCryptographicMaterialsProvider`) :raises AttributeError: if no encryption materials are available
f5629:c0:m2
def __attrs_post_init__(self):<EOL>
self._encrypted_table = EncryptedTable( <EOL>table=self._table, materials_provider=self._materials_provider<EOL>)<EOL>
Prepare the encrypted table resource from the provided table and materials provider.
f5630:c2:m1
@classmethod<EOL><INDENT>def create_table(cls, client, table_name, read_units, write_units):<EOL><DEDENT>
_LOGGER.debug("<STR_LIT>")<EOL>try:<EOL><INDENT>client.create_table(<EOL>TableName=table_name,<EOL>AttributeDefinitions=[<EOL>{"<STR_LIT>": MetaStoreAttributeNames.PARTITION.value, "<STR_LIT>": "<STR_LIT:S>"},<EOL>{"<STR_LIT>": MetaStoreAttributeNames.SORT.value, "<STR_LIT>": "<STR_LIT:N>"},<EOL>],<EOL>KeySchema=[<EOL>{"<STR_LIT>": MetaStoreAttributeNames.PARTITION.value, "<STR_LIT>": "<STR_LIT>"},<EOL>{"<STR_LIT>": MetaStoreAttributeNames.SORT.value, "<STR_LIT>": "<STR_LIT>"},<EOL>],<EOL>ProvisionedThroughput={"<STR_LIT>": read_units, "<STR_LIT>": write_units},<EOL>)<EOL><DEDENT>except botocore.exceptions.ClientError:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>
Create the table for this MetaStore. :param table: Pre-configured boto3 DynamoDB client object :type table: boto3.resources.base.BaseClient :param str table_name: Name of table to create :param int read_units: Read capacity units to provision :param int write_units: Write capacity units to provision
f5630:c2:m2
def _load_materials(self, material_name, version):<EOL>
_LOGGER.debug('<STR_LIT>', material_name, version)<EOL>key = {MetaStoreAttributeNames.PARTITION.value: material_name, MetaStoreAttributeNames.SORT.value: version}<EOL>response = self._encrypted_table.get_item(Key=key)<EOL>try:<EOL><INDENT>item = response["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise InvalidVersionError('<STR_LIT>'.format(material_name, version))<EOL><DEDENT>try:<EOL><INDENT>encryption_key_kwargs = dict(<EOL>key=item[MetaStoreAttributeNames.ENCRYPTION_KEY.value].value,<EOL>algorithm=item[MetaStoreAttributeNames.ENCRYPTION_ALGORITHM.value],<EOL>key_type=EncryptionKeyType.SYMMETRIC,<EOL>key_encoding=KeyEncodingType.RAW,<EOL>)<EOL>signing_key_kwargs = dict(<EOL>key=item[MetaStoreAttributeNames.INTEGRITY_KEY.value].value,<EOL>algorithm=item[MetaStoreAttributeNames.INTEGRITY_ALGORITHM.value],<EOL>key_type=EncryptionKeyType.SYMMETRIC,<EOL>key_encoding=KeyEncodingType.RAW,<EOL>)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if item[MetaStoreAttributeNames.MATERIAL_TYPE_VERSION.value] != MetaStoreValues.MATERIAL_TYPE_VERSION.value:<EOL><INDENT>raise InvalidVersionError(<EOL>'<STR_LIT>'.format(item[MetaStoreAttributeNames.MATERIAL_TYPE_VERSION.value])<EOL>)<EOL><DEDENT>encryption_key = JceNameLocalDelegatedKey(**encryption_key_kwargs)<EOL>signing_key = JceNameLocalDelegatedKey(**signing_key_kwargs)<EOL>return encryption_key, signing_key<EOL>
Load materials from table. :returns: Materials loaded into delegated keys :rtype: tuple(JceNameLocalDelegatedKey)
f5630:c2:m3
def _save_materials(self, material_name, version, encryption_key, signing_key):<EOL>
_LOGGER.debug('<STR_LIT>', material_name, version)<EOL>item = {<EOL>MetaStoreAttributeNames.PARTITION.value: material_name,<EOL>MetaStoreAttributeNames.SORT.value: version,<EOL>MetaStoreAttributeNames.MATERIAL_TYPE_VERSION.value: MetaStoreValues.MATERIAL_TYPE_VERSION.value,<EOL>MetaStoreAttributeNames.ENCRYPTION_ALGORITHM.value: encryption_key.algorithm,<EOL>MetaStoreAttributeNames.ENCRYPTION_KEY.value: Binary(encryption_key.key),<EOL>MetaStoreAttributeNames.INTEGRITY_ALGORITHM.value: signing_key.algorithm,<EOL>MetaStoreAttributeNames.INTEGRITY_KEY.value: Binary(signing_key.key),<EOL>}<EOL>try:<EOL><INDENT>self._encrypted_table.put_item(<EOL>Item=item,<EOL>ConditionExpression=(<EOL>Attr(MetaStoreAttributeNames.PARTITION.value).not_exists()<EOL>& Attr(MetaStoreAttributeNames.SORT.value).not_exists()<EOL>),<EOL>)<EOL><DEDENT>except botocore.exceptions.ClientError as error:<EOL><INDENT>if error.response["<STR_LIT>"]["<STR_LIT>"] == "<STR_LIT>":<EOL><INDENT>raise VersionAlreadyExistsError('<STR_LIT>'.format(material_name, version))<EOL><DEDENT><DEDENT>
Save materials to the table, raising an error if the version already exists. :param str material_name: Material to locate :param int version: Version of material to locate :raises VersionAlreadyExistsError: if the specified version already exists
f5630:c2:m4
def _save_or_load_materials(<EOL>self,<EOL>material_name, <EOL>version, <EOL>encryption_key, <EOL>signing_key, <EOL>):<EOL>
try:<EOL><INDENT>self._save_materials(material_name, version, encryption_key, signing_key)<EOL>return encryption_key, signing_key<EOL><DEDENT>except VersionAlreadyExistsError:<EOL><INDENT>return self._load_materials(material_name, version)<EOL><DEDENT>
Attempt to save the materials to the table. If the specified version already exists, the existing materials will be loaded from the table and returned. Otherwise, the provided materials will be returned. :param str material_name: Material to locate :param int version: Version of material to locate :param JceNameLocalDelegatedKey encryption_key: Loaded encryption key :param JceNameLocalDelegatedKey signing_key: Loaded signing key
f5630:c2:m5
@staticmethod<EOL><INDENT>def _material_description(material_name, version):<EOL><DEDENT>
return {_MATERIAL_DESCRIPTION_META_FIELD: "<STR_LIT>".format(name=material_name, version=version)}<EOL>
Build a material description from a material name and version. :param str material_name: Material to locate :param int version: Version of material to locate
f5630:c2:m6
def _load_provider_from_table(self, material_name, version):<EOL>
encryption_key, signing_key = self._load_materials(material_name, version)<EOL>return WrappedCryptographicMaterialsProvider(<EOL>signing_key=signing_key,<EOL>wrapping_key=encryption_key,<EOL>unwrapping_key=encryption_key,<EOL>material_description=self._material_description(material_name, version),<EOL>)<EOL>
Load a provider from the table. If the requested version does not exist, an error will be raised. :param str material_name: Material to locate :param int version: Version of material to locate
f5630:c2:m7
def get_or_create_provider(self, material_name, version):<EOL>
encryption_key = JceNameLocalDelegatedKey.generate(<EOL>MetaStoreValues.ENCRYPTION_ALGORITHM.value, MetaStoreValues.KEY_BITS.value<EOL>)<EOL>signing_key = JceNameLocalDelegatedKey.generate(<EOL>MetaStoreValues.INTEGRITY_ALGORITHM.value, MetaStoreValues.KEY_BITS.value<EOL>)<EOL>encryption_key, signing_key = self._save_or_load_materials(material_name, version, encryption_key, signing_key)<EOL>return WrappedCryptographicMaterialsProvider(<EOL>signing_key=signing_key,<EOL>wrapping_key=encryption_key,<EOL>unwrapping_key=encryption_key,<EOL>material_description=self._material_description(material_name, version),<EOL>)<EOL>
Obtain a cryptographic materials provider identified by a name and version. If the requested version does not exist, a new one will be created. :param str material_name: Material to locate :param int version: Version of material to locate :returns: cryptographic materials provider :rtype: CryptographicMaterialsProvider :raises InvalidVersionError: if the requested version is not available and cannot be created
f5630:c2:m8
def provider(self, material_name, version=None):<EOL>
if version is not None:<EOL><INDENT>return self._load_provider_from_table(material_name, version)<EOL><DEDENT>return super(MetaStore, self).provider(material_name, version)<EOL>
Obtain a cryptographic materials provider identified by a name and version. If the version is provided, an error will be raised if that version is not found. If the version is not provided, the maximum version will be used. :param str material_name: Material to locate :param int version: Version of material to locate (optional) :returns: cryptographic materials provider :rtype: CryptographicMaterialsProvider :raises InvalidVersionError: if the requested version is not found
f5630:c2:m9
def version_from_material_description(self, material_description):<EOL>
try:<EOL><INDENT>info = material_description[_MATERIAL_DESCRIPTION_META_FIELD]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>return int(info.split("<STR_LIT:#>", <NUM_LIT:1>)[<NUM_LIT:1>])<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>
Determine the version from the provided material description. :param dict material_description: Material description to use with this request :returns: version to use :rtype: int
f5630:c2:m10
def max_version(self, material_name):<EOL>
response = self._encrypted_table.query(<EOL>KeyConditionExpression=Key(MetaStoreAttributeNames.PARTITION.value).eq(material_name),<EOL>ScanIndexForward=False,<EOL>Limit=<NUM_LIT:1>,<EOL>)<EOL>if not response["<STR_LIT>"]:<EOL><INDENT>raise NoKnownVersionError('<STR_LIT>'.format(material_name))<EOL><DEDENT>return int(response["<STR_LIT>"][<NUM_LIT:0>][MetaStoreAttributeNames.SORT.value])<EOL>
Find the maximum known version of the specified material. :param str material_name: Material to locate :returns: Maximum known version :rtype: int :raises NoKnownVersion: if no version can be found
f5630:c2:m11
@abc.abstractmethod<EOL><INDENT>def get_or_create_provider(self, material_name, version):<EOL><DEDENT>
Obtain a cryptographic materials provider identified by a name and version. If the requested version does not exist, a new one might be created. :param str material_name: Material to locate :param int version: Version of material to locate (optional) :returns: cryptographic materials provider :rtype: CryptographicMaterialsProvider :raises InvalidVersionError: if the requested version is not available and cannot be created
f5631:c0:m0
@abc.abstractmethod<EOL><INDENT>def version_from_material_description(self, material_description):<EOL><DEDENT>
Determine the version from the provided material description. :param dict material_description: Material description to use with this request :returns: version to use :rtype: int
f5631:c0:m1
def max_version(self, material_name):<EOL>
raise NoKnownVersionError('<STR_LIT>'.format(material_name))<EOL>
Find the maximum known version of the specified material. .. note:: Child classes should usually override this method. :param str material_name: Material to locate :returns: Maximum known version :rtype: int :raises NoKnownVersionError: if no version can be found
f5631:c0:m2
def provider(self, material_name, version=None):<EOL>
if version is None:<EOL><INDENT>try:<EOL><INDENT>version = self.max_version(material_name)<EOL><DEDENT>except NoKnownVersionError:<EOL><INDENT>version = <NUM_LIT:0><EOL><DEDENT><DEDENT>return self.get_or_create_provider(material_name, version)<EOL>
Obtain a cryptographic materials provider identified by a name and version. If the version is not provided, the maximum version will be used. :param str material_name: Material to locate :param int version: Version of material to locate (optional) :returns: cryptographic materials provider :rtype: CryptographicMaterialsProvider :raises InvalidVersionError: if the requested version is not found
f5631:c0:m3
def new_provider(self, material_name):<EOL>
version = self.max_version(material_name) + <NUM_LIT:1><EOL>return self.get_or_create_provider(material_name, version)<EOL>
Create a new provider with a version one greater than the current known maximum. :param str material_name: Material to locate :returns: cryptographic materials provider :rtype: CryptographicMaterialsProvider
f5631:c0:m4
def __attrs_post_init__(self):
if self._table_info is None:<EOL><INDENT>self._table_info = TableInfo(name=self._table.name)<EOL><DEDENT>if self._auto_refresh_table_indexes:<EOL><INDENT>self._table_info.refresh_indexed_attributes(self._table.meta.client)<EOL><DEDENT>self._attribute_actions = self._attribute_actions.copy()<EOL>self._attribute_actions.set_index_keys(*self._table_info.protected_index_keys())<EOL>self._crypto_config = partial( <EOL>crypto_config_from_kwargs,<EOL>partial(crypto_config_from_table_info, self._materials_provider, self._attribute_actions, self._table_info),<EOL>)<EOL>self.get_item = partial( <EOL>decrypt_get_item, decrypt_python_item, self._crypto_config, self._table.get_item<EOL>)<EOL>self.put_item = partial( <EOL>encrypt_put_item, encrypt_python_item, self._crypto_config, self._table.put_item<EOL>)<EOL>self.query = partial( <EOL>decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.query<EOL>)<EOL>self.scan = partial( <EOL>decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.scan<EOL>)<EOL>
Prepare table info is it was not set and set up translation methods.
f5633:c0:m1
def __getattr__(self, name):
return getattr(self._table, name)<EOL>
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided bridge object. :param str name: Attribute name :returns: Result of asking the provided table object for that attribute name :raises AttributeError: if attribute is not found on provided bridge object
f5633:c0:m2
def update_item(self, **kwargs):
raise NotImplementedError('<STR_LIT>')<EOL>
Update item is not yet supported.
f5633:c0:m3
def batch_writer(self, overwrite_by_pkeys=None):
encrypted_client = EncryptedClient(<EOL>client=self._table.meta.client,<EOL>materials_provider=self._materials_provider,<EOL>attribute_actions=self._attribute_actions,<EOL>auto_refresh_table_indexes=self._auto_refresh_table_indexes,<EOL>expect_standard_dictionaries=True,<EOL>)<EOL>return BatchWriter(table_name=self._table.name, client=encrypted_client, overwrite_by_pkeys=overwrite_by_pkeys)<EOL>
Create a batch writer object. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Table.batch_writer :type overwrite_by_pkeys: list(string) :param overwrite_by_pkeys: De-duplicate request items in buffer if match new request item on specified primary keys. i.e ``["partition_key1", "sort_key2", "sort_key3"]``
f5633:c0:m4
def __attrs_post_init__(self):
self.all = partial( <EOL>self._transform_table, self._collection.all<EOL>)<EOL>self.filter = partial( <EOL>self._transform_table, self._collection.filter<EOL>)<EOL>self.limit = partial( <EOL>self._transform_table, self._collection.limit<EOL>)<EOL>self.page_size = partial( <EOL>self._transform_table, self._collection.page_size<EOL>)<EOL>
Set up the translation methods.
f5634:c0:m1
def __getattr__(self, name):
return getattr(self._collection, name)<EOL>
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided collection object. :param str name: Attribute name :returns: Result of asking the provided collection object for that attribute name :raises AttributeError: if attribute is not found on provided collection object
f5634:c0:m2
def _transform_table(self, method, **kwargs):
for table in method(**kwargs):<EOL><INDENT>yield EncryptedTable(<EOL>table=table,<EOL>materials_provider=self._materials_provider,<EOL>table_info=self._table_info_cache.table_info(table.name),<EOL>attribute_actions=self._attribute_actions,<EOL>)<EOL><DEDENT>
Transform a Table from the underlying collection manager to an EncryptedTable. :param method: Method on underlying collection manager to call :type method: callable :param **kwargs: Keyword arguments to pass to ``method``
f5634:c0:m3
def __attrs_post_init__(self):
self._table_info_cache = TableInfoCache( <EOL>client=self._resource.meta.client, auto_refresh_table_indexes=self._auto_refresh_table_indexes<EOL>)<EOL>self._crypto_config = partial( <EOL>crypto_config_from_cache, self._materials_provider, self._attribute_actions, self._table_info_cache<EOL>)<EOL>self.tables = EncryptedTablesCollectionManager( <EOL>collection=self._resource.tables,<EOL>materials_provider=self._materials_provider,<EOL>attribute_actions=self._attribute_actions,<EOL>table_info_cache=self._table_info_cache,<EOL>)<EOL>self.batch_get_item = partial( <EOL>decrypt_batch_get_item, decrypt_python_item, self._crypto_config, self._resource.batch_get_item<EOL>)<EOL>self.batch_write_item = partial( <EOL>encrypt_batch_write_item, encrypt_python_item, self._crypto_config, self._resource.batch_write_item<EOL>)<EOL>
Set up the table info cache, encrypted tables collection manager, and translation methods.
f5634:c1:m1
def __getattr__(self, name):
return getattr(self._resource, name)<EOL>
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided resource object. :param str name: Attribute name :returns: Result of asking the provided resource object for that attribute name :raises AttributeError: if attribute is not found on provided resource object
f5634:c1:m2
def Table(self, name, **kwargs):<EOL>
table_kwargs = dict(<EOL>table=self._resource.Table(name),<EOL>materials_provider=kwargs.get("<STR_LIT>", self._materials_provider),<EOL>attribute_actions=kwargs.get("<STR_LIT>", self._attribute_actions),<EOL>auto_refresh_table_indexes=kwargs.get("<STR_LIT>", self._auto_refresh_table_indexes),<EOL>table_info=self._table_info_cache.table_info(name),<EOL>)<EOL>return EncryptedTable(**table_kwargs)<EOL>
Creates an EncryptedTable resource. If any of the optional configuration values are not provided, the corresponding values for this ``EncryptedResource`` will be used. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.ServiceResource.Table :param name: The table name. :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use (optional) :param TableInfo table_info: Information about the target DynamoDB table (optional) :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes (optional)
f5634:c1:m3
@_decrypt_method.validator<EOL><INDENT>def validate_decrypt_method(self, attribute, value):<EOL><DEDENT>
if self._decrypt_method not in (decrypt_python_item, decrypt_dynamodb_item):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>name=attribute.name<EOL>)<EOL>)<EOL><DEDENT>
Validate that _decrypt_method is one of the item encryptors.
f5635:c0:m1
def __getattr__(self, name):
return getattr(self._paginator, name)<EOL>
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object
f5635:c0:m2
def paginate(self, **kwargs):<EOL>
validate_get_arguments(kwargs)<EOL>crypto_config, ddb_kwargs = self._crypto_config_method(**kwargs)<EOL>for page in self._paginator.paginate(**ddb_kwargs):<EOL><INDENT>for pos, value in enumerate(page["<STR_LIT>"]):<EOL><INDENT>page["<STR_LIT>"][pos] = self._decrypt_method(item=value, crypto_config=crypto_config)<EOL><DEDENT>yield page<EOL><DEDENT>
Create an iterator that will paginate through responses from the underlying paginator, transparently decrypting any returned items.
f5635:c0:m3
def __attrs_post_init__(self):
if self._expect_standard_dictionaries:<EOL><INDENT>self._encrypt_item = encrypt_python_item <EOL>self._decrypt_item = decrypt_python_item <EOL><DEDENT>else:<EOL><INDENT>self._encrypt_item = encrypt_dynamodb_item <EOL>self._decrypt_item = decrypt_dynamodb_item <EOL><DEDENT>self._table_info_cache = TableInfoCache( <EOL>client=self._client, auto_refresh_table_indexes=self._auto_refresh_table_indexes<EOL>)<EOL>self._table_crypto_config = partial( <EOL>crypto_config_from_cache, self._materials_provider, self._attribute_actions, self._table_info_cache<EOL>)<EOL>self._item_crypto_config = partial( <EOL>crypto_config_from_kwargs, self._table_crypto_config<EOL>)<EOL>self.get_item = partial( <EOL>decrypt_get_item, self._decrypt_item, self._item_crypto_config, self._client.get_item<EOL>)<EOL>self.put_item = partial( <EOL>encrypt_put_item, self._encrypt_item, self._item_crypto_config, self._client.put_item<EOL>)<EOL>self.query = partial( <EOL>decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.query<EOL>)<EOL>self.scan = partial( <EOL>decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.scan<EOL>)<EOL>self.batch_get_item = partial( <EOL>decrypt_batch_get_item, self._decrypt_item, self._table_crypto_config, self._client.batch_get_item<EOL>)<EOL>self.batch_write_item = partial( <EOL>encrypt_batch_write_item, self._encrypt_item, self._table_crypto_config, self._client.batch_write_item<EOL>)<EOL>
Set up the table info cache and translation methods.
f5635:c1:m1
def __getattr__(self, name):
return getattr(self._client, name)<EOL>
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object
f5635:c1:m2
def update_item(self, **kwargs):
raise NotImplementedError('<STR_LIT>')<EOL>
Update item is not yet supported. :raises NotImplementedError: if called
f5635:c1:m3
def get_paginator(self, operation_name):
paginator = self._client.get_paginator(operation_name)<EOL>if operation_name in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return EncryptedPaginator(<EOL>paginator=paginator, decrypt_method=self._decrypt_item, crypto_config_method=self._item_crypto_config<EOL>)<EOL><DEDENT>return paginator<EOL>
Get a paginator from the underlying client. If the paginator requested is for "scan" or "query", the paginator returned will transparently decrypt the returned items. :param str operation_name: Name of operation for which to get paginator :returns: Paginator for name :rtype: :class:`botocore.paginate.Paginator` or :class:`EncryptedPaginator`
f5635:c1:m4
def __attrs_post_init__(self):<EOL>
if self.encryption_context.partition_key_name is not None:<EOL><INDENT>if (<EOL>self.attribute_actions.action(self.encryption_context.partition_key_name)<EOL>is CryptoAction.ENCRYPT_AND_SIGN<EOL>): <EOL><INDENT>raise InvalidArgumentError("<STR_LIT>")<EOL><DEDENT><DEDENT>if self.encryption_context.sort_key_name is not None:<EOL><INDENT>if self.attribute_actions.action(self.encryption_context.sort_key_name) is CryptoAction.ENCRYPT_AND_SIGN:<EOL><INDENT>raise InvalidArgumentError("<STR_LIT>")<EOL><DEDENT><DEDENT>
Make sure that primary index attributes are not being encrypted.
f5636:c0:m1
def decryption_materials(self):<EOL>
return self.materials_provider.decryption_materials(self.encryption_context)<EOL>
Load decryption materials from instance resources. :returns: Decryption materials :rtype: CryptographicMaterials
f5636:c0:m2
def encryption_materials(self):<EOL>
return self.materials_provider.encryption_materials(self.encryption_context)<EOL>
Load encryption materials from instance resources. :returns: Encryption materials :rtype: CryptographicMaterials
f5636:c0:m3
def copy(self):<EOL>
return CryptoConfig(<EOL>materials_provider=self.materials_provider,<EOL>encryption_context=copy.copy(self.encryption_context),<EOL>attribute_actions=self.attribute_actions,<EOL>)<EOL>
Return a copy of this instance with a copied instance of its encryption context. :returns: New :class:`CryptoConfig` identical to this one :rtype: CryptoConfig
f5636:c0:m4
def with_item(self, item):
new_config = self.copy()<EOL>new_config.encryption_context.attributes = item<EOL>return new_config<EOL>
Return a copy of this instance with an encryption context that includes the provided item attributes. :param dict item: DynamoDB item in DynamnoDB JSON format :returns: New :class:`CryptoConfig` identical to this one :rtype: CryptoConfig
f5636:c0:m5
def encrypt_dynamodb_item(item, crypto_config):<EOL>
if crypto_config.attribute_actions.take_no_actions:<EOL><INDENT>return item.copy()<EOL><DEDENT>for reserved_name in ReservedAttributes:<EOL><INDENT>if reserved_name.value in item:<EOL><INDENT>raise EncryptionError(<EOL>'<STR_LIT>'.format(reserved_name.value)<EOL>)<EOL><DEDENT><DEDENT>encryption_materials = crypto_config.encryption_materials()<EOL>inner_material_description = encryption_materials.material_description.copy()<EOL>try:<EOL><INDENT>encryption_materials.encryption_key<EOL><DEDENT>except AttributeError:<EOL><INDENT>if crypto_config.attribute_actions.contains_action(CryptoAction.ENCRYPT_AND_SIGN):<EOL><INDENT>raise EncryptionError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>encrypted_item = item.copy()<EOL><DEDENT>else:<EOL><INDENT>encryption_mode = MaterialDescriptionValues.CBC_PKCS5_ATTRIBUTE_ENCRYPTION.value<EOL>inner_material_description[MaterialDescriptionKeys.ATTRIBUTE_ENCRYPTION_MODE.value] = encryption_mode<EOL>algorithm_descriptor = encryption_materials.encryption_key.algorithm + encryption_mode<EOL>encrypted_item = {}<EOL>for name, attribute in item.items():<EOL><INDENT>if crypto_config.attribute_actions.action(name) is CryptoAction.ENCRYPT_AND_SIGN:<EOL><INDENT>encrypted_item[name] = encrypt_attribute(<EOL>attribute_name=name,<EOL>attribute=attribute,<EOL>encryption_key=encryption_materials.encryption_key,<EOL>algorithm=algorithm_descriptor,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>encrypted_item[name] = attribute.copy()<EOL><DEDENT><DEDENT><DEDENT>signature_attribute = sign_item(encrypted_item, encryption_materials.signing_key, crypto_config)<EOL>encrypted_item[ReservedAttributes.SIGNATURE.value] = signature_attribute<EOL>try:<EOL><INDENT>inner_material_description[<EOL>MaterialDescriptionKeys.SIGNING_KEY_ALGORITHM.value<EOL>] = encryption_materials.signing_key.signing_algorithm()<EOL><DEDENT>except NotImplementedError:<EOL><INDENT>pass<EOL><DEDENT>material_description_attribute = serialize_material_description(inner_material_description)<EOL>encrypted_item[ReservedAttributes.MATERIAL_DESCRIPTION.value] = material_description_attribute<EOL>return encrypted_item<EOL>
Encrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item >>> plaintext_item = { ... 'some': {'S': 'data'}, ... 'more': {'N': '5'} ... } >>> encrypted_item = encrypt_dynamodb_item( ... item=plaintext_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles DynamoDB-formatted items and is for use with the boto3 DynamoDB client. :param dict item: Plaintext DynamoDB item :param CryptoConfig crypto_config: Cryptographic configuration :returns: Encrypted and signed DynamoDB item :rtype: dict
f5637:m0
def encrypt_python_item(item, crypto_config):<EOL>
ddb_item = dict_to_ddb(item)<EOL>encrypted_ddb_item = encrypt_dynamodb_item(ddb_item, crypto_config)<EOL>return ddb_to_dict(encrypted_ddb_item)<EOL>
Encrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item >>> plaintext_item = { ... 'some': 'data', ... 'more': 5 ... } >>> encrypted_item = encrypt_python_item( ... item=plaintext_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles human-friendly dictionaries and is for use with the boto3 DynamoDB service or table resource. :param dict item: Plaintext dictionary :param CryptoConfig crypto_config: Cryptographic configuration :returns: Encrypted and signed dictionary :rtype: dict
f5637:m1
def decrypt_dynamodb_item(item, crypto_config):<EOL>
unique_actions = set([crypto_config.attribute_actions.default_action.name])<EOL>unique_actions.update(set([action.name for action in crypto_config.attribute_actions.attribute_actions.values()]))<EOL>if crypto_config.attribute_actions.take_no_actions:<EOL><INDENT>return item.copy()<EOL><DEDENT>try:<EOL><INDENT>signature_attribute = item.pop(ReservedAttributes.SIGNATURE.value)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise DecryptionError("<STR_LIT>")<EOL><DEDENT>inner_crypto_config = crypto_config.copy()<EOL>try:<EOL><INDENT>material_description_attribute = item.pop(ReservedAttributes.MATERIAL_DESCRIPTION.value)<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>material_description = deserialize_material_description(material_description_attribute)<EOL>inner_crypto_config.encryption_context.material_description = material_description<EOL><DEDENT>decryption_materials = inner_crypto_config.decryption_materials()<EOL>verify_item_signature(signature_attribute, item, decryption_materials.verification_key, inner_crypto_config)<EOL>try:<EOL><INDENT>decryption_key = decryption_materials.decryption_key<EOL><DEDENT>except AttributeError:<EOL><INDENT>if inner_crypto_config.attribute_actions.contains_action(CryptoAction.ENCRYPT_AND_SIGN):<EOL><INDENT>raise DecryptionError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return item.copy()<EOL><DEDENT>decryption_mode = inner_crypto_config.encryption_context.material_description.get(<EOL>MaterialDescriptionKeys.ATTRIBUTE_ENCRYPTION_MODE.value<EOL>)<EOL>algorithm_descriptor = decryption_key.algorithm + decryption_mode<EOL>decrypted_item = {}<EOL>for name, attribute in item.items():<EOL><INDENT>if inner_crypto_config.attribute_actions.action(name) is CryptoAction.ENCRYPT_AND_SIGN:<EOL><INDENT>decrypted_item[name] = decrypt_attribute(<EOL>attribute_name=name, attribute=attribute, decryption_key=decryption_key, algorithm=algorithm_descriptor<EOL>)<EOL><DEDENT>else:<EOL><INDENT>decrypted_item[name] = attribute.copy()<EOL><DEDENT><DEDENT>return decrypted_item<EOL>
Decrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': {'B': b'ENCRYPTED_DATA'}, ... 'more': {'B': b'ENCRYPTED_DATA'} ... } >>> decrypted_item = decrypt_python_item( ... item=encrypted_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles DynamoDB-formatted items and is for use with the boto3 DynamoDB client. :param dict item: Encrypted and signed DynamoDB item :param CryptoConfig crypto_config: Cryptographic configuration :returns: Plaintext DynamoDB item :rtype: dict
f5637:m2
def decrypt_python_item(item, crypto_config):<EOL>
ddb_item = dict_to_ddb(item)<EOL>decrypted_ddb_item = decrypt_dynamodb_item(ddb_item, crypto_config)<EOL>return ddb_to_dict(decrypted_ddb_item)<EOL>
Decrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': Binary(b'ENCRYPTED_DATA'), ... 'more': Binary(b'ENCRYPTED_DATA') ... } >>> decrypted_item = decrypt_python_item( ... item=encrypted_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles human-friendly dictionaries and is for use with the boto3 DynamoDB service or table resource. :param dict item: Encrypted and signed dictionary :param CryptoConfig crypto_config: Cryptographic configuration :returns: Plaintext dictionary :rtype: dict
f5637:m3
def __attrs_post_init__(self):
if self._encryption_key is not None and not self._encryption_key.allowed_for_raw_materials:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>type(self._encryption_key)<EOL>)<EOL>)<EOL><DEDENT>
Verify that the encryption key is allowed be used for raw materials.
f5639:c0:m1
@property<EOL><INDENT>def material_description(self):<EOL><DEDENT>
return self._material_description<EOL>
Material description to use with these cryptographic materials. :returns: Material description :rtype: dict
f5639:c0:m2
@property<EOL><INDENT>def signing_key(self):<EOL><DEDENT>
return self._signing_key<EOL>
Delegated key used for calculating digital signatures. :returns: Signing key :rtype: DelegatedKey
f5639:c0:m3
@property<EOL><INDENT>def encryption_key(self):<EOL><DEDENT>
if self._encryption_key is None:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT>return self._encryption_key<EOL>
Delegated key used for encrypting attributes. :returns: Encryption key :rtype: DelegatedKey
f5639:c0:m4
def __attrs_post_init__(self):
if self._decryption_key is not None and not self._decryption_key.allowed_for_raw_materials:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>type(self._decryption_key)<EOL>)<EOL>)<EOL><DEDENT>
Verify that the encryption key is allowed be used for raw materials.
f5639:c1:m1
@property<EOL><INDENT>def material_description(self):<EOL><DEDENT>
return self._material_description<EOL>
Material description to use with these cryptographic materials. :returns: Material description :rtype: dict
f5639:c1:m2
@property<EOL><INDENT>def verification_key(self):<EOL><DEDENT>
return self._verification_key<EOL>
Delegated key used for verifying digital signatures. :returns: Verification key :rtype: DelegatedKey
f5639:c1:m3
@property<EOL><INDENT>def decryption_key(self):<EOL><DEDENT>
if self._decryption_key is None:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT>return self._decryption_key<EOL>
Delegated key used for decrypting attributes. :returns: Decryption key :rtype: DelegatedKey
f5639:c1:m4
def __attrs_post_init__(self):
self._content_key_algorithm = self.material_description.get( <EOL>MaterialDescriptionKeys.CONTENT_ENCRYPTION_ALGORITHM.value, _DEFAULT_CONTENT_ENCRYPTION_ALGORITHM<EOL>)<EOL>if MaterialDescriptionKeys.WRAPPED_DATA_KEY.value in self.material_description:<EOL><INDENT>self._content_key = (<EOL>self._content_key_from_material_description()<EOL>) <EOL><DEDENT>else:<EOL><INDENT>self._content_key, self._material_description = (<EOL>self._generate_content_key()<EOL>)<EOL><DEDENT>
Prepare the content key.
f5640:c0:m1
@staticmethod<EOL><INDENT>def _wrapping_transformation(algorithm):<DEDENT>
return _WRAPPING_TRANSFORMATION.get(algorithm, algorithm)<EOL>
Convert the specified algorithm name to the desired wrapping algorithm transformation. :param str algorithm: Algorithm name :returns: Algorithm transformation for wrapping with algorithm :rtype: str
f5640:c0:m2
def _content_key_from_material_description(self):
if self._unwrapping_key is None:<EOL><INDENT>raise UnwrappingError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>wrapping_algorithm = self.material_description.get(<EOL>MaterialDescriptionKeys.CONTENT_KEY_WRAPPING_ALGORITHM.value, self._unwrapping_key.algorithm<EOL>)<EOL>wrapped_key = base64.b64decode(self.material_description[MaterialDescriptionKeys.WRAPPED_DATA_KEY.value])<EOL>content_key_algorithm = self._content_key_algorithm.split("<STR_LIT:/>", <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>return self._unwrapping_key.unwrap(<EOL>algorithm=wrapping_algorithm,<EOL>wrapped_key=wrapped_key,<EOL>wrapped_key_algorithm=content_key_algorithm,<EOL>wrapped_key_type=EncryptionKeyType.SYMMETRIC,<EOL>additional_associated_data=None,<EOL>)<EOL>
Load the content key from material description and unwrap it for use. :returns: Unwrapped content key :rtype: DelegatedKey
f5640:c0:m3
def _generate_content_key(self):
if self._wrapping_key is None:<EOL><INDENT>raise WrappingError("<STR_LIT>")<EOL><DEDENT>wrapping_algorithm = self.material_description.get(<EOL>MaterialDescriptionKeys.CONTENT_KEY_WRAPPING_ALGORITHM.value,<EOL>self._wrapping_transformation(self._wrapping_key.algorithm),<EOL>)<EOL>args = self._content_key_algorithm.split("<STR_LIT:/>", <NUM_LIT:1>)<EOL>content_algorithm = args[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>content_key_length = int(args[<NUM_LIT:1>])<EOL><DEDENT>except IndexError:<EOL><INDENT>content_key_length = None<EOL><DEDENT>content_key = JceNameLocalDelegatedKey.generate(algorithm=content_algorithm, key_length=content_key_length)<EOL>wrapped_key = self._wrapping_key.wrap(<EOL>algorithm=wrapping_algorithm, content_key=content_key.key, additional_associated_data=None<EOL>)<EOL>new_material_description = self.material_description.copy()<EOL>new_material_description.update(<EOL>{<EOL>MaterialDescriptionKeys.WRAPPED_DATA_KEY.value: base64.b64encode(wrapped_key),<EOL>MaterialDescriptionKeys.CONTENT_ENCRYPTION_ALGORITHM.value: self._content_key_algorithm,<EOL>MaterialDescriptionKeys.CONTENT_KEY_WRAPPING_ALGORITHM.value: wrapping_algorithm,<EOL>}<EOL>)<EOL>return content_key, new_material_description<EOL>
Generate the content encryption key and create a new material description containing necessary information about the content and wrapping keys. :returns content key and new material description :rtype: tuple containing DelegatedKey and dict
f5640:c0:m4
@property<EOL><INDENT>def material_description(self):<EOL><DEDENT>
return self._material_description<EOL>
Material description to use with these cryptographic materials. :returns: Material description :rtype: dict
f5640:c0:m5
@property<EOL><INDENT>def encryption_key(self):<DEDENT>
return self._content_key<EOL>
Content key used for encrypting attributes. :returns: Encryption key :rtype: DelegatedKey
f5640:c0:m6
@property<EOL><INDENT>def decryption_key(self):<DEDENT>
return self._content_key<EOL>
Content key used for decrypting attributes. :returns: Decryption key :rtype: DelegatedKey
f5640:c0:m7
@property<EOL><INDENT>def signing_key(self):<DEDENT>
return self._signing_key<EOL>
Delegated key used for calculating digital signatures. :returns: Signing key :rtype: DelegatedKey
f5640:c0:m8
@property<EOL><INDENT>def verification_key(self):<DEDENT>
return self._signing_key<EOL>
Delegated key used for verifying digital signatures. :returns: Verification key :rtype: DelegatedKey
f5640:c0:m9
@abc.abstractproperty<EOL><INDENT>def material_description(self):<EOL><DEDENT>
Material description to use with these cryptographic materials. :returns: Material description :rtype: dict
f5641:c0:m0
@abc.abstractproperty<EOL><INDENT>def encryption_key(self):<EOL><DEDENT>
Delegated key used for encrypting attributes. :returns: Encryption key :rtype: DelegatedKey
f5641:c0:m1
@abc.abstractproperty<EOL><INDENT>def decryption_key(self):<EOL><DEDENT>
Delegated key used for decrypting attributes. :returns: Decryption key :rtype: DelegatedKey
f5641:c0:m2
@abc.abstractproperty<EOL><INDENT>def signing_key(self):<EOL><DEDENT>
Delegated key used for calculating digital signatures. :returns: Signing key :rtype: DelegatedKey
f5641:c0:m3
@abc.abstractproperty<EOL><INDENT>def verification_key(self):<EOL><DEDENT>
Delegated key used for verifying digital signatures. :returns: Verification key :rtype: DelegatedKey
f5641:c0:m4
@property<EOL><INDENT>def decryption_key(self):<EOL><DEDENT>
raise NotImplementedError("<STR_LIT>")<EOL>
Encryption materials do not provide decryption keys. :raises NotImplementedError: because encryption materials do not contain decryption keys
f5641:c1:m0
@property<EOL><INDENT>def verification_key(self):<EOL><DEDENT>
raise NotImplementedError("<STR_LIT>")<EOL>
Encryption materials do not provide verification keys. :raises NotImplementedError: because encryption materials do not contain verification keys
f5641:c1:m1
@property<EOL><INDENT>def encryption_key(self):<EOL><DEDENT>
raise NotImplementedError("<STR_LIT>")<EOL>
Decryption materials do not provide encryption keys. :raises NotImplementedError: because decryption materials do not contain encryption keys
f5641:c2:m0
@property<EOL><INDENT>def signing_key(self):<EOL><DEDENT>
raise NotImplementedError("<STR_LIT>")<EOL>
Decryption materials do not provide signing keys. :raises NotImplementedError: because decryption materials do not contain signing keys
f5641:c2:m1
def _generate_symmetric_key(key_length):
return os.urandom(key_length // <NUM_LIT:8>), EncryptionKeyType.SYMMETRIC, KeyEncodingType.RAW<EOL>
Generate a new AES key. :param int key_length: Required key length in bits :returns: raw key, symmetric key identifier, and RAW encoding identifier :rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`)
f5642:m0
def _generate_rsa_key(key_length):
private_key = rsa.generate_private_key(public_exponent=<NUM_LIT>, key_size=key_length, backend=default_backend())<EOL>key_bytes = private_key.private_bytes(<EOL>encoding=serialization.Encoding.DER,<EOL>format=serialization.PrivateFormat.PKCS8,<EOL>encryption_algorithm=serialization.NoEncryption(),<EOL>)<EOL>return key_bytes, EncryptionKeyType.PRIVATE, KeyEncodingType.DER<EOL>
Generate a new RSA private key. :param int key_length: Required key length in bits :returns: DER-encoded private key, private key identifier, and DER encoding identifier :rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`)
f5642:m1
@property<EOL><INDENT>def algorithm(self):<EOL><DEDENT>
return self._algorithm<EOL>
Text description of algorithm used by this delegated key.
f5642:c0:m1
def _enable_authentication(self):<EOL>
self.sign = self._sign<EOL>self.verify = self._verify<EOL>self.signing_algorithm = self._signing_algorithm<EOL>
Enable authentication methods for keys that support them.
f5642:c0:m2
def _enable_encryption(self):<EOL>
self.encrypt = self._encrypt<EOL>self.decrypt = self._decrypt<EOL>
Enable encryption methods for keys that support them.
f5642:c0:m3
def _enable_wrap(self):<EOL>
self.wrap = self._wrap<EOL>self.unwrap = self._unwrap<EOL>
Enable key wrapping methods for keys that support them.
f5642:c0:m4
def __attrs_post_init__(self):<EOL>
<EOL>try:<EOL><INDENT>key_transformer = primitives.JAVA_ENCRYPTION_ALGORITHM[self.algorithm]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.__key = key_transformer.load_key( <EOL>self.key, self._key_type, self._key_encoding<EOL>)<EOL>self._enable_encryption()<EOL>self._enable_wrap()<EOL>return<EOL><DEDENT>try:<EOL><INDENT>key_transformer = authentication.JAVA_AUTHENTICATOR[self.algorithm]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.__key = key_transformer.load_key( <EOL>self.key, self._key_type, self._key_encoding<EOL>)<EOL>self._enable_authentication()<EOL>return<EOL><DEDENT>raise JceTransformationError('<STR_LIT>'.format(self.algorithm))<EOL>
Identify the correct key handler class for the requested algorithm and load the provided key.
f5642:c0:m5
@classmethod<EOL><INDENT>def generate(cls, algorithm, key_length=None):<EOL><DEDENT>
<EOL>algorithm_lookup = algorithm.upper()<EOL>if "<STR_LIT>" in algorithm_lookup or algorithm_lookup in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>algorithm_lookup = "<STR_LIT>"<EOL><DEDENT>elif "<STR_LIT>" in algorithm_lookup:<EOL><INDENT>algorithm_lookup = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>key_generator = _ALGORITHM_GENERATE_MAP[algorithm_lookup]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(algorithm))<EOL><DEDENT>key, key_type, key_encoding = key_generator(key_length)<EOL>return cls(key=key, algorithm=algorithm, key_type=key_type, key_encoding=key_encoding)<EOL>
Generate an instance of this :class:`DelegatedKey` using the specified algorithm and key length. :param str algorithm: Text description of algorithm to be used :param int key_length: Size in bits of key to generate :returns: Generated delegated key :rtype: DelegatedKey
f5642:c0:m6
@property<EOL><INDENT>def allowed_for_raw_materials(self):<EOL><DEDENT>
return self.algorithm == "<STR_LIT>"<EOL>
Only :class:`JceNameLocalDelegatedKey` backed by AES keys are allowed to be used with :class:`RawDecryptionMaterials` or :class:`RawEncryptionMaterials`. :returns: decision :rtype: bool
f5642:c0:m7
def _encrypt(self, algorithm, name, plaintext, additional_associated_data=None):<EOL>
encryptor = encryption.JavaCipher.from_transformation(algorithm)<EOL>return encryptor.encrypt(self.__key, plaintext)<EOL>
Encrypt data. :param str algorithm: Java StandardName transformation string of algorithm to use to encrypt data https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html :param str name: Name associated with plaintext data :param bytes plaintext: Plaintext data to encrypt :param dict additional_associated_data: Not used by all delegated keys, but if it is, then if it is provided on encrypt it must be required on decrypt. :returns: Encrypted ciphertext :rtype: bytes
f5642:c0:m8
def _decrypt(self, algorithm, name, ciphertext, additional_associated_data=None):<EOL>
decryptor = encryption.JavaCipher.from_transformation(algorithm)<EOL>return decryptor.decrypt(self.__key, ciphertext)<EOL>
Encrypt data. :param str algorithm: Java StandardName transformation string of algorithm to use to decrypt data https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html :param str name: Name associated with ciphertext data :param bytes ciphertext: Ciphertext data to decrypt :param dict additional_associated_data: Not used by :class:`JceNameLocalDelegatedKey` :returns: Decrypted plaintext :rtype: bytes
f5642:c0:m9
def _wrap(self, algorithm, content_key, additional_associated_data=None):<EOL>
wrapper = encryption.JavaCipher.from_transformation(algorithm)<EOL>return wrapper.wrap(wrapping_key=self.__key, key_to_wrap=content_key)<EOL>
Wrap content key. :param str algorithm: Text description of algorithm to use to wrap key :param bytes content_key: Raw content key to wrap :param dict additional_associated_data: Not used by :class:`JceNameLocalDelegatedKey` :returns: Wrapped key :rtype: bytes
f5642:c0:m10
def _unwrap(self, algorithm, wrapped_key, wrapped_key_algorithm, wrapped_key_type, additional_associated_data=None):<EOL>
if wrapped_key_type is not EncryptionKeyType.SYMMETRIC:<EOL><INDENT>raise UnwrappingError('<STR_LIT>'.format(wrapped_key_type))<EOL><DEDENT>unwrapper = encryption.JavaCipher.from_transformation(algorithm)<EOL>unwrapped_key = unwrapper.unwrap(wrapping_key=self.__key, wrapped_key=wrapped_key)<EOL>return JceNameLocalDelegatedKey(<EOL>key=unwrapped_key,<EOL>algorithm=wrapped_key_algorithm,<EOL>key_type=wrapped_key_type,<EOL>key_encoding=KeyEncodingType.RAW,<EOL>)<EOL>
Wrap content key. :param str algorithm: Text description of algorithm to use to unwrap key :param bytes content_key: Raw content key to wrap :param str wrapped_key_algorithm: Text description of algorithm for unwrapped key to use :param EncryptionKeyType wrapped_key_type: Type of key to treat key as once unwrapped :param dict additional_associated_data: Not used by :class:`JceNameLocalDelegatedKey` :returns: Delegated key using unwrapped key :rtype: DelegatedKey
f5642:c0:m11
def _sign(self, algorithm, data):<EOL>
signer = authentication.JAVA_AUTHENTICATOR[algorithm]<EOL>return signer.sign(self.__key, data)<EOL>
Sign data. :param str algorithm: Text description of algorithm to use to sign data :param bytes data: Data to sign :returns: Signature value :rtype: bytes
f5642:c0:m12
def _verify(self, algorithm, signature, data):<EOL>
verifier = authentication.JAVA_AUTHENTICATOR[algorithm]<EOL>verifier.verify(self.__key, signature, data)<EOL>
Sign data. :param str algorithm: Text description of algorithm to use to verify signature :param bytes signature: Signature to verify :param bytes data: Data over which to verify signature
f5642:c0:m13
def _signing_algorithm(self):<EOL>
return self.algorithm<EOL>
Provide a description that can inform an appropriate cryptographic materials provider about how to build a ``JceNameLocalDelegatedKey`` for signature verification. The return value of this method is included in the material description written to the encrypted item. :returns: Signing algorithm identifier :rtype: str
f5642:c0:m14
def _raise_not_implemented(method_name):
raise NotImplementedError('<STR_LIT>'.format(method_name))<EOL>
Raises a standardized :class:`NotImplementedError` to report that the specified method is not supported. :raises NotImplementedError: when called
f5643:m0
@abc.abstractproperty<EOL><INDENT>def algorithm(self):<EOL><DEDENT>
Text description of algorithm used by this delegated key.
f5643:c0:m0
@property<EOL><INDENT>def allowed_for_raw_materials(self):<EOL><DEDENT>
return False<EOL>
Most delegated keys should not be used with :class:`RawDecryptionMaterials` or :class:`RawEncryptionMaterials`. :returns: False :rtype: bool
f5643:c0:m1
@classmethod<EOL><INDENT>def generate(cls, algorithm, key_length): <EOL><DEDENT>
_raise_not_implemented("<STR_LIT>")<EOL>
Generate an instance of this :class:`DelegatedKey` using the specified algorithm and key length. :param str algorithm: Text description of algorithm to be used :param int key_length: Size of key to generate :returns: Generated delegated key :rtype: DelegatedKey
f5643:c0:m2
def encrypt(self, algorithm, name, plaintext, additional_associated_data=None): <EOL>
_raise_not_implemented("<STR_LIT>")<EOL>
Encrypt data. :param str algorithm: Text description of algorithm to use to encrypt data :param str name: Name associated with plaintext data :param bytes plaintext: Plaintext data to encrypt :param dict additional_associated_data: Not used by all delegated keys, but if it is, then if it is provided on encrypt it must be required on decrypt. :returns: Encrypted ciphertext :rtype: bytes
f5643:c0:m3
def decrypt(self, algorithm, name, ciphertext, additional_associated_data=None): <EOL>
_raise_not_implemented("<STR_LIT>")<EOL>
Encrypt data. :param str algorithm: Text description of algorithm to use to decrypt data :param str name: Name associated with ciphertext data :param bytes ciphertext: Ciphertext data to decrypt :param dict additional_associated_data: Not used by all delegated keys, but if it is, then if it is provided on encrypt it must be required on decrypt. :returns: Decrypted plaintext :rtype: bytes
f5643:c0:m4
def wrap(self, algorithm, content_key, additional_associated_data=None): <EOL>
_raise_not_implemented("<STR_LIT>")<EOL>
Wrap content key. :param str algorithm: Text description of algorithm to use to wrap key :param bytes content_key: Raw content key to wrap :param dict additional_associated_data: Not used by all delegated keys, but if it is, then if it is provided on wrap it must be required on unwrap. :returns: Wrapped key :rtype: bytes
f5643:c0:m5