signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def load_key(self, key, key_type, key_encoding):<EOL>
if not (key_type is EncryptionKeyType.SYMMETRIC and key_encoding is KeyEncodingType.RAW):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(key) * <NUM_LIT:8> < MinimumKeySizes.HMAC.value:<EOL><INDENT>_LOGGER.warning("<STR_LIT>" % MinimumKeySizes.HMAC.value)<EOL><DEDENT>return key<EOL>
Load a raw key from bytes. :param bytes key: Raw key bytes to load :param EncryptionKeyType key_type: Type of key to load :param KeyEncodingType key_encoding: Encoding used to serialize ``key`` :returns: Loaded key :rtype: bytes :raises ValueError: if ``key_type`` is not symmetric or ``key_encoding`` is not raw
f5615:c1:m2
def validate_algorithm(self, algorithm):<EOL>
if not algorithm.startswith(self.java_name):<EOL><INDENT>raise InvalidAlgorithmError(<EOL>'<STR_LIT>'.format(<EOL>requested=algorithm, actual=self.java_name<EOL>)<EOL>)<EOL><DEDENT>
Determine whether the requested algorithm name is compatible with this authenticator. :param str algorithm: Algorithm name :raises InvalidAlgorithmError: if specified algorithm name is not compatible with this authenticator
f5615:c1:m3
def sign(self, key, data):<EOL>
try:<EOL><INDENT>signer = self._build_hmac_signer(key)<EOL>signer.update(data)<EOL>return signer.finalize()<EOL><DEDENT>except Exception:<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise SigningError(message)<EOL><DEDENT>
Sign ``data`` using loaded ``key``. :param bytes key: Loaded key :param bytes data: Data to sign :returns: Calculated signature :rtype: bytes :raises SigningError: if unable to sign ``data`` with ``key``
f5615:c1:m4
def verify(self, key, signature, data):<EOL>
try:<EOL><INDENT>verifier = self._build_hmac_signer(key)<EOL>verifier.update(data)<EOL>verifier.verify(signature)<EOL><DEDENT>except Exception:<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise SignatureVerificationError(message)<EOL><DEDENT>
Verify ``signature`` over ``data`` using ``key``. :param bytes key: Loaded key :param bytes signature: Signature to verify :param bytes data: Data over which to verify signature :raises SignatureVerificationError: if unable to verify ``signature``
f5615:c1:m5
def validate_algorithm(self, algorithm):<EOL>
if not algorithm.endswith(self.java_name):<EOL><INDENT>raise InvalidAlgorithmError(<EOL>'<STR_LIT>'.format(<EOL>requested=algorithm, actual=self.java_name<EOL>)<EOL>)<EOL><DEDENT>
Determine whether the requested algorithm name is compatible with this authenticator. :param str algorithm: Algorithm name :raises InvalidAlgorithmError: if specified algorithm name is not compatible with this authenticator
f5615:c2:m1
def load_key(self, key, key_type, key_encoding):<EOL>
return load_rsa_key(key, key_type, key_encoding)<EOL>
Load a key object from the provided raw key bytes. :param bytes key: Raw key bytes to load :param EncryptionKeyType key_type: Type of key to load :param KeyEncodingType key_encoding: Encoding used to serialize ``key`` :returns: Loaded key :rtype: TODO: :raises ValueError: if ``key_type`` and ``key_encoding`` are not a valid pairing
f5615:c2:m2
def sign(self, key, data):<EOL>
if hasattr(key, "<STR_LIT>"):<EOL><INDENT>raise SigningError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>return key.sign(data, self.padding_type(), self.hash_type())<EOL><DEDENT>except Exception:<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise SigningError(message)<EOL><DEDENT>
Sign ``data`` using loaded ``key``. :param key: Loaded key :type key: TODO: :param bytes data: Data to sign :returns: Calculated signature :rtype: bytes :raises SigningError: if unable to sign ``data`` with ``key``
f5615:c2:m3
def verify(self, key, signature, data):<EOL>
if hasattr(key, "<STR_LIT>"):<EOL><INDENT>_key = key.public_key()<EOL><DEDENT>else:<EOL><INDENT>_key = key<EOL><DEDENT>try:<EOL><INDENT>_key.verify(signature, data, self.padding_type(), self.hash_type())<EOL><DEDENT>except Exception:<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise SignatureVerificationError(message)<EOL><DEDENT>
Verify ``signature`` over ``data`` using ``key``. :param key: Loaded key :type key: TODO: :param bytes signature: Signature to verify :param bytes data: Data over which to verify signature :raises SignatureVerificationError: if unable to verify ``signature``
f5615:c2:m4
def encrypt(self, key, data):
return self.cipher.encrypt(key, data, self.mode, self.padding)<EOL>
Encrypt data using loaded key. :param key: Key loaded by ``cipher`` :param bytes data: Data to encrypt :returns: Encrypted data :rtype: bytes
f5616:c0:m1
def decrypt(self, key, data):
return self.cipher.decrypt(key, data, self.mode, self.padding)<EOL>
Decrypt data using loaded key. :param key: Key loaded by ``cipher`` :param bytes data: Data to decrypt :returns: Decrypted data :rtype: bytes
f5616:c0:m2
def wrap(self, wrapping_key, key_to_wrap):
if hasattr(self.cipher, "<STR_LIT>"):<EOL><INDENT>return self.cipher.wrap(wrapping_key, key_to_wrap)<EOL><DEDENT>return self.cipher.encrypt(key=wrapping_key, data=key_to_wrap, mode=self.mode, padding=self.padding)<EOL>
Wrap key using loaded key. :param wrapping_key: Key loaded by ``cipher`` :param bytes key_to_wrap: Key to wrap :returns: Wrapped key :rtype: bytes
f5616:c0:m3
def unwrap(self, wrapping_key, wrapped_key):
if hasattr(self.cipher, "<STR_LIT>"):<EOL><INDENT>return self.cipher.unwrap(wrapping_key, wrapped_key)<EOL><DEDENT>return self.cipher.decrypt(key=wrapping_key, data=wrapped_key, mode=self.mode, padding=self.padding)<EOL>
Wrap key using loaded key. :param wrapping_key: Key loaded by ``cipher`` :param bytes wrapped_key: Wrapped key :returns: Unwrapped key :rtype: bytes
f5616:c0:m4
@property<EOL><INDENT>def transformation(self):<DEDENT>
return "<STR_LIT>".format(<EOL>cipher=self.cipher.java_name, mode=self.mode.java_name, padding=self.padding.java_name<EOL>)<EOL>
Returns the Java transformation describing this JavaCipher. https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Cipher :returns: Formatted transformation :rtype: str
f5616:c0:m5
@staticmethod<EOL><INDENT>def _map_load_or_error(name_type, name, mappings):<DEDENT>
try:<EOL><INDENT>return mappings[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise JceTransformationError('<STR_LIT>'.format(type=name_type, name=name))<EOL><DEDENT>
Load the requested name from mapping or raise an appropriate error. :param str name_type: Type of thing to load. This is used in the error message if name is not found in mappings. :param str name: Name to locate in mappings :param dict mappings: Dict in which to look for name
f5616:c0:m6
@classmethod<EOL><INDENT>def from_transformation(cls, cipher_transformation):<DEDENT>
if cipher_transformation == "<STR_LIT>":<EOL><INDENT>return cls.from_transformation("<STR_LIT>")<EOL><DEDENT>if cipher_transformation == "<STR_LIT>":<EOL><INDENT>return cls.from_transformation("<STR_LIT>")<EOL><DEDENT>cipher_transformation_parts = cipher_transformation.split("<STR_LIT:/>")<EOL>if len(cipher_transformation_parts) != <NUM_LIT:3>:<EOL><INDENT>raise JceTransformationError(<EOL>'<STR_LIT>'.format(<EOL>cipher_transformation<EOL>)<EOL>)<EOL><DEDENT>cipher = cls._map_load_or_error("<STR_LIT>", cipher_transformation_parts[<NUM_LIT:0>], JAVA_ENCRYPTION_ALGORITHM)<EOL>mode = cls._map_load_or_error("<STR_LIT>", cipher_transformation_parts[<NUM_LIT:1>], JAVA_MODE)<EOL>padding = cls._map_load_or_error("<STR_LIT>", cipher_transformation_parts[<NUM_LIT:2>], JAVA_PADDING)<EOL>return cls(cipher, mode, padding)<EOL>
Generates an JavaCipher object from the Java transformation. https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Cipher :param str cipher_transformation: Formatted transformation :returns: JavaCipher instance :rtype: JavaCipher
f5616:c0:m7
def load_rsa_key(key, key_type, key_encoding):<EOL>
try:<EOL><INDENT>loader = _RSA_KEY_LOADING[key_type][key_encoding]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(key_type, key_encoding))<EOL><DEDENT>kwargs = dict(data=key, backend=default_backend())<EOL>if key_type is EncryptionKeyType.PRIVATE:<EOL><INDENT>kwargs["<STR_LIT:password>"] = None<EOL><DEDENT>loaded_key = loader(**kwargs)<EOL>if loaded_key.key_size < MinimumKeySizes.RSA.value:<EOL><INDENT>_LOGGER.warning("<STR_LIT>" % MinimumKeySizes.RSA.value)<EOL><DEDENT>return loaded_key<EOL>
Load an RSA key object from the provided raw key bytes. :param bytes key: Raw key bytes to load :param EncryptionKeyType key_type: Type of key to load :param KeyEncodingType key_encoding: Encoding used to serialize ``key`` :returns: Loaded key :rtype: TODO: :raises ValueError: if ``key_type`` and ``key_encoding`` are not a valid pairing
f5617:m0
def padder(self):
return self._NoPadder()<EOL>
Return NoPadder object. :returns: NoPadder object. :rtype: _NoPadder
f5617:c0:m0
def unpadder(self):
return self._NoPadder()<EOL>
Return NoPadder object. :returns: NoPadder object. :rtype: _NoPadder
f5617:c0:m1
@abc.abstractmethod<EOL><INDENT>def build(self, block_size):<DEDENT>
Build an instance of this padding type.
f5617:c1:m0
def build(self, block_size=None):<EOL>
return self.padding()<EOL>
Build an instance of this padding type. :param int block_size: Not used by SimplePadding. Ignored and not required. :returns: Padding instance
f5617:c2:m1
def build(self, block_size):<EOL>
return self.padding(block_size)<EOL>
Build an instance of this padding type. :param int block_size: Block size of algorithm for which to build padder. :returns: Padding instance
f5617:c3:m1
def build(self, block_size=None):<EOL>
return self.padding(mgf=self.mgf(algorithm=self.mgf_digest()), algorithm=self.digest(), label=None)<EOL>
Build an instance of this padding type. :param int block_size: Not used by OaepPadding. Ignored and not required. :returns: Padding instance
f5617:c4:m1
def build(self, iv):<EOL>
return self.mode(iv)<EOL>
Build an instance of this mode type. :param bytes iv: Initialization vector bytes :returns: Mode instance
f5617:c5:m1
def __attrs_post_init__(self):
No-op stub to standardize API.
f5617:c6:m1
def validate_algorithm(self, algorithm):<EOL>
if not algorithm == self.java_name:<EOL><INDENT>raise InvalidAlgorithmError(<EOL>'<STR_LIT>'.format(<EOL>requested=algorithm, actual=self.java_name<EOL>)<EOL>)<EOL><DEDENT>
Determine whether the requested algorithm name is compatible with this cipher
f5617:c6:m2
def _disabled_encrypt(self, *args, **kwargs):
raise NotImplementedError('<STR_LIT>'.format(self.java_name))<EOL>
Catcher for algorithms that do not support encryption.
f5617:c7:m0
def _disabled_decrypt(self, *args, **kwargs):
raise NotImplementedError('<STR_LIT>'.format(self.java_name))<EOL>
Catcher for algorithms that do not support decryption.
f5617:c7:m1
def _disable_encryption(self):<EOL>
self.encrypt = self._disabled_encrypt<EOL>self.decrypt = self._disabled_decrypt<EOL>
Enable encryption methods for ciphers that support them.
f5617:c7:m2
def __attrs_post_init__(self):<EOL>
if self.java_name == "<STR_LIT>":<EOL><INDENT>self._disable_encryption()<EOL><DEDENT>
Disable encryption if algorithm is AESWrap.
f5617:c7:m3
def load_key(self, key, key_type, key_encoding):
if key_type is not EncryptionKeyType.SYMMETRIC:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(key_type=key_type, cipher=self.java_name)<EOL>)<EOL><DEDENT>if key_encoding is not KeyEncodingType.RAW:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>key_encoding=key_encoding, cipher=self.java_name<EOL>)<EOL>)<EOL><DEDENT>return key<EOL>
Load a key from bytes. :param bytes key: Key bytes :param EncryptionKeyType key_type: Type of key :param KeyEncodingType key_encoding: Encoding used to serialize key :returns: Loaded key
f5617:c7:m4
def wrap(self, wrapping_key, key_to_wrap):<EOL>
if self.java_name not in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>raise NotImplementedError('<STR_LIT>'.format(self.java_name))<EOL><DEDENT>try:<EOL><INDENT>return keywrap.aes_key_wrap(wrapping_key=wrapping_key, key_to_wrap=key_to_wrap, backend=default_backend())<EOL><DEDENT>except Exception:<EOL><INDENT>error_message = "<STR_LIT>"<EOL>_LOGGER.exception(error_message)<EOL>raise WrappingError(error_message)<EOL><DEDENT>
Wrap key using AES keywrap. :param bytes wrapping_key: Loaded key with which to wrap :param bytes key_to_wrap: Raw key to wrap :returns: Wrapped key :rtype: bytes
f5617:c7:m5
def unwrap(self, wrapping_key, wrapped_key):<EOL>
if self.java_name not in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>return keywrap.aes_key_unwrap(wrapping_key=wrapping_key, wrapped_key=wrapped_key, backend=default_backend())<EOL><DEDENT>except Exception:<EOL><INDENT>error_message = "<STR_LIT>"<EOL>_LOGGER.exception(error_message)<EOL>raise UnwrappingError(error_message)<EOL><DEDENT>
Unwrap key using AES keywrap. :param bytes wrapping_key: Loaded key with which to unwrap :param bytes wrapped_key: Wrapped key to unwrap :returns: Unwrapped key :rtype: bytes
f5617:c7:m6
def encrypt(self, key, data, mode, padding):<EOL>
try:<EOL><INDENT>block_size = self.cipher.block_size<EOL>iv_len = block_size // <NUM_LIT:8><EOL>iv = os.urandom(iv_len)<EOL>encryptor = Cipher(self.cipher(key), mode.build(iv), backend=default_backend()).encryptor()<EOL>padder = padding.build(block_size).padder()<EOL>padded_data = padder.update(data) + padder.finalize()<EOL>return iv + encryptor.update(padded_data) + encryptor.finalize()<EOL><DEDENT>except Exception:<EOL><INDENT>error_message = "<STR_LIT>"<EOL>_LOGGER.exception(error_message)<EOL>raise EncryptionError(error_message)<EOL><DEDENT>
Encrypt data using the supplied values. :param bytes key: Loaded encryption key :param bytes data: Data to encrypt :param JavaMode mode: Encryption mode to use :param JavaPadding padding: Padding mode to use :returns: IV prepended to encrypted data :rtype: bytes
f5617:c7:m7
def decrypt(self, key, data, mode, padding):<EOL>
try:<EOL><INDENT>block_size = self.cipher.block_size<EOL>iv_len = block_size // <NUM_LIT:8><EOL>iv = data[:iv_len]<EOL>data = data[iv_len:]<EOL>decryptor = Cipher(self.cipher(key), mode.build(iv), backend=default_backend()).decryptor()<EOL>decrypted_data = decryptor.update(data) + decryptor.finalize()<EOL>unpadder = padding.build(block_size).unpadder()<EOL>return unpadder.update(decrypted_data) + unpadder.finalize()<EOL><DEDENT>except Exception:<EOL><INDENT>error_message = "<STR_LIT>"<EOL>_LOGGER.exception(error_message)<EOL>raise DecryptionError(error_message)<EOL><DEDENT>
Decrypt data using the supplied values. :param bytes key: Loaded decryption key :param bytes data: IV prepended to encrypted data :param JavaMode mode: Decryption mode to use :param JavaPadding padding: Padding mode to use :returns: Decrypted data :rtype: bytes
f5617:c7:m8
def load_key(self, key, key_type, key_encoding):
if key_type not in (EncryptionKeyType.PRIVATE, EncryptionKeyType.PUBLIC):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(key_type=key_type, cipher=self.java_name)<EOL>)<EOL><DEDENT>if key_encoding not in (KeyEncodingType.DER, KeyEncodingType.PEM):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>key_encoding=key_encoding, cipher=self.java_name<EOL>)<EOL>)<EOL><DEDENT>return _KEY_LOADERS[self.cipher](key, key_type, key_encoding)<EOL>
Load a key from bytes. :param bytes key: Key bytes :param EncryptionKeyType key_type: Type of key :param KeyEncodingType key_encoding: Encoding used to serialize key :returns: Loaded key
f5617:c8:m0
def encrypt(self, key, data, mode, padding):<EOL>
if hasattr(key, "<STR_LIT>"):<EOL><INDENT>_key = key.public_key()<EOL><DEDENT>else:<EOL><INDENT>_key = key<EOL><DEDENT>try:<EOL><INDENT>return _key.encrypt(data, padding.build())<EOL><DEDENT>except Exception:<EOL><INDENT>error_message = "<STR_LIT>"<EOL>_LOGGER.exception(error_message)<EOL>raise EncryptionError(error_message)<EOL><DEDENT>
Encrypt data using the supplied values. :param bytes key: Loaded encryption key :param bytes data: Data to encrypt :param JavaMode mode: Encryption mode to use (not used by :class:`JavaAsymmetricEncryptionAlgorithm`) :param JavaPadding padding: Padding mode to use :returns: Encrypted data :rtype: bytes
f5617:c8:m1
def decrypt(self, key, data, mode, padding):<EOL>
if hasattr(key, "<STR_LIT>"):<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>return key.decrypt(data, padding.build())<EOL><DEDENT>except Exception:<EOL><INDENT>error_message = "<STR_LIT>"<EOL>_LOGGER.exception(error_message)<EOL>raise DecryptionError(error_message)<EOL><DEDENT>
Decrypt data using the supplied values. :param bytes key: Loaded decryption key :param bytes data: IV prepended to encrypted data :param JavaMode mode: Decryption mode to use (not used by :class:`JavaAsymmetricEncryptionAlgorithm`) :param JavaPadding padding: Padding mode to use :returns: Decrypted data :rtype: bytes
f5617:c8:m2
def validate_get_arguments(kwargs):<EOL>
for arg in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>if arg in kwargs:<EOL><INDENT>raise InvalidArgumentError('<STR_LIT>'.format(arg))<EOL><DEDENT><DEDENT>if kwargs.get("<STR_LIT>", None) in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>raise InvalidArgumentError('<STR_LIT>'.format(kwargs["<STR_LIT>"]))<EOL><DEDENT>
Verify that attribute filtering parameters are not found in the request. :raises InvalidArgumentError: if banned parameters are found
f5621:m0
def crypto_config_from_kwargs(fallback, **kwargs):
try:<EOL><INDENT>crypto_config = kwargs.pop("<STR_LIT>")<EOL><DEDENT>except KeyError:<EOL><INDENT>try:<EOL><INDENT>fallback_kwargs = {"<STR_LIT>": kwargs["<STR_LIT>"]}<EOL><DEDENT>except KeyError:<EOL><INDENT>fallback_kwargs = {}<EOL><DEDENT>crypto_config = fallback(**fallback_kwargs)<EOL><DEDENT>return crypto_config, kwargs<EOL>
Pull all encryption-specific parameters from the request and use them to build a crypto config. :returns: crypto config and updated kwargs :rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict
f5621:m1
def crypto_config_from_table_info(materials_provider, attribute_actions, table_info):
ec_kwargs = table_info.encryption_context_values<EOL>if table_info.primary_index is not None:<EOL><INDENT>ec_kwargs.update(<EOL>{"<STR_LIT>": table_info.primary_index.partition, "<STR_LIT>": table_info.primary_index.sort}<EOL>)<EOL><DEDENT>return CryptoConfig(<EOL>materials_provider=materials_provider,<EOL>encryption_context=EncryptionContext(**ec_kwargs),<EOL>attribute_actions=attribute_actions,<EOL>)<EOL>
Build a crypto config from the provided values and table info. :returns: crypto config and updated kwargs :rtype: tuple(CryptoConfig, dict)
f5621:m2
def crypto_config_from_cache(materials_provider, attribute_actions, table_info_cache, table_name):
table_info = table_info_cache.table_info(table_name)<EOL>attribute_actions = attribute_actions.copy()<EOL>attribute_actions.set_index_keys(*table_info.protected_index_keys())<EOL>return crypto_config_from_table_info(materials_provider, attribute_actions, table_info)<EOL>
Build a crypto config from the provided values, loading the table info from the provided cache. :returns: crypto config and updated kwargs :rtype: tuple(CryptoConfig, dict)
f5621:m3
def _item_transformer(crypto_transformer):
if crypto_transformer in (decrypt_python_item, encrypt_python_item):<EOL><INDENT>return dict_to_ddb<EOL><DEDENT>return lambda x: x<EOL>
Supply an item transformer to go from an item that the provided ``crypto_transformer`` can understand to a DynamoDB JSON object. :param crypto_transformer: An item encryptor or decryptor function :returns: Item transformer function
f5621:m4
def decrypt_multi_get(decrypt_method, crypto_config_method, read_method, **kwargs):<EOL>
validate_get_arguments(kwargs)<EOL>crypto_config, ddb_kwargs = crypto_config_method(**kwargs)<EOL>response = read_method(**ddb_kwargs)<EOL>for pos in range(len(response["<STR_LIT>"])):<EOL><INDENT>response["<STR_LIT>"][pos] = decrypt_method(<EOL>item=response["<STR_LIT>"][pos],<EOL>crypto_config=crypto_config.with_item(_item_transformer(decrypt_method)(response["<STR_LIT>"][pos])),<EOL>)<EOL><DEDENT>return response<EOL>
Transparently decrypt multiple items after getting them from the table with a scan or query method. :param callable decrypt_method: Method to use to decrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict
f5621:m5
def decrypt_get_item(decrypt_method, crypto_config_method, read_method, **kwargs):<EOL>
validate_get_arguments(kwargs)<EOL>crypto_config, ddb_kwargs = crypto_config_method(**kwargs)<EOL>response = read_method(**ddb_kwargs)<EOL>if "<STR_LIT>" in response:<EOL><INDENT>response["<STR_LIT>"] = decrypt_method(<EOL>item=response["<STR_LIT>"],<EOL>crypto_config=crypto_config.with_item(_item_transformer(decrypt_method)(response["<STR_LIT>"])),<EOL>)<EOL><DEDENT>return response<EOL>
Transparently decrypt an item after getting it from the table. :param callable decrypt_method: Method to use to decrypt item :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict
f5621:m6
def decrypt_batch_get_item(decrypt_method, crypto_config_method, read_method, **kwargs):<EOL>
request_crypto_config = kwargs.pop("<STR_LIT>", None)<EOL>for _table_name, table_kwargs in kwargs["<STR_LIT>"].items():<EOL><INDENT>validate_get_arguments(table_kwargs)<EOL><DEDENT>response = read_method(**kwargs)<EOL>for table_name, items in response["<STR_LIT>"].items():<EOL><INDENT>if request_crypto_config is not None:<EOL><INDENT>crypto_config = request_crypto_config<EOL><DEDENT>else:<EOL><INDENT>crypto_config = crypto_config_method(table_name=table_name)<EOL><DEDENT>for pos, value in enumerate(items):<EOL><INDENT>items[pos] = decrypt_method(<EOL>item=value, crypto_config=crypto_config.with_item(_item_transformer(decrypt_method)(items[pos]))<EOL>)<EOL><DEDENT><DEDENT>return response<EOL>
Transparently decrypt multiple items after getting them in a batch request. :param callable decrypt_method: Method to use to decrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict
f5621:m7
def encrypt_put_item(encrypt_method, crypto_config_method, write_method, **kwargs):<EOL>
crypto_config, ddb_kwargs = crypto_config_method(**kwargs)<EOL>ddb_kwargs["<STR_LIT>"] = encrypt_method(<EOL>item=ddb_kwargs["<STR_LIT>"],<EOL>crypto_config=crypto_config.with_item(_item_transformer(encrypt_method)(ddb_kwargs["<STR_LIT>"])),<EOL>)<EOL>return write_method(**ddb_kwargs)<EOL>
Transparently encrypt an item before putting it to the table. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict
f5621:m8
def encrypt_batch_write_item(encrypt_method, crypto_config_method, write_method, **kwargs):<EOL>
request_crypto_config = kwargs.pop("<STR_LIT>", None)<EOL>table_crypto_configs = {}<EOL>plaintext_items = copy.deepcopy(kwargs["<STR_LIT>"])<EOL>for table_name, items in kwargs["<STR_LIT>"].items():<EOL><INDENT>if request_crypto_config is not None:<EOL><INDENT>crypto_config = request_crypto_config<EOL><DEDENT>else:<EOL><INDENT>crypto_config = crypto_config_method(table_name=table_name)<EOL><DEDENT>table_crypto_configs[table_name] = crypto_config<EOL>for pos, value in enumerate(items):<EOL><INDENT>for request_type, item in value.items():<EOL><INDENT>if request_type == "<STR_LIT>":<EOL><INDENT>items[pos][request_type]["<STR_LIT>"] = encrypt_method(<EOL>item=item["<STR_LIT>"],<EOL>crypto_config=crypto_config.with_item(_item_transformer(encrypt_method)(item["<STR_LIT>"])),<EOL>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>response = write_method(**kwargs)<EOL>return _process_batch_write_response(plaintext_items, response, table_crypto_configs)<EOL>
Transparently encrypt multiple items before putting them in a batch request. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts a table name string and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict
f5621:m9
def _process_batch_write_response(request, response, table_crypto_config):<EOL>
try:<EOL><INDENT>unprocessed_items = response["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>return response<EOL><DEDENT>for table_name, unprocessed in unprocessed_items.items():<EOL><INDENT>original_items = request[table_name]<EOL>crypto_config = table_crypto_config[table_name]<EOL>if crypto_config.encryption_context.partition_key_name:<EOL><INDENT>items_match = partial(_item_keys_match, crypto_config)<EOL><DEDENT>else:<EOL><INDENT>items_match = partial(_item_attributes_match, crypto_config)<EOL><DEDENT>for pos, operation in enumerate(unprocessed):<EOL><INDENT>for request_type, item in operation.items():<EOL><INDENT>if request_type != "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>for plaintext_item in original_items:<EOL><INDENT>if plaintext_item.get(request_type) and items_match(<EOL>plaintext_item[request_type]["<STR_LIT>"], item["<STR_LIT>"]<EOL>):<EOL><INDENT>unprocessed[pos] = plaintext_item.copy()<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return response<EOL>
Handle unprocessed items in the response from a transparently encrypted write. :param dict request: The DynamoDB plaintext request dictionary :param dict response: The DynamoDB response from the batch operation :param Dict[Text, CryptoConfig] table_crypto_config: table level CryptoConfig used in encrypting the request items :return: DynamoDB response, with any unprocessed items reverted back to the original plaintext values :rtype: dict
f5621:m10
def _item_keys_match(crypto_config, item1, item2):<EOL>
partition_key_name = crypto_config.encryption_context.partition_key_name<EOL>sort_key_name = crypto_config.encryption_context.sort_key_name<EOL>partition_keys_match = item1[partition_key_name] == item2[partition_key_name]<EOL>if sort_key_name is None:<EOL><INDENT>return partition_keys_match<EOL><DEDENT>return partition_keys_match and item1[sort_key_name] == item2[sort_key_name]<EOL>
Determines whether the values in the primary and sort keys (if they exist) are the same :param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items :param dict item1: The first item to compare :param dict item2: The second item to compare :return: Bool response, True if the key attributes match :rtype: bool
f5621:m11
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item):<EOL>
for name, value in plaintext_item.items():<EOL><INDENT>if crypto_config.attribute_actions.action(name) == CryptoAction.ENCRYPT_AND_SIGN:<EOL><INDENT>continue<EOL><DEDENT>if encrypted_item.get(name) != value:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Determines whether the unencrypted values in the plaintext items attributes are the same as those in the encrypted item. Essentially this uses brute force to cover when we don't know the primary and sort index attribute names, since they can't be encrypted. :param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items :param dict plaintext_item: The plaintext item :param dict encrypted_item: The encrypted item :return: Bool response, True if the unencrypted attributes in the plaintext item match those in the encrypted item :rtype: bool
f5621:m12
def __attrs_post_init__(self):
self._all_tables_info = {}<EOL>
Set up the empty cache.
f5621:c0:m1
def table_info(self, table_name):
try:<EOL><INDENT>return self._all_tables_info[table_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>_table_info = TableInfo(name=table_name)<EOL>if self._auto_refresh_table_indexes:<EOL><INDENT>_table_info.refresh_indexed_attributes(self._client)<EOL><DEDENT>self._all_tables_info[table_name] = _table_info<EOL>return _table_info<EOL><DEDENT>
Collect a TableInfo object for the specified table, creating and adding it to the cache if not already present. :param str table_name: Name of table :returns: TableInfo describing the requested table :rtype: TableInfo
f5621:c0:m2
def to_str(data):
if isinstance(data, bytes):<EOL><INDENT>return codecs.decode(data, TEXT_ENCODING)<EOL><DEDENT>return data<EOL>
Takes an input str or bytes object and returns an equivalent str object. :param data: Input data :type data: str or bytes :returns: Data normalized to str :rtype: str
f5622:m0
def to_bytes(data):
if isinstance(data, six.string_types) and not isinstance(data, bytes):<EOL><INDENT>return codecs.encode(data, TEXT_ENCODING)<EOL><DEDENT>return data<EOL>
Takes an input str or bytes object and returns an equivalent bytes object. :param data: Input data :type data: str or bytes :returns: Data normalized to bytes :rtype: bytes
f5622:m1
def dict_to_ddb(item):<EOL>
serializer = TypeSerializer()<EOL>return {key: serializer.serialize(value) for key, value in item.items()}<EOL>
Converts a native Python dictionary to a raw DynamoDB item. :param dict item: Native item :returns: DynamoDB item :rtype: dict
f5623:m0
def ddb_to_dict(item):<EOL>
deserializer = TypeDeserializer()<EOL>return {key: deserializer.deserialize(value) for key, value in item.items()}<EOL>
Converts a raw DynamoDB item to a native Python dictionary. :param dict item: DynamoDB item :returns: Native item :rtype: dict
f5623:m1
def _validate_attribute_values_are_ddb_items(instance, attribute, value):
for data in value.values():<EOL><INDENT>if len(list(data.values())) != <NUM_LIT:1>:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(attribute.name))<EOL><DEDENT><DEDENT>
Validate that dictionary values in ``value`` match the structure of DynamoDB JSON items. .. note:: We are not trying to validate the full structure of the item with this validator. This is just meant to verify that the values roughly match the correct format.
f5624:m0
def __attrs_post_init__(self):<EOL>
for attribute in ReservedAttributes:<EOL><INDENT>if attribute.value in self.attribute_actions:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(attribute.value))<EOL><DEDENT><DEDENT>_unique_actions = {self.default_action.name}<EOL>_unique_actions.update({action.name for action in self.attribute_actions.values()})<EOL>no_actions = _unique_actions == {CryptoAction.DO_NOTHING.name}<EOL>self.take_no_actions = no_actions<EOL>
Determine if any actions should ever be taken with this configuration and record that for reference.
f5624:c1:m1
def action(self, attribute_name):<EOL>
return self.attribute_actions.get(attribute_name, self.default_action)<EOL>
Determine the correct :class:`CryptoAction` to apply to a supplied attribute based on this config. :param str attribute_name: Attribute for which to determine action
f5624:c1:m2
def copy(self):<EOL>
return AttributeActions(default_action=self.default_action, attribute_actions=self.attribute_actions.copy())<EOL>
Return a new copy of this object.
f5624:c1:m3
def set_index_keys(self, *keys):
for key in keys:<EOL><INDENT>index_action = min(self.action(key), CryptoAction.SIGN_ONLY)<EOL>try:<EOL><INDENT>if self.attribute_actions[key] is not index_action:<EOL><INDENT>raise InvalidArgumentError(<EOL>'<STR_LIT>'.format(key)<EOL>)<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>self.attribute_actions[key] = index_action<EOL><DEDENT><DEDENT>
Set the appropriate action for the specified indexed attribute names. .. warning:: If you have already set a custom action for any of these attributes, this will raise an error. .. code:: Default Action -> Index Key Action DO_NOTHING -> DO_NOTHING SIGN_ONLY -> SIGN_ONLY ENCRYPT_AND_SIGN -> SIGN_ONLY :param str *keys: Attribute names to treat as indexed :raises InvalidArgumentError: if a custom action was previously set for any specified attributes
f5624:c1:m4
def contains_action(self, action):<EOL>
return action is self.default_action or action in self.attribute_actions.values()<EOL>
Determine if the specified action is a possible action from this configuration. :param CryptoAction action: Action to look for
f5624:c1:m5
def __add__(self, other):<EOL>
default_action = self.default_action + other.default_action<EOL>all_attributes = set(self.attribute_actions.keys()).union(set(other.attribute_actions.keys()))<EOL>attribute_actions = {}<EOL>for attribute in all_attributes:<EOL><INDENT>attribute_actions[attribute] = max(self.action(attribute), other.action(attribute))<EOL><DEDENT>return AttributeActions(default_action=default_action, attribute_actions=attribute_actions)<EOL>
Merge two AttributeActions objects into a new instance, applying the dominant action in each discovered case.
f5624:c1:m6
def __attrs_post_init__(self):
self.attributes = set([self.partition]) <EOL>if self.sort is not None:<EOL><INDENT>self.attributes.add(self.sort)<EOL><DEDENT>
Set the ``attributes`` attribute for ease of access later.
f5624:c2:m1
@classmethod<EOL><INDENT>def from_key_schema(cls, key_schema):<EOL><DEDENT>
index = {key["<STR_LIT>"]: key["<STR_LIT>"] for key in key_schema}<EOL>return cls(partition=index["<STR_LIT>"], sort=index.get("<STR_LIT>", None))<EOL>
Build a TableIndex from the key schema returned by DescribeTable. .. code:: [ { "KeyType": "HASH"|"RANGE", "AttributeName": "" }, ] :param list key_schema: KeySchema from DescribeTable response :returns: New TableIndex that describes the provided schema :rtype: TableIndex
f5624:c2:m2
@property<EOL><INDENT>def primary_index(self):<EOL><DEDENT>
if self._primary_index is None:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT>return self._primary_index<EOL>
Return the primary TableIndex. :returns: primary index description :rtype: TableIndex :raises AttributeError: if primary index is unknown
f5624:c3:m1
@property<EOL><INDENT>def secondary_indexes(self):<EOL><DEDENT>
if self._secondary_indexes is None:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT>return self._secondary_indexes<EOL>
Return the primary TableIndex. :returns: secondary index descriptions :rtype: TableIndex :raises AttributeError: if secondary indexes are unknown
f5624:c3:m2
def protected_index_keys(self):<EOL>
return self.primary_index.attributes<EOL>
Provide a set containing the names of all indexed attributes that must not be encrypted.
f5624:c3:m3
@property<EOL><INDENT>def encryption_context_values(self):<EOL><DEDENT>
values = {"<STR_LIT>": self.name}<EOL>if self.primary_index is not None:<EOL><INDENT>values.update(<EOL>{"<STR_LIT>": self.primary_index.partition, "<STR_LIT>": self.primary_index.sort}<EOL>)<EOL><DEDENT>return values<EOL>
Build parameters needed to inform an EncryptionContext constructor about this table. :rtype: dict
f5624:c3:m4
def refresh_indexed_attributes(self, client):
table = client.describe_table(TableName=self.name)["<STR_LIT>"]<EOL>self._primary_index = TableIndex.from_key_schema(table["<STR_LIT>"])<EOL>self._secondary_indexes = []<EOL>for group in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>for index in table[group]:<EOL><INDENT>self._secondary_indexes.append(TableIndex.from_key_schema(index["<STR_LIT>"]))<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Use the provided boto3 DynamoDB client to determine all indexes for this table. :param client: Pre-configured boto3 DynamoDB client :type client: botocore.client.BaseClient
f5624:c3:m5
def _min_capacity_validator(instance, attribute, value):<EOL>
if value < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>
Attrs validator to require that value is at least 1.
f5625:m0
def __attrs_post_init__(self):<EOL>
self._cache_lock = RLock() <EOL>self.clear()<EOL>
Initialize the internal cache.
f5625:c1:m1
def _prune(self):<EOL>
with self._cache_lock:<EOL><INDENT>while len(self._cache) > self.capacity:<EOL><INDENT>self._cache.popitem(last=False)<EOL><DEDENT><DEDENT>
Prunes internal cache until internal cache is within the defined limit.
f5625:c1:m2
def put(self, name, value):<EOL>
with self._cache_lock:<EOL><INDENT>self._cache[name] = value<EOL>self._prune()<EOL><DEDENT>
Add a value to the cache. :param name: Hashable object to identify the value in the cache :param value: Value to add to cache
f5625:c1:m3
def get(self, name):<EOL>
with self._cache_lock:<EOL><INDENT>value = self._cache.pop(name)<EOL>self.put(name, value) <EOL>return value<EOL><DEDENT>
Get a value from the cache. :param name: Object to identify the value in the cache :returns: Value from cache
f5625:c1:m4
def clear(self):<EOL>
_LOGGER.debug("<STR_LIT>")<EOL>with self._cache_lock:<EOL><INDENT>self._cache = OrderedDict()<EOL><DEDENT>
Clear the cache.
f5625:c1:m5
def __attrs_post_init__(self):<EOL>
self._version = None <EOL>self._last_updated = None <EOL>self._lock = Lock() <EOL>self._cache = BasicCache(<NUM_LIT:1000>) <EOL>self.refresh()<EOL>
Initialize the cache.
f5625:c2:m1
def decryption_materials(self, encryption_context):<EOL>
version = self._provider_store.version_from_material_description(encryption_context.material_description)<EOL>try:<EOL><INDENT>_LOGGER.debug("<STR_LIT>", version)<EOL>provider = self._cache.get(version)<EOL><DEDENT>except KeyError:<EOL><INDENT>_LOGGER.debug("<STR_LIT>")<EOL>try:<EOL><INDENT>provider = self._provider_store.provider(self._material_name, version)<EOL><DEDENT>except InvalidVersionError:<EOL><INDENT>_LOGGER.exception("<STR_LIT>")<EOL>raise AttributeError("<STR_LIT>")<EOL><DEDENT><DEDENT>self._cache.put(version, provider)<EOL>return provider.decryption_materials(encryption_context)<EOL>
Return decryption materials. :param EncryptionContext encryption_context: Encryption context for request :raises AttributeError: if no decryption materials are available
f5625:c2:m2
def _ttl_action(self):<EOL>
if self._version is None:<EOL><INDENT>_LOGGER.debug("<STR_LIT>")<EOL>return TtlActions.EXPIRED<EOL><DEDENT>time_since_updated = time.time() - self._last_updated<EOL>if time_since_updated < self._version_ttl:<EOL><INDENT>return TtlActions.LIVE<EOL><DEDENT>elif time_since_updated < self._version_ttl + _GRACE_PERIOD:<EOL><INDENT>return TtlActions.GRACE_PERIOD<EOL><DEDENT>_LOGGER.debug("<STR_LIT>")<EOL>return TtlActions.EXPIRED<EOL>
Determine the correct action to take based on the local resources and TTL. :returns: decision :rtype: TtlActions
f5625:c2:m3
def _get_max_version(self):<EOL>
try:<EOL><INDENT>return self._provider_store.max_version(self._material_name)<EOL><DEDENT>except NoKnownVersionError:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>
Ask the provider store for the most recent version of this material. :returns: Latest version in the provider store (0 if not found) :rtype: int
f5625:c2:m4
def _get_provider(self, version):<EOL>
try:<EOL><INDENT>return self._provider_store.get_or_create_provider(self._material_name, version)<EOL><DEDENT>except InvalidVersionError:<EOL><INDENT>_LOGGER.exception("<STR_LIT>")<EOL>raise AttributeError("<STR_LIT>")<EOL><DEDENT>
Ask the provider for a specific version of this material. :param int version: Version to request :returns: Cryptographic materials provider for the requested version :rtype: CryptographicMaterialsProvider :raises AttributeError: if provider could not locate version
f5625:c2:m5
def _get_most_recent_version(self, allow_local):<EOL>
acquired = self._lock.acquire(not allow_local)<EOL>if not acquired:<EOL><INDENT>_LOGGER.debug("<STR_LIT>")<EOL>version = self._version<EOL>return self._cache.get(version)<EOL><DEDENT>try:<EOL><INDENT>max_version = self._get_max_version()<EOL>try:<EOL><INDENT>provider = self._cache.get(max_version)<EOL><DEDENT>except KeyError:<EOL><INDENT>provider = self._get_provider(max_version)<EOL><DEDENT>received_version = self._provider_store.version_from_material_description(provider._material_description)<EOL>_LOGGER.debug("<STR_LIT>", received_version)<EOL>self._version = received_version<EOL>self._last_updated = time.time()<EOL>self._cache.put(received_version, provider)<EOL><DEDENT>finally:<EOL><INDENT>self._lock.release()<EOL><DEDENT>_LOGGER.debug("<STR_LIT>", self._version)<EOL>return provider<EOL>
Get the most recent version of the provider. If allowing local and we cannot obtain the lock, just return the most recent local version. Otherwise, wait for the lock and ask the provider store for the most recent version of the provider. :param bool allow_local: Should we allow returning the local version if we cannot obtain the lock? :returns: version and corresponding cryptographic materials provider :rtype: CryptographicMaterialsProvider
f5625:c2:m6
def encryption_materials(self, encryption_context):<EOL>
ttl_action = self._ttl_action()<EOL>_LOGGER.debug('<STR_LIT>', ttl_action.name)<EOL>provider = None<EOL>if ttl_action is TtlActions.LIVE:<EOL><INDENT>try:<EOL><INDENT>_LOGGER.debug("<STR_LIT>", self._version)<EOL>provider = self._cache.get(self._version)<EOL><DEDENT>except KeyError:<EOL><INDENT>_LOGGER.debug("<STR_LIT>")<EOL>ttl_action = TtlActions.EXPIRED<EOL><DEDENT><DEDENT>if provider is None:<EOL><INDENT>allow_local = bool(ttl_action is TtlActions.GRACE_PERIOD)<EOL>_LOGGER.debug("<STR_LIT>")<EOL>provider = self._get_most_recent_version(allow_local)<EOL><DEDENT>return provider.encryption_materials(encryption_context)<EOL>
Return encryption materials. :param EncryptionContext encryption_context: Encryption context for request :raises AttributeError: if no encryption materials are available
f5625:c2:m7
def refresh(self):<EOL>
_LOGGER.debug("<STR_LIT>")<EOL>with self._lock:<EOL><INDENT>self._cache.clear()<EOL>self._version = None <EOL>self._last_updated = None<EOL><DEDENT>
Clear all local caches for this provider.
f5625:c2:m8
def _build_materials(self, encryption_context):<EOL>
material_description = self._material_description.copy()<EOL>material_description.update(encryption_context.material_description)<EOL>return WrappedCryptographicMaterials(<EOL>wrapping_key=self._wrapping_key,<EOL>unwrapping_key=self._unwrapping_key,<EOL>signing_key=self._signing_key,<EOL>material_description=material_description,<EOL>)<EOL>
Construct :param EncryptionContext encryption_context: Encryption context for request :returns: Wrapped cryptographic materials :rtype: WrappedCryptographicMaterials
f5626:c0:m1
def encryption_materials(self, encryption_context):<EOL>
if self._wrapping_key is None:<EOL><INDENT>raise WrappingError("<STR_LIT>")<EOL><DEDENT>return self._build_materials(encryption_context)<EOL>
Provide encryption materials. :param EncryptionContext encryption_context: Encryption context for request :returns: Encryption materials :rtype: WrappedCryptographicMaterials :raises WrappingError: if no wrapping key is available
f5626:c0:m2
def decryption_materials(self, encryption_context):<EOL>
if self._unwrapping_key is None:<EOL><INDENT>raise UnwrappingError("<STR_LIT>")<EOL><DEDENT>return self._build_materials(encryption_context)<EOL>
Provide decryption materials. :param EncryptionContext encryption_context: Encryption context for request :returns: Decryption materials :rtype: WrappedCryptographicMaterials :raises UnwrappingError: if no unwrapping key is available
f5626:c0:m3
@classmethod<EOL><INDENT>def from_description(cls, description, default_key_length=None):<EOL><DEDENT>
description_parts = description.split("<STR_LIT:/>", <NUM_LIT:1>)<EOL>algorithm = description_parts[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>key_length = int(description_parts[<NUM_LIT:1>])<EOL><DEDENT>except IndexError:<EOL><INDENT>if default_key_length is None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>description<EOL>)<EOL>)<EOL><DEDENT>key_length = default_key_length<EOL><DEDENT>return cls(description, algorithm, key_length)<EOL>
Load key info from key info description. :param str description: Key info description :param int default_key_length: Key length to use if not found in description
f5627:c2:m1
@classmethod<EOL><INDENT>def from_material_description(cls, material_description, description_key, default_algorithm, default_key_length):<EOL><DEDENT>
description = material_description.get(description_key, default_algorithm)<EOL>return cls.from_description(description, default_key_length)<EOL>
Load key info from material description. :param dict material_description: Material description to read :param str description_key: Material description key containing desired key info description :param str default_algorithm: Algorithm name to use if not found in material description :param int default_key_length: Key length to use if not found in key info description :returns: Key info loaded from material description, with defaults applied if necessary :rtype: KeyInfo
f5627:c2:m2
def __attrs_post_init__(self):<EOL>
self._user_agent_adding_config = botocore.config.Config( <EOL>user_agent_extra=USER_AGENT_SUFFIX<EOL>)<EOL>self._content_key_info = KeyInfo.from_material_description( <EOL>material_description=self._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>self._signing_key_info = KeyInfo.from_material_description( <EOL>material_description=self._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>self._regional_clients = (<EOL>{}<EOL>)<EOL>
Load the content and signing key info.
f5627:c3:m1
def _add_regional_client(self, region_name):<EOL>
if region_name not in self._regional_clients:<EOL><INDENT>self._regional_clients[region_name] = boto3.session.Session(<EOL>region_name=region_name, botocore_session=self._botocore_session<EOL>).client("<STR_LIT>", config=self._user_agent_adding_config)<EOL><DEDENT>return self._regional_clients[region_name]<EOL>
Adds a regional client for the specified region if it does not already exist. :param str region_name: AWS Region ID (ex: us-east-1)
f5627:c3:m2
def _client(self, key_id):
try:<EOL><INDENT>key_region = key_id.split("<STR_LIT::>", <NUM_LIT:4>)[<NUM_LIT:3>]<EOL>region = key_region<EOL><DEDENT>except IndexError:<EOL><INDENT>session_region = self._botocore_session.get_config_variable("<STR_LIT>")<EOL>if session_region is None:<EOL><INDENT>raise UnknownRegionError(<EOL>"<STR_LIT>".format(key_id)<EOL>)<EOL><DEDENT>region = session_region<EOL><DEDENT>return self._add_regional_client(region)<EOL>
Returns a boto3 KMS client for the appropriate region. :param str key_id: KMS CMK ID :returns: Boto3 KMS client for requested key id :rtype: botocore.client.KMS
f5627:c3:m3
def _select_key_id(self, encryption_context):<EOL>
return self._key_id<EOL>
Select the desired key id. .. note:: Default behavior is to use the key id provided on creation, but this method provides an extension point for a CMP that might select a different key id based on the encryption context. :param EncryptionContext encryption_context: Encryption context providing information about request :returns: Key id to use :rtype: str
f5627:c3:m4
def _validate_key_id(self, key_id, encryption_context):<EOL>
Validate the selected key id. .. note:: Default behavior is to do nothing, but this method provides an extension point for a CMP that overrides ``_select_key_id`` or otherwise wants to validate a key id before it is used. :param EncryptionContext encryption_context: Encryption context providing information about request
f5627:c3:m5
def _attribute_to_value(self, attribute):<EOL>
attribute_type, attribute_value = list(attribute.items())[<NUM_LIT:0>]<EOL>if attribute_type == "<STR_LIT:B>":<EOL><INDENT>return base64.b64encode(attribute_value).decode(TEXT_ENCODING)<EOL><DEDENT>if attribute_type in ("<STR_LIT:S>", "<STR_LIT:N>"):<EOL><INDENT>return attribute_value<EOL><DEDENT>raise ValueError('<STR_LIT>'.format(attribute_type))<EOL>
Convert a DynamoDB attribute to a value that can be added to the KMS encryption context. :param dict attribute: Attribute to convert :returns: value from attribute, ready to be addd to the KMS encryption context :rtype: str
f5627:c3:m6
def _kms_encryption_context(self, encryption_context, encryption_description, signing_description):<EOL>
kms_encryption_context = {<EOL>EncryptionContextKeys.CONTENT_ENCRYPTION_ALGORITHM.value: encryption_description,<EOL>EncryptionContextKeys.SIGNATURE_ALGORITHM.value: signing_description,<EOL>}<EOL>if encryption_context.partition_key_name is not None:<EOL><INDENT>try:<EOL><INDENT>partition_key_attribute = encryption_context.attributes[encryption_context.partition_key_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>kms_encryption_context[encryption_context.partition_key_name] = self._attribute_to_value(<EOL>partition_key_attribute<EOL>)<EOL><DEDENT><DEDENT>if encryption_context.sort_key_name is not None:<EOL><INDENT>try:<EOL><INDENT>sort_key_attribute = encryption_context.attributes[encryption_context.sort_key_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>kms_encryption_context[encryption_context.sort_key_name] = self._attribute_to_value(sort_key_attribute)<EOL><DEDENT><DEDENT>if encryption_context.table_name is not None:<EOL><INDENT>kms_encryption_context[_TABLE_NAME_EC_KEY] = encryption_context.table_name<EOL><DEDENT>return kms_encryption_context<EOL>
Build the KMS encryption context from the encryption context and key descriptions. :param EncryptionContext encryption_context: Encryption context providing information about request :param str encryption_description: Description value from encryption KeyInfo :param str signing_description: Description value from signing KeyInfo :returns: KMS encryption context for use in request :rtype: dict
f5627:c3:m7
def _generate_initial_material(self, encryption_context):<EOL>
key_id = self._select_key_id(encryption_context)<EOL>self._validate_key_id(key_id, encryption_context)<EOL>key_length = <NUM_LIT> // <NUM_LIT:8><EOL>kms_encryption_context = self._kms_encryption_context(<EOL>encryption_context=encryption_context,<EOL>encryption_description=self._content_key_info.description,<EOL>signing_description=self._signing_key_info.description,<EOL>)<EOL>kms_params = dict(KeyId=key_id, NumberOfBytes=key_length, EncryptionContext=kms_encryption_context)<EOL>if self._grant_tokens:<EOL><INDENT>kms_params["<STR_LIT>"] = self._grant_tokens<EOL><DEDENT>try:<EOL><INDENT>response = self._client(key_id).generate_data_key(**kms_params)<EOL>return response["<STR_LIT>"], response["<STR_LIT>"]<EOL><DEDENT>except (botocore.exceptions.ClientError, KeyError):<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise WrappingError(message)<EOL><DEDENT>
Generate the initial cryptographic material for use with HKDF. :param EncryptionContext encryption_context: Encryption context providing information about request :returns: Plaintext and ciphertext of initial cryptographic material :rtype: bytes and bytes
f5627:c3:m8
def _decrypt_initial_material(self, encryption_context):<EOL>
key_id = self._select_key_id(encryption_context)<EOL>self._validate_key_id(key_id, encryption_context)<EOL>kms_encryption_context = self._kms_encryption_context(<EOL>encryption_context=encryption_context,<EOL>encryption_description=encryption_context.material_description.get(<EOL>MaterialDescriptionKeys.CONTENT_ENCRYPTION_ALGORITHM.value<EOL>),<EOL>signing_description=encryption_context.material_description.get(<EOL>MaterialDescriptionKeys.ITEM_SIGNATURE_ALGORITHM.value<EOL>),<EOL>)<EOL>encrypted_initial_material = base64.b64decode(<EOL>to_bytes(encryption_context.material_description.get(MaterialDescriptionKeys.WRAPPED_DATA_KEY.value))<EOL>)<EOL>kms_params = dict(CiphertextBlob=encrypted_initial_material, EncryptionContext=kms_encryption_context)<EOL>if self._grant_tokens:<EOL><INDENT>kms_params["<STR_LIT>"] = self._grant_tokens<EOL><DEDENT>try:<EOL><INDENT>response = self._client(key_id).decrypt(**kms_params)<EOL>return response["<STR_LIT>"]<EOL><DEDENT>except (botocore.exceptions.ClientError, KeyError):<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise UnwrappingError(message)<EOL><DEDENT>
Decrypt an encrypted initial cryptographic material value. :param encryption_context: Encryption context providing information about request :type encryption_context: EncryptionContext :returns: Plaintext of initial cryptographic material :rtype: bytes
f5627:c3:m9
def _hkdf(self, initial_material, key_length, info):<EOL>
hkdf = HKDF(algorithm=hashes.SHA256(), length=key_length, salt=None, info=info, backend=default_backend())<EOL>return hkdf.derive(initial_material)<EOL>
Use HKDF to derive a key. :param bytes initial_material: Initial material to use with HKDF :param int key_length: Length of key to derive :param str info: Info value to use in HKDF calculate :returns: Derived key material :rtype: bytes
f5627:c3:m10
def _derive_delegated_key(self, initial_material, key_info, hkdf_info):<EOL>
raw_key = self._hkdf(initial_material, key_info.length // <NUM_LIT:8>, hkdf_info.value)<EOL>return JceNameLocalDelegatedKey(<EOL>key=raw_key,<EOL>algorithm=key_info.algorithm,<EOL>key_type=EncryptionKeyType.SYMMETRIC,<EOL>key_encoding=KeyEncodingType.RAW,<EOL>)<EOL>
Derive the raw key and use it to build a JceNameLocalDelegatedKey. :param bytes initial_material: Initial material to use with KDF :param KeyInfo key_info: Key information to use to calculate encryption key :param HkdfInfo hkdf_info: Info to use in HKDF calculation :returns: Delegated key to use for encryption and decryption :rtype: JceNameLocalDelegatedKey
f5627:c3:m11