repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/caches/__init__.py | _encrypted_data_keys_hash | def _encrypted_data_keys_hash(hasher, encrypted_data_keys):
"""Generates the expected hash for the provided encrypted data keys.
:param hasher: Existing hasher to use
:type hasher: cryptography.hazmat.primitives.hashes.Hash
:param iterable encrypted_data_keys: Encrypted data keys to hash
:returns: Concatenated, sorted, list of all hashes
:rtype: bytes
"""
hashed_keys = []
for edk in encrypted_data_keys:
serialized_edk = serialize_encrypted_data_key(edk)
_hasher = hasher.copy()
_hasher.update(serialized_edk)
hashed_keys.append(_hasher.finalize())
return b"".join(sorted(hashed_keys)) | python | def _encrypted_data_keys_hash(hasher, encrypted_data_keys):
"""Generates the expected hash for the provided encrypted data keys.
:param hasher: Existing hasher to use
:type hasher: cryptography.hazmat.primitives.hashes.Hash
:param iterable encrypted_data_keys: Encrypted data keys to hash
:returns: Concatenated, sorted, list of all hashes
:rtype: bytes
"""
hashed_keys = []
for edk in encrypted_data_keys:
serialized_edk = serialize_encrypted_data_key(edk)
_hasher = hasher.copy()
_hasher.update(serialized_edk)
hashed_keys.append(_hasher.finalize())
return b"".join(sorted(hashed_keys)) | [
"def",
"_encrypted_data_keys_hash",
"(",
"hasher",
",",
"encrypted_data_keys",
")",
":",
"hashed_keys",
"=",
"[",
"]",
"for",
"edk",
"in",
"encrypted_data_keys",
":",
"serialized_edk",
"=",
"serialize_encrypted_data_key",
"(",
"edk",
")",
"_hasher",
"=",
"hasher",
".",
"copy",
"(",
")",
"_hasher",
".",
"update",
"(",
"serialized_edk",
")",
"hashed_keys",
".",
"append",
"(",
"_hasher",
".",
"finalize",
"(",
")",
")",
"return",
"b\"\"",
".",
"join",
"(",
"sorted",
"(",
"hashed_keys",
")",
")"
] | Generates the expected hash for the provided encrypted data keys.
:param hasher: Existing hasher to use
:type hasher: cryptography.hazmat.primitives.hashes.Hash
:param iterable encrypted_data_keys: Encrypted data keys to hash
:returns: Concatenated, sorted, list of all hashes
:rtype: bytes | [
"Generates",
"the",
"expected",
"hash",
"for",
"the",
"provided",
"encrypted",
"data",
"keys",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/caches/__init__.py#L89-L104 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/caches/__init__.py | build_decryption_materials_cache_key | def build_decryption_materials_cache_key(partition, request):
"""Generates a cache key for a decrypt request.
:param bytes partition: Partition name for which to generate key
:param request: Request for which to generate key
:type request: aws_encryption_sdk.materials_managers.DecryptionMaterialsRequest
:returns: cache key
:rtype: bytes
"""
hasher = _new_cache_key_hasher()
_partition_hash = _partition_name_hash(hasher=hasher.copy(), partition_name=partition)
_algorithm_info = request.algorithm.id_as_bytes()
_edks_hash = _encrypted_data_keys_hash(hasher=hasher.copy(), encrypted_data_keys=request.encrypted_data_keys)
_ec_hash = _encryption_context_hash(hasher=hasher.copy(), encryption_context=request.encryption_context)
hasher.update(_partition_hash)
hasher.update(_algorithm_info)
hasher.update(_edks_hash)
hasher.update(_512_BIT_PAD)
hasher.update(_ec_hash)
return hasher.finalize() | python | def build_decryption_materials_cache_key(partition, request):
"""Generates a cache key for a decrypt request.
:param bytes partition: Partition name for which to generate key
:param request: Request for which to generate key
:type request: aws_encryption_sdk.materials_managers.DecryptionMaterialsRequest
:returns: cache key
:rtype: bytes
"""
hasher = _new_cache_key_hasher()
_partition_hash = _partition_name_hash(hasher=hasher.copy(), partition_name=partition)
_algorithm_info = request.algorithm.id_as_bytes()
_edks_hash = _encrypted_data_keys_hash(hasher=hasher.copy(), encrypted_data_keys=request.encrypted_data_keys)
_ec_hash = _encryption_context_hash(hasher=hasher.copy(), encryption_context=request.encryption_context)
hasher.update(_partition_hash)
hasher.update(_algorithm_info)
hasher.update(_edks_hash)
hasher.update(_512_BIT_PAD)
hasher.update(_ec_hash)
return hasher.finalize() | [
"def",
"build_decryption_materials_cache_key",
"(",
"partition",
",",
"request",
")",
":",
"hasher",
"=",
"_new_cache_key_hasher",
"(",
")",
"_partition_hash",
"=",
"_partition_name_hash",
"(",
"hasher",
"=",
"hasher",
".",
"copy",
"(",
")",
",",
"partition_name",
"=",
"partition",
")",
"_algorithm_info",
"=",
"request",
".",
"algorithm",
".",
"id_as_bytes",
"(",
")",
"_edks_hash",
"=",
"_encrypted_data_keys_hash",
"(",
"hasher",
"=",
"hasher",
".",
"copy",
"(",
")",
",",
"encrypted_data_keys",
"=",
"request",
".",
"encrypted_data_keys",
")",
"_ec_hash",
"=",
"_encryption_context_hash",
"(",
"hasher",
"=",
"hasher",
".",
"copy",
"(",
")",
",",
"encryption_context",
"=",
"request",
".",
"encryption_context",
")",
"hasher",
".",
"update",
"(",
"_partition_hash",
")",
"hasher",
".",
"update",
"(",
"_algorithm_info",
")",
"hasher",
".",
"update",
"(",
"_edks_hash",
")",
"hasher",
".",
"update",
"(",
"_512_BIT_PAD",
")",
"hasher",
".",
"update",
"(",
"_ec_hash",
")",
"return",
"hasher",
".",
"finalize",
"(",
")"
] | Generates a cache key for a decrypt request.
:param bytes partition: Partition name for which to generate key
:param request: Request for which to generate key
:type request: aws_encryption_sdk.materials_managers.DecryptionMaterialsRequest
:returns: cache key
:rtype: bytes | [
"Generates",
"a",
"cache",
"key",
"for",
"a",
"decrypt",
"request",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/caches/__init__.py#L111-L131 | train |
aws/aws-encryption-sdk-python | examples/src/basic_file_encryption_with_raw_key_provider.py | cycle_file | def cycle_file(source_plaintext_filename):
"""Encrypts and then decrypts a file under a custom static master key provider.
:param str source_plaintext_filename: Filename of file to encrypt
"""
# Create a static random master key provider
key_id = os.urandom(8)
master_key_provider = StaticRandomMasterKeyProvider()
master_key_provider.add_master_key(key_id)
ciphertext_filename = source_plaintext_filename + ".encrypted"
cycled_plaintext_filename = source_plaintext_filename + ".decrypted"
# Encrypt the plaintext source data
with open(source_plaintext_filename, "rb") as plaintext, open(ciphertext_filename, "wb") as ciphertext:
with aws_encryption_sdk.stream(mode="e", source=plaintext, key_provider=master_key_provider) as encryptor:
for chunk in encryptor:
ciphertext.write(chunk)
# Decrypt the ciphertext
with open(ciphertext_filename, "rb") as ciphertext, open(cycled_plaintext_filename, "wb") as plaintext:
with aws_encryption_sdk.stream(mode="d", source=ciphertext, key_provider=master_key_provider) as decryptor:
for chunk in decryptor:
plaintext.write(chunk)
# Verify that the "cycled" (encrypted, then decrypted) plaintext is identical to the source
# plaintext
assert filecmp.cmp(source_plaintext_filename, cycled_plaintext_filename)
# Verify that the encryption context used in the decrypt operation includes all key pairs from
# the encrypt operation
#
# In production, always use a meaningful encryption context. In this sample, we omit the
# encryption context (no key pairs).
assert all(
pair in decryptor.header.encryption_context.items() for pair in encryptor.header.encryption_context.items()
)
return ciphertext_filename, cycled_plaintext_filename | python | def cycle_file(source_plaintext_filename):
"""Encrypts and then decrypts a file under a custom static master key provider.
:param str source_plaintext_filename: Filename of file to encrypt
"""
# Create a static random master key provider
key_id = os.urandom(8)
master_key_provider = StaticRandomMasterKeyProvider()
master_key_provider.add_master_key(key_id)
ciphertext_filename = source_plaintext_filename + ".encrypted"
cycled_plaintext_filename = source_plaintext_filename + ".decrypted"
# Encrypt the plaintext source data
with open(source_plaintext_filename, "rb") as plaintext, open(ciphertext_filename, "wb") as ciphertext:
with aws_encryption_sdk.stream(mode="e", source=plaintext, key_provider=master_key_provider) as encryptor:
for chunk in encryptor:
ciphertext.write(chunk)
# Decrypt the ciphertext
with open(ciphertext_filename, "rb") as ciphertext, open(cycled_plaintext_filename, "wb") as plaintext:
with aws_encryption_sdk.stream(mode="d", source=ciphertext, key_provider=master_key_provider) as decryptor:
for chunk in decryptor:
plaintext.write(chunk)
# Verify that the "cycled" (encrypted, then decrypted) plaintext is identical to the source
# plaintext
assert filecmp.cmp(source_plaintext_filename, cycled_plaintext_filename)
# Verify that the encryption context used in the decrypt operation includes all key pairs from
# the encrypt operation
#
# In production, always use a meaningful encryption context. In this sample, we omit the
# encryption context (no key pairs).
assert all(
pair in decryptor.header.encryption_context.items() for pair in encryptor.header.encryption_context.items()
)
return ciphertext_filename, cycled_plaintext_filename | [
"def",
"cycle_file",
"(",
"source_plaintext_filename",
")",
":",
"# Create a static random master key provider",
"key_id",
"=",
"os",
".",
"urandom",
"(",
"8",
")",
"master_key_provider",
"=",
"StaticRandomMasterKeyProvider",
"(",
")",
"master_key_provider",
".",
"add_master_key",
"(",
"key_id",
")",
"ciphertext_filename",
"=",
"source_plaintext_filename",
"+",
"\".encrypted\"",
"cycled_plaintext_filename",
"=",
"source_plaintext_filename",
"+",
"\".decrypted\"",
"# Encrypt the plaintext source data",
"with",
"open",
"(",
"source_plaintext_filename",
",",
"\"rb\"",
")",
"as",
"plaintext",
",",
"open",
"(",
"ciphertext_filename",
",",
"\"wb\"",
")",
"as",
"ciphertext",
":",
"with",
"aws_encryption_sdk",
".",
"stream",
"(",
"mode",
"=",
"\"e\"",
",",
"source",
"=",
"plaintext",
",",
"key_provider",
"=",
"master_key_provider",
")",
"as",
"encryptor",
":",
"for",
"chunk",
"in",
"encryptor",
":",
"ciphertext",
".",
"write",
"(",
"chunk",
")",
"# Decrypt the ciphertext",
"with",
"open",
"(",
"ciphertext_filename",
",",
"\"rb\"",
")",
"as",
"ciphertext",
",",
"open",
"(",
"cycled_plaintext_filename",
",",
"\"wb\"",
")",
"as",
"plaintext",
":",
"with",
"aws_encryption_sdk",
".",
"stream",
"(",
"mode",
"=",
"\"d\"",
",",
"source",
"=",
"ciphertext",
",",
"key_provider",
"=",
"master_key_provider",
")",
"as",
"decryptor",
":",
"for",
"chunk",
"in",
"decryptor",
":",
"plaintext",
".",
"write",
"(",
"chunk",
")",
"# Verify that the \"cycled\" (encrypted, then decrypted) plaintext is identical to the source",
"# plaintext",
"assert",
"filecmp",
".",
"cmp",
"(",
"source_plaintext_filename",
",",
"cycled_plaintext_filename",
")",
"# Verify that the encryption context used in the decrypt operation includes all key pairs from",
"# the encrypt operation",
"#",
"# In production, always use a meaningful encryption context. In this sample, we omit the",
"# encryption context (no key pairs).",
"assert",
"all",
"(",
"pair",
"in",
"decryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
"for",
"pair",
"in",
"encryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
")",
"return",
"ciphertext_filename",
",",
"cycled_plaintext_filename"
] | Encrypts and then decrypts a file under a custom static master key provider.
:param str source_plaintext_filename: Filename of file to encrypt | [
"Encrypts",
"and",
"then",
"decrypts",
"a",
"file",
"under",
"a",
"custom",
"static",
"master",
"key",
"provider",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/examples/src/basic_file_encryption_with_raw_key_provider.py#L51-L88 | train |
aws/aws-encryption-sdk-python | examples/src/basic_file_encryption_with_raw_key_provider.py | StaticRandomMasterKeyProvider._get_raw_key | def _get_raw_key(self, key_id):
"""Returns a static, randomly-generated symmetric key for the specified key ID.
:param str key_id: Key ID
:returns: Wrapping key that contains the specified static key
:rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`
"""
try:
static_key = self._static_keys[key_id]
except KeyError:
static_key = os.urandom(32)
self._static_keys[key_id] = static_key
return WrappingKey(
wrapping_algorithm=WrappingAlgorithm.AES_256_GCM_IV12_TAG16_NO_PADDING,
wrapping_key=static_key,
wrapping_key_type=EncryptionKeyType.SYMMETRIC,
) | python | def _get_raw_key(self, key_id):
"""Returns a static, randomly-generated symmetric key for the specified key ID.
:param str key_id: Key ID
:returns: Wrapping key that contains the specified static key
:rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`
"""
try:
static_key = self._static_keys[key_id]
except KeyError:
static_key = os.urandom(32)
self._static_keys[key_id] = static_key
return WrappingKey(
wrapping_algorithm=WrappingAlgorithm.AES_256_GCM_IV12_TAG16_NO_PADDING,
wrapping_key=static_key,
wrapping_key_type=EncryptionKeyType.SYMMETRIC,
) | [
"def",
"_get_raw_key",
"(",
"self",
",",
"key_id",
")",
":",
"try",
":",
"static_key",
"=",
"self",
".",
"_static_keys",
"[",
"key_id",
"]",
"except",
"KeyError",
":",
"static_key",
"=",
"os",
".",
"urandom",
"(",
"32",
")",
"self",
".",
"_static_keys",
"[",
"key_id",
"]",
"=",
"static_key",
"return",
"WrappingKey",
"(",
"wrapping_algorithm",
"=",
"WrappingAlgorithm",
".",
"AES_256_GCM_IV12_TAG16_NO_PADDING",
",",
"wrapping_key",
"=",
"static_key",
",",
"wrapping_key_type",
"=",
"EncryptionKeyType",
".",
"SYMMETRIC",
",",
")"
] | Returns a static, randomly-generated symmetric key for the specified key ID.
:param str key_id: Key ID
:returns: Wrapping key that contains the specified static key
:rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey` | [
"Returns",
"a",
"static",
"randomly",
"-",
"generated",
"symmetric",
"key",
"for",
"the",
"specified",
"key",
"ID",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/examples/src/basic_file_encryption_with_raw_key_provider.py#L32-L48 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | _EncryptionStream.stream_length | def stream_length(self):
"""Returns the length of the source stream, determining it if not already known."""
if self._stream_length is None:
try:
current_position = self.source_stream.tell()
self.source_stream.seek(0, 2)
self._stream_length = self.source_stream.tell()
self.source_stream.seek(current_position, 0)
except Exception as error:
# Catch-all for unknown issues encountered trying to seek for stream length
raise NotSupportedError(error)
return self._stream_length | python | def stream_length(self):
"""Returns the length of the source stream, determining it if not already known."""
if self._stream_length is None:
try:
current_position = self.source_stream.tell()
self.source_stream.seek(0, 2)
self._stream_length = self.source_stream.tell()
self.source_stream.seek(current_position, 0)
except Exception as error:
# Catch-all for unknown issues encountered trying to seek for stream length
raise NotSupportedError(error)
return self._stream_length | [
"def",
"stream_length",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stream_length",
"is",
"None",
":",
"try",
":",
"current_position",
"=",
"self",
".",
"source_stream",
".",
"tell",
"(",
")",
"self",
".",
"source_stream",
".",
"seek",
"(",
"0",
",",
"2",
")",
"self",
".",
"_stream_length",
"=",
"self",
".",
"source_stream",
".",
"tell",
"(",
")",
"self",
".",
"source_stream",
".",
"seek",
"(",
"current_position",
",",
"0",
")",
"except",
"Exception",
"as",
"error",
":",
"# Catch-all for unknown issues encountered trying to seek for stream length",
"raise",
"NotSupportedError",
"(",
"error",
")",
"return",
"self",
".",
"_stream_length"
] | Returns the length of the source stream, determining it if not already known. | [
"Returns",
"the",
"length",
"of",
"the",
"source",
"stream",
"determining",
"it",
"if",
"not",
"already",
"known",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L173-L184 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | _EncryptionStream.read | def read(self, b=-1):
"""Returns either the requested number of bytes or the entire stream.
:param int b: Number of bytes to read
:returns: Processed (encrypted or decrypted) bytes from source stream
:rtype: bytes
"""
# Any negative value for b is interpreted as a full read
# None is also accepted for legacy compatibility
if b is None or b < 0:
b = -1
_LOGGER.debug("Stream read called, requesting %d bytes", b)
output = io.BytesIO()
if not self._message_prepped:
self._prep_message()
if self.closed:
raise ValueError("I/O operation on closed file")
if b >= 0:
self._read_bytes(b)
output.write(self.output_buffer[:b])
self.output_buffer = self.output_buffer[b:]
else:
while True:
line = self.readline()
if not line:
break
output.write(line)
self.bytes_read += output.tell()
_LOGGER.debug("Returning %d bytes of %d bytes requested", output.tell(), b)
return output.getvalue() | python | def read(self, b=-1):
"""Returns either the requested number of bytes or the entire stream.
:param int b: Number of bytes to read
:returns: Processed (encrypted or decrypted) bytes from source stream
:rtype: bytes
"""
# Any negative value for b is interpreted as a full read
# None is also accepted for legacy compatibility
if b is None or b < 0:
b = -1
_LOGGER.debug("Stream read called, requesting %d bytes", b)
output = io.BytesIO()
if not self._message_prepped:
self._prep_message()
if self.closed:
raise ValueError("I/O operation on closed file")
if b >= 0:
self._read_bytes(b)
output.write(self.output_buffer[:b])
self.output_buffer = self.output_buffer[b:]
else:
while True:
line = self.readline()
if not line:
break
output.write(line)
self.bytes_read += output.tell()
_LOGGER.debug("Returning %d bytes of %d bytes requested", output.tell(), b)
return output.getvalue() | [
"def",
"read",
"(",
"self",
",",
"b",
"=",
"-",
"1",
")",
":",
"# Any negative value for b is interpreted as a full read",
"# None is also accepted for legacy compatibility",
"if",
"b",
"is",
"None",
"or",
"b",
"<",
"0",
":",
"b",
"=",
"-",
"1",
"_LOGGER",
".",
"debug",
"(",
"\"Stream read called, requesting %d bytes\"",
",",
"b",
")",
"output",
"=",
"io",
".",
"BytesIO",
"(",
")",
"if",
"not",
"self",
".",
"_message_prepped",
":",
"self",
".",
"_prep_message",
"(",
")",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file\"",
")",
"if",
"b",
">=",
"0",
":",
"self",
".",
"_read_bytes",
"(",
"b",
")",
"output",
".",
"write",
"(",
"self",
".",
"output_buffer",
"[",
":",
"b",
"]",
")",
"self",
".",
"output_buffer",
"=",
"self",
".",
"output_buffer",
"[",
"b",
":",
"]",
"else",
":",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"output",
".",
"write",
"(",
"line",
")",
"self",
".",
"bytes_read",
"+=",
"output",
".",
"tell",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Returning %d bytes of %d bytes requested\"",
",",
"output",
".",
"tell",
"(",
")",
",",
"b",
")",
"return",
"output",
".",
"getvalue",
"(",
")"
] | Returns either the requested number of bytes or the entire stream.
:param int b: Number of bytes to read
:returns: Processed (encrypted or decrypted) bytes from source stream
:rtype: bytes | [
"Returns",
"either",
"the",
"requested",
"number",
"of",
"bytes",
"or",
"the",
"entire",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L220-L254 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | _EncryptionStream.readline | def readline(self):
"""Read a chunk of the output"""
_LOGGER.info("reading line")
line = self.read(self.line_length)
if len(line) < self.line_length:
_LOGGER.info("all lines read")
return line | python | def readline(self):
"""Read a chunk of the output"""
_LOGGER.info("reading line")
line = self.read(self.line_length)
if len(line) < self.line_length:
_LOGGER.info("all lines read")
return line | [
"def",
"readline",
"(",
"self",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"reading line\"",
")",
"line",
"=",
"self",
".",
"read",
"(",
"self",
".",
"line_length",
")",
"if",
"len",
"(",
"line",
")",
"<",
"self",
".",
"line_length",
":",
"_LOGGER",
".",
"info",
"(",
"\"all lines read\"",
")",
"return",
"line"
] | Read a chunk of the output | [
"Read",
"a",
"chunk",
"of",
"the",
"output"
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L276-L282 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | _EncryptionStream.next | def next(self):
"""Provides hook for Python2 iterator functionality."""
_LOGGER.debug("reading next")
if self.closed:
_LOGGER.debug("stream is closed")
raise StopIteration()
line = self.readline()
if not line:
_LOGGER.debug("nothing more to read")
raise StopIteration()
return line | python | def next(self):
"""Provides hook for Python2 iterator functionality."""
_LOGGER.debug("reading next")
if self.closed:
_LOGGER.debug("stream is closed")
raise StopIteration()
line = self.readline()
if not line:
_LOGGER.debug("nothing more to read")
raise StopIteration()
return line | [
"def",
"next",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"reading next\"",
")",
"if",
"self",
".",
"closed",
":",
"_LOGGER",
".",
"debug",
"(",
"\"stream is closed\"",
")",
"raise",
"StopIteration",
"(",
")",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"_LOGGER",
".",
"debug",
"(",
"\"nothing more to read\"",
")",
"raise",
"StopIteration",
"(",
")",
"return",
"line"
] | Provides hook for Python2 iterator functionality. | [
"Provides",
"hook",
"for",
"Python2",
"iterator",
"functionality",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L292-L304 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamEncryptor.ciphertext_length | def ciphertext_length(self):
"""Returns the length of the resulting ciphertext message in bytes.
:rtype: int
"""
return aws_encryption_sdk.internal.formatting.ciphertext_length(
header=self.header, plaintext_length=self.stream_length
) | python | def ciphertext_length(self):
"""Returns the length of the resulting ciphertext message in bytes.
:rtype: int
"""
return aws_encryption_sdk.internal.formatting.ciphertext_length(
header=self.header, plaintext_length=self.stream_length
) | [
"def",
"ciphertext_length",
"(",
"self",
")",
":",
"return",
"aws_encryption_sdk",
".",
"internal",
".",
"formatting",
".",
"ciphertext_length",
"(",
"header",
"=",
"self",
".",
"header",
",",
"plaintext_length",
"=",
"self",
".",
"stream_length",
")"
] | Returns the length of the resulting ciphertext message in bytes.
:rtype: int | [
"Returns",
"the",
"length",
"of",
"the",
"resulting",
"ciphertext",
"message",
"in",
"bytes",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L409-L416 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamEncryptor._write_header | def _write_header(self):
"""Builds the message header and writes it to the output stream."""
self.output_buffer += serialize_header(header=self._header, signer=self.signer)
self.output_buffer += serialize_header_auth(
algorithm=self._encryption_materials.algorithm,
header=self.output_buffer,
data_encryption_key=self._derived_data_key,
signer=self.signer,
) | python | def _write_header(self):
"""Builds the message header and writes it to the output stream."""
self.output_buffer += serialize_header(header=self._header, signer=self.signer)
self.output_buffer += serialize_header_auth(
algorithm=self._encryption_materials.algorithm,
header=self.output_buffer,
data_encryption_key=self._derived_data_key,
signer=self.signer,
) | [
"def",
"_write_header",
"(",
"self",
")",
":",
"self",
".",
"output_buffer",
"+=",
"serialize_header",
"(",
"header",
"=",
"self",
".",
"_header",
",",
"signer",
"=",
"self",
".",
"signer",
")",
"self",
".",
"output_buffer",
"+=",
"serialize_header_auth",
"(",
"algorithm",
"=",
"self",
".",
"_encryption_materials",
".",
"algorithm",
",",
"header",
"=",
"self",
".",
"output_buffer",
",",
"data_encryption_key",
"=",
"self",
".",
"_derived_data_key",
",",
"signer",
"=",
"self",
".",
"signer",
",",
")"
] | Builds the message header and writes it to the output stream. | [
"Builds",
"the",
"message",
"header",
"and",
"writes",
"it",
"to",
"the",
"output",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L484-L492 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamEncryptor._read_bytes_to_non_framed_body | def _read_bytes_to_non_framed_body(self, b):
"""Reads the requested number of bytes from source to a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Encrypted bytes from source stream
:rtype: bytes
"""
_LOGGER.debug("Reading %d bytes", b)
plaintext = self.__unframed_plaintext_cache.read(b)
plaintext_length = len(plaintext)
if self.tell() + len(plaintext) > MAX_NON_FRAMED_SIZE:
raise SerializationError("Source too large for non-framed message")
ciphertext = self.encryptor.update(plaintext)
self._bytes_encrypted += plaintext_length
if self.signer is not None:
self.signer.update(ciphertext)
if len(plaintext) < b:
_LOGGER.debug("Closing encryptor after receiving only %d bytes of %d bytes requested", plaintext_length, b)
closing = self.encryptor.finalize()
if self.signer is not None:
self.signer.update(closing)
closing += serialize_non_framed_close(tag=self.encryptor.tag, signer=self.signer)
if self.signer is not None:
closing += serialize_footer(self.signer)
self.__message_complete = True
return ciphertext + closing
return ciphertext | python | def _read_bytes_to_non_framed_body(self, b):
"""Reads the requested number of bytes from source to a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Encrypted bytes from source stream
:rtype: bytes
"""
_LOGGER.debug("Reading %d bytes", b)
plaintext = self.__unframed_plaintext_cache.read(b)
plaintext_length = len(plaintext)
if self.tell() + len(plaintext) > MAX_NON_FRAMED_SIZE:
raise SerializationError("Source too large for non-framed message")
ciphertext = self.encryptor.update(plaintext)
self._bytes_encrypted += plaintext_length
if self.signer is not None:
self.signer.update(ciphertext)
if len(plaintext) < b:
_LOGGER.debug("Closing encryptor after receiving only %d bytes of %d bytes requested", plaintext_length, b)
closing = self.encryptor.finalize()
if self.signer is not None:
self.signer.update(closing)
closing += serialize_non_framed_close(tag=self.encryptor.tag, signer=self.signer)
if self.signer is not None:
closing += serialize_footer(self.signer)
self.__message_complete = True
return ciphertext + closing
return ciphertext | [
"def",
"_read_bytes_to_non_framed_body",
"(",
"self",
",",
"b",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Reading %d bytes\"",
",",
"b",
")",
"plaintext",
"=",
"self",
".",
"__unframed_plaintext_cache",
".",
"read",
"(",
"b",
")",
"plaintext_length",
"=",
"len",
"(",
"plaintext",
")",
"if",
"self",
".",
"tell",
"(",
")",
"+",
"len",
"(",
"plaintext",
")",
">",
"MAX_NON_FRAMED_SIZE",
":",
"raise",
"SerializationError",
"(",
"\"Source too large for non-framed message\"",
")",
"ciphertext",
"=",
"self",
".",
"encryptor",
".",
"update",
"(",
"plaintext",
")",
"self",
".",
"_bytes_encrypted",
"+=",
"plaintext_length",
"if",
"self",
".",
"signer",
"is",
"not",
"None",
":",
"self",
".",
"signer",
".",
"update",
"(",
"ciphertext",
")",
"if",
"len",
"(",
"plaintext",
")",
"<",
"b",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Closing encryptor after receiving only %d bytes of %d bytes requested\"",
",",
"plaintext_length",
",",
"b",
")",
"closing",
"=",
"self",
".",
"encryptor",
".",
"finalize",
"(",
")",
"if",
"self",
".",
"signer",
"is",
"not",
"None",
":",
"self",
".",
"signer",
".",
"update",
"(",
"closing",
")",
"closing",
"+=",
"serialize_non_framed_close",
"(",
"tag",
"=",
"self",
".",
"encryptor",
".",
"tag",
",",
"signer",
"=",
"self",
".",
"signer",
")",
"if",
"self",
".",
"signer",
"is",
"not",
"None",
":",
"closing",
"+=",
"serialize_footer",
"(",
"self",
".",
"signer",
")",
"self",
".",
"__message_complete",
"=",
"True",
"return",
"ciphertext",
"+",
"closing",
"return",
"ciphertext"
] | Reads the requested number of bytes from source to a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Encrypted bytes from source stream
:rtype: bytes | [
"Reads",
"the",
"requested",
"number",
"of",
"bytes",
"from",
"source",
"to",
"a",
"streaming",
"non",
"-",
"framed",
"message",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L529-L562 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamEncryptor._read_bytes_to_framed_body | def _read_bytes_to_framed_body(self, b):
"""Reads the requested number of bytes from source to a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream, encrypted, and serialized
:rtype: bytes
"""
_LOGGER.debug("collecting %d bytes", b)
_b = b
if b > 0:
_frames_to_read = math.ceil(b / float(self.config.frame_length))
b = int(_frames_to_read * self.config.frame_length)
_LOGGER.debug("%d bytes requested; reading %d bytes after normalizing to frame length", _b, b)
plaintext = self.source_stream.read(b)
plaintext_length = len(plaintext)
_LOGGER.debug("%d bytes read from source", plaintext_length)
finalize = False
if b < 0 or plaintext_length < b:
_LOGGER.debug("Final plaintext read from source")
finalize = True
output = b""
final_frame_written = False
while (
# If not finalizing on this pass, exit when plaintext is exhausted
(not finalize and plaintext)
# If finalizing on this pass, wait until final frame is written
or (finalize and not final_frame_written)
):
current_plaintext_length = len(plaintext)
is_final_frame = finalize and current_plaintext_length < self.config.frame_length
bytes_in_frame = min(current_plaintext_length, self.config.frame_length)
_LOGGER.debug(
"Writing %d bytes into%s frame %d",
bytes_in_frame,
" final" if is_final_frame else "",
self.sequence_number,
)
self._bytes_encrypted += bytes_in_frame
ciphertext, plaintext = serialize_frame(
algorithm=self._encryption_materials.algorithm,
plaintext=plaintext,
message_id=self._header.message_id,
data_encryption_key=self._derived_data_key,
frame_length=self.config.frame_length,
sequence_number=self.sequence_number,
is_final_frame=is_final_frame,
signer=self.signer,
)
final_frame_written = is_final_frame
output += ciphertext
self.sequence_number += 1
if finalize:
_LOGGER.debug("Writing footer")
if self.signer is not None:
output += serialize_footer(self.signer)
self.__message_complete = True
return output | python | def _read_bytes_to_framed_body(self, b):
"""Reads the requested number of bytes from source to a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream, encrypted, and serialized
:rtype: bytes
"""
_LOGGER.debug("collecting %d bytes", b)
_b = b
if b > 0:
_frames_to_read = math.ceil(b / float(self.config.frame_length))
b = int(_frames_to_read * self.config.frame_length)
_LOGGER.debug("%d bytes requested; reading %d bytes after normalizing to frame length", _b, b)
plaintext = self.source_stream.read(b)
plaintext_length = len(plaintext)
_LOGGER.debug("%d bytes read from source", plaintext_length)
finalize = False
if b < 0 or plaintext_length < b:
_LOGGER.debug("Final plaintext read from source")
finalize = True
output = b""
final_frame_written = False
while (
# If not finalizing on this pass, exit when plaintext is exhausted
(not finalize and plaintext)
# If finalizing on this pass, wait until final frame is written
or (finalize and not final_frame_written)
):
current_plaintext_length = len(plaintext)
is_final_frame = finalize and current_plaintext_length < self.config.frame_length
bytes_in_frame = min(current_plaintext_length, self.config.frame_length)
_LOGGER.debug(
"Writing %d bytes into%s frame %d",
bytes_in_frame,
" final" if is_final_frame else "",
self.sequence_number,
)
self._bytes_encrypted += bytes_in_frame
ciphertext, plaintext = serialize_frame(
algorithm=self._encryption_materials.algorithm,
plaintext=plaintext,
message_id=self._header.message_id,
data_encryption_key=self._derived_data_key,
frame_length=self.config.frame_length,
sequence_number=self.sequence_number,
is_final_frame=is_final_frame,
signer=self.signer,
)
final_frame_written = is_final_frame
output += ciphertext
self.sequence_number += 1
if finalize:
_LOGGER.debug("Writing footer")
if self.signer is not None:
output += serialize_footer(self.signer)
self.__message_complete = True
return output | [
"def",
"_read_bytes_to_framed_body",
"(",
"self",
",",
"b",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"collecting %d bytes\"",
",",
"b",
")",
"_b",
"=",
"b",
"if",
"b",
">",
"0",
":",
"_frames_to_read",
"=",
"math",
".",
"ceil",
"(",
"b",
"/",
"float",
"(",
"self",
".",
"config",
".",
"frame_length",
")",
")",
"b",
"=",
"int",
"(",
"_frames_to_read",
"*",
"self",
".",
"config",
".",
"frame_length",
")",
"_LOGGER",
".",
"debug",
"(",
"\"%d bytes requested; reading %d bytes after normalizing to frame length\"",
",",
"_b",
",",
"b",
")",
"plaintext",
"=",
"self",
".",
"source_stream",
".",
"read",
"(",
"b",
")",
"plaintext_length",
"=",
"len",
"(",
"plaintext",
")",
"_LOGGER",
".",
"debug",
"(",
"\"%d bytes read from source\"",
",",
"plaintext_length",
")",
"finalize",
"=",
"False",
"if",
"b",
"<",
"0",
"or",
"plaintext_length",
"<",
"b",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Final plaintext read from source\"",
")",
"finalize",
"=",
"True",
"output",
"=",
"b\"\"",
"final_frame_written",
"=",
"False",
"while",
"(",
"# If not finalizing on this pass, exit when plaintext is exhausted",
"(",
"not",
"finalize",
"and",
"plaintext",
")",
"# If finalizing on this pass, wait until final frame is written",
"or",
"(",
"finalize",
"and",
"not",
"final_frame_written",
")",
")",
":",
"current_plaintext_length",
"=",
"len",
"(",
"plaintext",
")",
"is_final_frame",
"=",
"finalize",
"and",
"current_plaintext_length",
"<",
"self",
".",
"config",
".",
"frame_length",
"bytes_in_frame",
"=",
"min",
"(",
"current_plaintext_length",
",",
"self",
".",
"config",
".",
"frame_length",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Writing %d bytes into%s frame %d\"",
",",
"bytes_in_frame",
",",
"\" final\"",
"if",
"is_final_frame",
"else",
"\"\"",
",",
"self",
".",
"sequence_number",
",",
")",
"self",
".",
"_bytes_encrypted",
"+=",
"bytes_in_frame",
"ciphertext",
",",
"plaintext",
"=",
"serialize_frame",
"(",
"algorithm",
"=",
"self",
".",
"_encryption_materials",
".",
"algorithm",
",",
"plaintext",
"=",
"plaintext",
",",
"message_id",
"=",
"self",
".",
"_header",
".",
"message_id",
",",
"data_encryption_key",
"=",
"self",
".",
"_derived_data_key",
",",
"frame_length",
"=",
"self",
".",
"config",
".",
"frame_length",
",",
"sequence_number",
"=",
"self",
".",
"sequence_number",
",",
"is_final_frame",
"=",
"is_final_frame",
",",
"signer",
"=",
"self",
".",
"signer",
",",
")",
"final_frame_written",
"=",
"is_final_frame",
"output",
"+=",
"ciphertext",
"self",
".",
"sequence_number",
"+=",
"1",
"if",
"finalize",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Writing footer\"",
")",
"if",
"self",
".",
"signer",
"is",
"not",
"None",
":",
"output",
"+=",
"serialize_footer",
"(",
"self",
".",
"signer",
")",
"self",
".",
"__message_complete",
"=",
"True",
"return",
"output"
] | Reads the requested number of bytes from source to a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream, encrypted, and serialized
:rtype: bytes | [
"Reads",
"the",
"requested",
"number",
"of",
"bytes",
"from",
"source",
"to",
"a",
"streaming",
"framed",
"message",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L564-L627 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamDecryptor._read_header | def _read_header(self):
"""Reads the message header from the input stream.
:returns: tuple containing deserialized header and header_auth objects
:rtype: tuple of aws_encryption_sdk.structures.MessageHeader
and aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:raises CustomMaximumValueExceeded: if frame length is greater than the custom max value
"""
header, raw_header = deserialize_header(self.source_stream)
self.__unframed_bytes_read += len(raw_header)
if (
self.config.max_body_length is not None
and header.content_type == ContentType.FRAMED_DATA
and header.frame_length > self.config.max_body_length
):
raise CustomMaximumValueExceeded(
"Frame Size in header found larger than custom value: {found:d} > {custom:d}".format(
found=header.frame_length, custom=self.config.max_body_length
)
)
decrypt_materials_request = DecryptionMaterialsRequest(
encrypted_data_keys=header.encrypted_data_keys,
algorithm=header.algorithm,
encryption_context=header.encryption_context,
)
decryption_materials = self.config.materials_manager.decrypt_materials(request=decrypt_materials_request)
if decryption_materials.verification_key is None:
self.verifier = None
else:
self.verifier = Verifier.from_key_bytes(
algorithm=header.algorithm, key_bytes=decryption_materials.verification_key
)
if self.verifier is not None:
self.verifier.update(raw_header)
header_auth = deserialize_header_auth(
stream=self.source_stream, algorithm=header.algorithm, verifier=self.verifier
)
self._derived_data_key = derive_data_encryption_key(
source_key=decryption_materials.data_key.data_key, algorithm=header.algorithm, message_id=header.message_id
)
validate_header(header=header, header_auth=header_auth, raw_header=raw_header, data_key=self._derived_data_key)
return header, header_auth | python | def _read_header(self):
"""Reads the message header from the input stream.
:returns: tuple containing deserialized header and header_auth objects
:rtype: tuple of aws_encryption_sdk.structures.MessageHeader
and aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:raises CustomMaximumValueExceeded: if frame length is greater than the custom max value
"""
header, raw_header = deserialize_header(self.source_stream)
self.__unframed_bytes_read += len(raw_header)
if (
self.config.max_body_length is not None
and header.content_type == ContentType.FRAMED_DATA
and header.frame_length > self.config.max_body_length
):
raise CustomMaximumValueExceeded(
"Frame Size in header found larger than custom value: {found:d} > {custom:d}".format(
found=header.frame_length, custom=self.config.max_body_length
)
)
decrypt_materials_request = DecryptionMaterialsRequest(
encrypted_data_keys=header.encrypted_data_keys,
algorithm=header.algorithm,
encryption_context=header.encryption_context,
)
decryption_materials = self.config.materials_manager.decrypt_materials(request=decrypt_materials_request)
if decryption_materials.verification_key is None:
self.verifier = None
else:
self.verifier = Verifier.from_key_bytes(
algorithm=header.algorithm, key_bytes=decryption_materials.verification_key
)
if self.verifier is not None:
self.verifier.update(raw_header)
header_auth = deserialize_header_auth(
stream=self.source_stream, algorithm=header.algorithm, verifier=self.verifier
)
self._derived_data_key = derive_data_encryption_key(
source_key=decryption_materials.data_key.data_key, algorithm=header.algorithm, message_id=header.message_id
)
validate_header(header=header, header_auth=header_auth, raw_header=raw_header, data_key=self._derived_data_key)
return header, header_auth | [
"def",
"_read_header",
"(",
"self",
")",
":",
"header",
",",
"raw_header",
"=",
"deserialize_header",
"(",
"self",
".",
"source_stream",
")",
"self",
".",
"__unframed_bytes_read",
"+=",
"len",
"(",
"raw_header",
")",
"if",
"(",
"self",
".",
"config",
".",
"max_body_length",
"is",
"not",
"None",
"and",
"header",
".",
"content_type",
"==",
"ContentType",
".",
"FRAMED_DATA",
"and",
"header",
".",
"frame_length",
">",
"self",
".",
"config",
".",
"max_body_length",
")",
":",
"raise",
"CustomMaximumValueExceeded",
"(",
"\"Frame Size in header found larger than custom value: {found:d} > {custom:d}\"",
".",
"format",
"(",
"found",
"=",
"header",
".",
"frame_length",
",",
"custom",
"=",
"self",
".",
"config",
".",
"max_body_length",
")",
")",
"decrypt_materials_request",
"=",
"DecryptionMaterialsRequest",
"(",
"encrypted_data_keys",
"=",
"header",
".",
"encrypted_data_keys",
",",
"algorithm",
"=",
"header",
".",
"algorithm",
",",
"encryption_context",
"=",
"header",
".",
"encryption_context",
",",
")",
"decryption_materials",
"=",
"self",
".",
"config",
".",
"materials_manager",
".",
"decrypt_materials",
"(",
"request",
"=",
"decrypt_materials_request",
")",
"if",
"decryption_materials",
".",
"verification_key",
"is",
"None",
":",
"self",
".",
"verifier",
"=",
"None",
"else",
":",
"self",
".",
"verifier",
"=",
"Verifier",
".",
"from_key_bytes",
"(",
"algorithm",
"=",
"header",
".",
"algorithm",
",",
"key_bytes",
"=",
"decryption_materials",
".",
"verification_key",
")",
"if",
"self",
".",
"verifier",
"is",
"not",
"None",
":",
"self",
".",
"verifier",
".",
"update",
"(",
"raw_header",
")",
"header_auth",
"=",
"deserialize_header_auth",
"(",
"stream",
"=",
"self",
".",
"source_stream",
",",
"algorithm",
"=",
"header",
".",
"algorithm",
",",
"verifier",
"=",
"self",
".",
"verifier",
")",
"self",
".",
"_derived_data_key",
"=",
"derive_data_encryption_key",
"(",
"source_key",
"=",
"decryption_materials",
".",
"data_key",
".",
"data_key",
",",
"algorithm",
"=",
"header",
".",
"algorithm",
",",
"message_id",
"=",
"header",
".",
"message_id",
")",
"validate_header",
"(",
"header",
"=",
"header",
",",
"header_auth",
"=",
"header_auth",
",",
"raw_header",
"=",
"raw_header",
",",
"data_key",
"=",
"self",
".",
"_derived_data_key",
")",
"return",
"header",
",",
"header_auth"
] | Reads the message header from the input stream.
:returns: tuple containing deserialized header and header_auth objects
:rtype: tuple of aws_encryption_sdk.structures.MessageHeader
and aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:raises CustomMaximumValueExceeded: if frame length is greater than the custom max value | [
"Reads",
"the",
"message",
"header",
"from",
"the",
"input",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L738-L782 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamDecryptor._read_bytes_from_non_framed_body | def _read_bytes_from_non_framed_body(self, b):
"""Reads the requested number of bytes from a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Decrypted bytes from source stream
:rtype: bytes
"""
_LOGGER.debug("starting non-framed body read")
# Always read the entire message for non-framed message bodies.
bytes_to_read = self.body_length
_LOGGER.debug("%d bytes requested; reading %d bytes", b, bytes_to_read)
ciphertext = self.source_stream.read(bytes_to_read)
if len(self.output_buffer) + len(ciphertext) < self.body_length:
raise SerializationError("Total message body contents less than specified in body description")
if self.verifier is not None:
self.verifier.update(ciphertext)
tag = deserialize_tag(stream=self.source_stream, header=self._header, verifier=self.verifier)
aad_content_string = aws_encryption_sdk.internal.utils.get_aad_content_string(
content_type=self._header.content_type, is_final_frame=True
)
associated_data = assemble_content_aad(
message_id=self._header.message_id,
aad_content_string=aad_content_string,
seq_num=1,
length=self.body_length,
)
self.decryptor = Decryptor(
algorithm=self._header.algorithm,
key=self._derived_data_key,
associated_data=associated_data,
iv=self._unframed_body_iv,
tag=tag,
)
plaintext = self.decryptor.update(ciphertext)
plaintext += self.decryptor.finalize()
self.footer = deserialize_footer(stream=self.source_stream, verifier=self.verifier)
return plaintext | python | def _read_bytes_from_non_framed_body(self, b):
"""Reads the requested number of bytes from a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Decrypted bytes from source stream
:rtype: bytes
"""
_LOGGER.debug("starting non-framed body read")
# Always read the entire message for non-framed message bodies.
bytes_to_read = self.body_length
_LOGGER.debug("%d bytes requested; reading %d bytes", b, bytes_to_read)
ciphertext = self.source_stream.read(bytes_to_read)
if len(self.output_buffer) + len(ciphertext) < self.body_length:
raise SerializationError("Total message body contents less than specified in body description")
if self.verifier is not None:
self.verifier.update(ciphertext)
tag = deserialize_tag(stream=self.source_stream, header=self._header, verifier=self.verifier)
aad_content_string = aws_encryption_sdk.internal.utils.get_aad_content_string(
content_type=self._header.content_type, is_final_frame=True
)
associated_data = assemble_content_aad(
message_id=self._header.message_id,
aad_content_string=aad_content_string,
seq_num=1,
length=self.body_length,
)
self.decryptor = Decryptor(
algorithm=self._header.algorithm,
key=self._derived_data_key,
associated_data=associated_data,
iv=self._unframed_body_iv,
tag=tag,
)
plaintext = self.decryptor.update(ciphertext)
plaintext += self.decryptor.finalize()
self.footer = deserialize_footer(stream=self.source_stream, verifier=self.verifier)
return plaintext | [
"def",
"_read_bytes_from_non_framed_body",
"(",
"self",
",",
"b",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"starting non-framed body read\"",
")",
"# Always read the entire message for non-framed message bodies.",
"bytes_to_read",
"=",
"self",
".",
"body_length",
"_LOGGER",
".",
"debug",
"(",
"\"%d bytes requested; reading %d bytes\"",
",",
"b",
",",
"bytes_to_read",
")",
"ciphertext",
"=",
"self",
".",
"source_stream",
".",
"read",
"(",
"bytes_to_read",
")",
"if",
"len",
"(",
"self",
".",
"output_buffer",
")",
"+",
"len",
"(",
"ciphertext",
")",
"<",
"self",
".",
"body_length",
":",
"raise",
"SerializationError",
"(",
"\"Total message body contents less than specified in body description\"",
")",
"if",
"self",
".",
"verifier",
"is",
"not",
"None",
":",
"self",
".",
"verifier",
".",
"update",
"(",
"ciphertext",
")",
"tag",
"=",
"deserialize_tag",
"(",
"stream",
"=",
"self",
".",
"source_stream",
",",
"header",
"=",
"self",
".",
"_header",
",",
"verifier",
"=",
"self",
".",
"verifier",
")",
"aad_content_string",
"=",
"aws_encryption_sdk",
".",
"internal",
".",
"utils",
".",
"get_aad_content_string",
"(",
"content_type",
"=",
"self",
".",
"_header",
".",
"content_type",
",",
"is_final_frame",
"=",
"True",
")",
"associated_data",
"=",
"assemble_content_aad",
"(",
"message_id",
"=",
"self",
".",
"_header",
".",
"message_id",
",",
"aad_content_string",
"=",
"aad_content_string",
",",
"seq_num",
"=",
"1",
",",
"length",
"=",
"self",
".",
"body_length",
",",
")",
"self",
".",
"decryptor",
"=",
"Decryptor",
"(",
"algorithm",
"=",
"self",
".",
"_header",
".",
"algorithm",
",",
"key",
"=",
"self",
".",
"_derived_data_key",
",",
"associated_data",
"=",
"associated_data",
",",
"iv",
"=",
"self",
".",
"_unframed_body_iv",
",",
"tag",
"=",
"tag",
",",
")",
"plaintext",
"=",
"self",
".",
"decryptor",
".",
"update",
"(",
"ciphertext",
")",
"plaintext",
"+=",
"self",
".",
"decryptor",
".",
"finalize",
"(",
")",
"self",
".",
"footer",
"=",
"deserialize_footer",
"(",
"stream",
"=",
"self",
".",
"source_stream",
",",
"verifier",
"=",
"self",
".",
"verifier",
")",
"return",
"plaintext"
] | Reads the requested number of bytes from a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Decrypted bytes from source stream
:rtype: bytes | [
"Reads",
"the",
"requested",
"number",
"of",
"bytes",
"from",
"a",
"streaming",
"non",
"-",
"framed",
"message",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L814-L857 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamDecryptor._read_bytes_from_framed_body | def _read_bytes_from_framed_body(self, b):
"""Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes
"""
plaintext = b""
final_frame = False
_LOGGER.debug("collecting %d bytes", b)
while len(plaintext) < b and not final_frame:
_LOGGER.debug("Reading frame")
frame_data, final_frame = deserialize_frame(
stream=self.source_stream, header=self._header, verifier=self.verifier
)
_LOGGER.debug("Read complete for frame %d", frame_data.sequence_number)
if frame_data.sequence_number != self.last_sequence_number + 1:
raise SerializationError("Malformed message: frames out of order")
self.last_sequence_number += 1
aad_content_string = aws_encryption_sdk.internal.utils.get_aad_content_string(
content_type=self._header.content_type, is_final_frame=frame_data.final_frame
)
associated_data = assemble_content_aad(
message_id=self._header.message_id,
aad_content_string=aad_content_string,
seq_num=frame_data.sequence_number,
length=len(frame_data.ciphertext),
)
plaintext += decrypt(
algorithm=self._header.algorithm,
key=self._derived_data_key,
encrypted_data=frame_data,
associated_data=associated_data,
)
plaintext_length = len(plaintext)
_LOGGER.debug("bytes collected: %d", plaintext_length)
if final_frame:
_LOGGER.debug("Reading footer")
self.footer = deserialize_footer(stream=self.source_stream, verifier=self.verifier)
return plaintext | python | def _read_bytes_from_framed_body(self, b):
"""Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes
"""
plaintext = b""
final_frame = False
_LOGGER.debug("collecting %d bytes", b)
while len(plaintext) < b and not final_frame:
_LOGGER.debug("Reading frame")
frame_data, final_frame = deserialize_frame(
stream=self.source_stream, header=self._header, verifier=self.verifier
)
_LOGGER.debug("Read complete for frame %d", frame_data.sequence_number)
if frame_data.sequence_number != self.last_sequence_number + 1:
raise SerializationError("Malformed message: frames out of order")
self.last_sequence_number += 1
aad_content_string = aws_encryption_sdk.internal.utils.get_aad_content_string(
content_type=self._header.content_type, is_final_frame=frame_data.final_frame
)
associated_data = assemble_content_aad(
message_id=self._header.message_id,
aad_content_string=aad_content_string,
seq_num=frame_data.sequence_number,
length=len(frame_data.ciphertext),
)
plaintext += decrypt(
algorithm=self._header.algorithm,
key=self._derived_data_key,
encrypted_data=frame_data,
associated_data=associated_data,
)
plaintext_length = len(plaintext)
_LOGGER.debug("bytes collected: %d", plaintext_length)
if final_frame:
_LOGGER.debug("Reading footer")
self.footer = deserialize_footer(stream=self.source_stream, verifier=self.verifier)
return plaintext | [
"def",
"_read_bytes_from_framed_body",
"(",
"self",
",",
"b",
")",
":",
"plaintext",
"=",
"b\"\"",
"final_frame",
"=",
"False",
"_LOGGER",
".",
"debug",
"(",
"\"collecting %d bytes\"",
",",
"b",
")",
"while",
"len",
"(",
"plaintext",
")",
"<",
"b",
"and",
"not",
"final_frame",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Reading frame\"",
")",
"frame_data",
",",
"final_frame",
"=",
"deserialize_frame",
"(",
"stream",
"=",
"self",
".",
"source_stream",
",",
"header",
"=",
"self",
".",
"_header",
",",
"verifier",
"=",
"self",
".",
"verifier",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Read complete for frame %d\"",
",",
"frame_data",
".",
"sequence_number",
")",
"if",
"frame_data",
".",
"sequence_number",
"!=",
"self",
".",
"last_sequence_number",
"+",
"1",
":",
"raise",
"SerializationError",
"(",
"\"Malformed message: frames out of order\"",
")",
"self",
".",
"last_sequence_number",
"+=",
"1",
"aad_content_string",
"=",
"aws_encryption_sdk",
".",
"internal",
".",
"utils",
".",
"get_aad_content_string",
"(",
"content_type",
"=",
"self",
".",
"_header",
".",
"content_type",
",",
"is_final_frame",
"=",
"frame_data",
".",
"final_frame",
")",
"associated_data",
"=",
"assemble_content_aad",
"(",
"message_id",
"=",
"self",
".",
"_header",
".",
"message_id",
",",
"aad_content_string",
"=",
"aad_content_string",
",",
"seq_num",
"=",
"frame_data",
".",
"sequence_number",
",",
"length",
"=",
"len",
"(",
"frame_data",
".",
"ciphertext",
")",
",",
")",
"plaintext",
"+=",
"decrypt",
"(",
"algorithm",
"=",
"self",
".",
"_header",
".",
"algorithm",
",",
"key",
"=",
"self",
".",
"_derived_data_key",
",",
"encrypted_data",
"=",
"frame_data",
",",
"associated_data",
"=",
"associated_data",
",",
")",
"plaintext_length",
"=",
"len",
"(",
"plaintext",
")",
"_LOGGER",
".",
"debug",
"(",
"\"bytes collected: %d\"",
",",
"plaintext_length",
")",
"if",
"final_frame",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Reading footer\"",
")",
"self",
".",
"footer",
"=",
"deserialize_footer",
"(",
"stream",
"=",
"self",
".",
"source_stream",
",",
"verifier",
"=",
"self",
".",
"verifier",
")",
"return",
"plaintext"
] | Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes | [
"Reads",
"the",
"requested",
"number",
"of",
"bytes",
"from",
"a",
"streaming",
"framed",
"message",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L859-L899 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/streaming_client.py | StreamDecryptor.close | def close(self):
"""Closes out the stream."""
_LOGGER.debug("Closing stream")
if not hasattr(self, "footer"):
raise SerializationError("Footer not read")
super(StreamDecryptor, self).close() | python | def close(self):
"""Closes out the stream."""
_LOGGER.debug("Closing stream")
if not hasattr(self, "footer"):
raise SerializationError("Footer not read")
super(StreamDecryptor, self).close() | [
"def",
"close",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Closing stream\"",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"footer\"",
")",
":",
"raise",
"SerializationError",
"(",
"\"Footer not read\"",
")",
"super",
"(",
"StreamDecryptor",
",",
"self",
")",
".",
"close",
"(",
")"
] | Closes out the stream. | [
"Closes",
"out",
"the",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/streaming_client.py#L923-L928 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | _region_from_key_id | def _region_from_key_id(key_id, default_region=None):
"""Determine the target region from a key ID, falling back to a default region if provided.
:param str key_id: AWS KMS key ID
:param str default_region: Region to use if no region found in key_id
:returns: region name
:rtype: str
:raises UnknownRegionError: if no region found in key_id and no default_region provided
"""
try:
region_name = key_id.split(":", 4)[3]
except IndexError:
if default_region is None:
raise UnknownRegionError(
"No default region found and no region determinable from key id: {}".format(key_id)
)
region_name = default_region
return region_name | python | def _region_from_key_id(key_id, default_region=None):
"""Determine the target region from a key ID, falling back to a default region if provided.
:param str key_id: AWS KMS key ID
:param str default_region: Region to use if no region found in key_id
:returns: region name
:rtype: str
:raises UnknownRegionError: if no region found in key_id and no default_region provided
"""
try:
region_name = key_id.split(":", 4)[3]
except IndexError:
if default_region is None:
raise UnknownRegionError(
"No default region found and no region determinable from key id: {}".format(key_id)
)
region_name = default_region
return region_name | [
"def",
"_region_from_key_id",
"(",
"key_id",
",",
"default_region",
"=",
"None",
")",
":",
"try",
":",
"region_name",
"=",
"key_id",
".",
"split",
"(",
"\":\"",
",",
"4",
")",
"[",
"3",
"]",
"except",
"IndexError",
":",
"if",
"default_region",
"is",
"None",
":",
"raise",
"UnknownRegionError",
"(",
"\"No default region found and no region determinable from key id: {}\"",
".",
"format",
"(",
"key_id",
")",
")",
"region_name",
"=",
"default_region",
"return",
"region_name"
] | Determine the target region from a key ID, falling back to a default region if provided.
:param str key_id: AWS KMS key ID
:param str default_region: Region to use if no region found in key_id
:returns: region name
:rtype: str
:raises UnknownRegionError: if no region found in key_id and no default_region provided | [
"Determine",
"the",
"target",
"region",
"from",
"a",
"key",
"ID",
"falling",
"back",
"to",
"a",
"default",
"region",
"if",
"provided",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L35-L52 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKeyProvider._process_config | def _process_config(self):
"""Traverses the config and adds master keys and regional clients as needed."""
self._user_agent_adding_config = botocore.config.Config(user_agent_extra=USER_AGENT_SUFFIX)
if self.config.region_names:
self.add_regional_clients_from_list(self.config.region_names)
self.default_region = self.config.region_names[0]
else:
self.default_region = self.config.botocore_session.get_config_variable("region")
if self.default_region is not None:
self.add_regional_client(self.default_region)
if self.config.key_ids:
self.add_master_keys_from_list(self.config.key_ids) | python | def _process_config(self):
"""Traverses the config and adds master keys and regional clients as needed."""
self._user_agent_adding_config = botocore.config.Config(user_agent_extra=USER_AGENT_SUFFIX)
if self.config.region_names:
self.add_regional_clients_from_list(self.config.region_names)
self.default_region = self.config.region_names[0]
else:
self.default_region = self.config.botocore_session.get_config_variable("region")
if self.default_region is not None:
self.add_regional_client(self.default_region)
if self.config.key_ids:
self.add_master_keys_from_list(self.config.key_ids) | [
"def",
"_process_config",
"(",
"self",
")",
":",
"self",
".",
"_user_agent_adding_config",
"=",
"botocore",
".",
"config",
".",
"Config",
"(",
"user_agent_extra",
"=",
"USER_AGENT_SUFFIX",
")",
"if",
"self",
".",
"config",
".",
"region_names",
":",
"self",
".",
"add_regional_clients_from_list",
"(",
"self",
".",
"config",
".",
"region_names",
")",
"self",
".",
"default_region",
"=",
"self",
".",
"config",
".",
"region_names",
"[",
"0",
"]",
"else",
":",
"self",
".",
"default_region",
"=",
"self",
".",
"config",
".",
"botocore_session",
".",
"get_config_variable",
"(",
"\"region\"",
")",
"if",
"self",
".",
"default_region",
"is",
"not",
"None",
":",
"self",
".",
"add_regional_client",
"(",
"self",
".",
"default_region",
")",
"if",
"self",
".",
"config",
".",
"key_ids",
":",
"self",
".",
"add_master_keys_from_list",
"(",
"self",
".",
"config",
".",
"key_ids",
")"
] | Traverses the config and adds master keys and regional clients as needed. | [
"Traverses",
"the",
"config",
"and",
"adds",
"master",
"keys",
"and",
"regional",
"clients",
"as",
"needed",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L115-L128 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKeyProvider._wrap_client | def _wrap_client(self, region_name, method, *args, **kwargs):
"""Proxies all calls to a kms clients methods and removes misbehaving clients
:param str region_name: AWS Region ID (ex: us-east-1)
:param callable method: a method on the KMS client to proxy
:param tuple args: list of arguments to pass to the provided ``method``
:param dict kwargs: dictonary of keyword arguments to pass to the provided ``method``
"""
try:
return method(*args, **kwargs)
except botocore.exceptions.BotoCoreError:
self._regional_clients.pop(region_name)
_LOGGER.error(
'Removing regional client "%s" from cache due to BotoCoreError on %s call', region_name, method.__name__
)
raise | python | def _wrap_client(self, region_name, method, *args, **kwargs):
"""Proxies all calls to a kms clients methods and removes misbehaving clients
:param str region_name: AWS Region ID (ex: us-east-1)
:param callable method: a method on the KMS client to proxy
:param tuple args: list of arguments to pass to the provided ``method``
:param dict kwargs: dictonary of keyword arguments to pass to the provided ``method``
"""
try:
return method(*args, **kwargs)
except botocore.exceptions.BotoCoreError:
self._regional_clients.pop(region_name)
_LOGGER.error(
'Removing regional client "%s" from cache due to BotoCoreError on %s call', region_name, method.__name__
)
raise | [
"def",
"_wrap_client",
"(",
"self",
",",
"region_name",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"botocore",
".",
"exceptions",
".",
"BotoCoreError",
":",
"self",
".",
"_regional_clients",
".",
"pop",
"(",
"region_name",
")",
"_LOGGER",
".",
"error",
"(",
"'Removing regional client \"%s\" from cache due to BotoCoreError on %s call'",
",",
"region_name",
",",
"method",
".",
"__name__",
")",
"raise"
] | Proxies all calls to a kms clients methods and removes misbehaving clients
:param str region_name: AWS Region ID (ex: us-east-1)
:param callable method: a method on the KMS client to proxy
:param tuple args: list of arguments to pass to the provided ``method``
:param dict kwargs: dictonary of keyword arguments to pass to the provided ``method`` | [
"Proxies",
"all",
"calls",
"to",
"a",
"kms",
"clients",
"methods",
"and",
"removes",
"misbehaving",
"clients"
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L130-L145 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKeyProvider._register_client | def _register_client(self, client, region_name):
"""Uses functools.partial to wrap all methods on a client with the self._wrap_client method
:param botocore.client.BaseClient client: the client to proxy
:param str region_name: AWS Region ID (ex: us-east-1)
"""
for item in client.meta.method_to_api_mapping:
method = getattr(client, item)
wrapped_method = functools.partial(self._wrap_client, region_name, method)
setattr(client, item, wrapped_method) | python | def _register_client(self, client, region_name):
"""Uses functools.partial to wrap all methods on a client with the self._wrap_client method
:param botocore.client.BaseClient client: the client to proxy
:param str region_name: AWS Region ID (ex: us-east-1)
"""
for item in client.meta.method_to_api_mapping:
method = getattr(client, item)
wrapped_method = functools.partial(self._wrap_client, region_name, method)
setattr(client, item, wrapped_method) | [
"def",
"_register_client",
"(",
"self",
",",
"client",
",",
"region_name",
")",
":",
"for",
"item",
"in",
"client",
".",
"meta",
".",
"method_to_api_mapping",
":",
"method",
"=",
"getattr",
"(",
"client",
",",
"item",
")",
"wrapped_method",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_wrap_client",
",",
"region_name",
",",
"method",
")",
"setattr",
"(",
"client",
",",
"item",
",",
"wrapped_method",
")"
] | Uses functools.partial to wrap all methods on a client with the self._wrap_client method
:param botocore.client.BaseClient client: the client to proxy
:param str region_name: AWS Region ID (ex: us-east-1) | [
"Uses",
"functools",
".",
"partial",
"to",
"wrap",
"all",
"methods",
"on",
"a",
"client",
"with",
"the",
"self",
".",
"_wrap_client",
"method"
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L147-L156 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKeyProvider.add_regional_client | def add_regional_client(self, region_name):
"""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)
"""
if region_name not in self._regional_clients:
session = boto3.session.Session(region_name=region_name, botocore_session=self.config.botocore_session)
client = session.client("kms", config=self._user_agent_adding_config)
self._register_client(client, region_name)
self._regional_clients[region_name] = client | python | def add_regional_client(self, region_name):
"""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)
"""
if region_name not in self._regional_clients:
session = boto3.session.Session(region_name=region_name, botocore_session=self.config.botocore_session)
client = session.client("kms", config=self._user_agent_adding_config)
self._register_client(client, region_name)
self._regional_clients[region_name] = client | [
"def",
"add_regional_client",
"(",
"self",
",",
"region_name",
")",
":",
"if",
"region_name",
"not",
"in",
"self",
".",
"_regional_clients",
":",
"session",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
"region_name",
"=",
"region_name",
",",
"botocore_session",
"=",
"self",
".",
"config",
".",
"botocore_session",
")",
"client",
"=",
"session",
".",
"client",
"(",
"\"kms\"",
",",
"config",
"=",
"self",
".",
"_user_agent_adding_config",
")",
"self",
".",
"_register_client",
"(",
"client",
",",
"region_name",
")",
"self",
".",
"_regional_clients",
"[",
"region_name",
"]",
"=",
"client"
] | 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) | [
"Adds",
"a",
"regional",
"client",
"for",
"the",
"specified",
"region",
"if",
"it",
"does",
"not",
"already",
"exist",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L158-L167 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKeyProvider._client | def _client(self, key_id):
"""Returns a Boto3 KMS client for the appropriate region.
:param str key_id: KMS CMK ID
"""
region_name = _region_from_key_id(key_id, self.default_region)
self.add_regional_client(region_name)
return self._regional_clients[region_name] | python | def _client(self, key_id):
"""Returns a Boto3 KMS client for the appropriate region.
:param str key_id: KMS CMK ID
"""
region_name = _region_from_key_id(key_id, self.default_region)
self.add_regional_client(region_name)
return self._regional_clients[region_name] | [
"def",
"_client",
"(",
"self",
",",
"key_id",
")",
":",
"region_name",
"=",
"_region_from_key_id",
"(",
"key_id",
",",
"self",
".",
"default_region",
")",
"self",
".",
"add_regional_client",
"(",
"region_name",
")",
"return",
"self",
".",
"_regional_clients",
"[",
"region_name",
"]"
] | Returns a Boto3 KMS client for the appropriate region.
:param str key_id: KMS CMK ID | [
"Returns",
"a",
"Boto3",
"KMS",
"client",
"for",
"the",
"appropriate",
"region",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L177-L184 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKeyProvider._new_master_key | def _new_master_key(self, key_id):
"""Returns a KMSMasterKey for the specified key_id.
:param bytes key_id: KMS CMK ID
:returns: KMS Master Key based on key_id
:rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey
:raises InvalidKeyIdError: if key_id is not a valid KMS CMK ID to which this key provider has access
"""
_key_id = to_str(key_id) # KMS client requires str, not bytes
return KMSMasterKey(config=KMSMasterKeyConfig(key_id=key_id, client=self._client(_key_id))) | python | def _new_master_key(self, key_id):
"""Returns a KMSMasterKey for the specified key_id.
:param bytes key_id: KMS CMK ID
:returns: KMS Master Key based on key_id
:rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey
:raises InvalidKeyIdError: if key_id is not a valid KMS CMK ID to which this key provider has access
"""
_key_id = to_str(key_id) # KMS client requires str, not bytes
return KMSMasterKey(config=KMSMasterKeyConfig(key_id=key_id, client=self._client(_key_id))) | [
"def",
"_new_master_key",
"(",
"self",
",",
"key_id",
")",
":",
"_key_id",
"=",
"to_str",
"(",
"key_id",
")",
"# KMS client requires str, not bytes",
"return",
"KMSMasterKey",
"(",
"config",
"=",
"KMSMasterKeyConfig",
"(",
"key_id",
"=",
"key_id",
",",
"client",
"=",
"self",
".",
"_client",
"(",
"_key_id",
")",
")",
")"
] | Returns a KMSMasterKey for the specified key_id.
:param bytes key_id: KMS CMK ID
:returns: KMS Master Key based on key_id
:rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey
:raises InvalidKeyIdError: if key_id is not a valid KMS CMK ID to which this key provider has access | [
"Returns",
"a",
"KMSMasterKey",
"for",
"the",
"specified",
"key_id",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L186-L195 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKey._generate_data_key | def _generate_data_key(self, algorithm, encryption_context=None):
"""Generates data key and returns plaintext and ciphertext of key.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to pass to KMS
:returns: Generated data key
:rtype: aws_encryption_sdk.structures.DataKey
"""
kms_params = {"KeyId": self._key_id, "NumberOfBytes": algorithm.kdf_input_len}
if encryption_context is not None:
kms_params["EncryptionContext"] = encryption_context
if self.config.grant_tokens:
kms_params["GrantTokens"] = self.config.grant_tokens
# Catch any boto3 errors and normalize to expected EncryptKeyError
try:
response = self.config.client.generate_data_key(**kms_params)
plaintext = response["Plaintext"]
ciphertext = response["CiphertextBlob"]
key_id = response["KeyId"]
except (ClientError, KeyError):
error_message = "Master Key {key_id} unable to generate data key".format(key_id=self._key_id)
_LOGGER.exception(error_message)
raise GenerateKeyError(error_message)
return DataKey(
key_provider=MasterKeyInfo(provider_id=self.provider_id, key_info=key_id),
data_key=plaintext,
encrypted_data_key=ciphertext,
) | python | def _generate_data_key(self, algorithm, encryption_context=None):
"""Generates data key and returns plaintext and ciphertext of key.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to pass to KMS
:returns: Generated data key
:rtype: aws_encryption_sdk.structures.DataKey
"""
kms_params = {"KeyId": self._key_id, "NumberOfBytes": algorithm.kdf_input_len}
if encryption_context is not None:
kms_params["EncryptionContext"] = encryption_context
if self.config.grant_tokens:
kms_params["GrantTokens"] = self.config.grant_tokens
# Catch any boto3 errors and normalize to expected EncryptKeyError
try:
response = self.config.client.generate_data_key(**kms_params)
plaintext = response["Plaintext"]
ciphertext = response["CiphertextBlob"]
key_id = response["KeyId"]
except (ClientError, KeyError):
error_message = "Master Key {key_id} unable to generate data key".format(key_id=self._key_id)
_LOGGER.exception(error_message)
raise GenerateKeyError(error_message)
return DataKey(
key_provider=MasterKeyInfo(provider_id=self.provider_id, key_info=key_id),
data_key=plaintext,
encrypted_data_key=ciphertext,
) | [
"def",
"_generate_data_key",
"(",
"self",
",",
"algorithm",
",",
"encryption_context",
"=",
"None",
")",
":",
"kms_params",
"=",
"{",
"\"KeyId\"",
":",
"self",
".",
"_key_id",
",",
"\"NumberOfBytes\"",
":",
"algorithm",
".",
"kdf_input_len",
"}",
"if",
"encryption_context",
"is",
"not",
"None",
":",
"kms_params",
"[",
"\"EncryptionContext\"",
"]",
"=",
"encryption_context",
"if",
"self",
".",
"config",
".",
"grant_tokens",
":",
"kms_params",
"[",
"\"GrantTokens\"",
"]",
"=",
"self",
".",
"config",
".",
"grant_tokens",
"# Catch any boto3 errors and normalize to expected EncryptKeyError",
"try",
":",
"response",
"=",
"self",
".",
"config",
".",
"client",
".",
"generate_data_key",
"(",
"*",
"*",
"kms_params",
")",
"plaintext",
"=",
"response",
"[",
"\"Plaintext\"",
"]",
"ciphertext",
"=",
"response",
"[",
"\"CiphertextBlob\"",
"]",
"key_id",
"=",
"response",
"[",
"\"KeyId\"",
"]",
"except",
"(",
"ClientError",
",",
"KeyError",
")",
":",
"error_message",
"=",
"\"Master Key {key_id} unable to generate data key\"",
".",
"format",
"(",
"key_id",
"=",
"self",
".",
"_key_id",
")",
"_LOGGER",
".",
"exception",
"(",
"error_message",
")",
"raise",
"GenerateKeyError",
"(",
"error_message",
")",
"return",
"DataKey",
"(",
"key_provider",
"=",
"MasterKeyInfo",
"(",
"provider_id",
"=",
"self",
".",
"provider_id",
",",
"key_info",
"=",
"key_id",
")",
",",
"data_key",
"=",
"plaintext",
",",
"encrypted_data_key",
"=",
"ciphertext",
",",
")"
] | Generates data key and returns plaintext and ciphertext of key.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to pass to KMS
:returns: Generated data key
:rtype: aws_encryption_sdk.structures.DataKey | [
"Generates",
"data",
"key",
"and",
"returns",
"plaintext",
"and",
"ciphertext",
"of",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L244-L272 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/kms.py | KMSMasterKey._encrypt_data_key | def _encrypt_data_key(self, data_key, algorithm, encryption_context=None):
"""Encrypts a data key and returns the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Placeholder to maintain API compatibility with parent
:param dict encryption_context: Encryption context to pass to KMS
:returns: Data key containing encrypted data key
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
:raises EncryptKeyError: if Master Key is unable to encrypt data key
"""
kms_params = {"KeyId": self._key_id, "Plaintext": data_key.data_key}
if encryption_context:
kms_params["EncryptionContext"] = encryption_context
if self.config.grant_tokens:
kms_params["GrantTokens"] = self.config.grant_tokens
# Catch any boto3 errors and normalize to expected EncryptKeyError
try:
response = self.config.client.encrypt(**kms_params)
ciphertext = response["CiphertextBlob"]
key_id = response["KeyId"]
except (ClientError, KeyError):
error_message = "Master Key {key_id} unable to encrypt data key".format(key_id=self._key_id)
_LOGGER.exception(error_message)
raise EncryptKeyError(error_message)
return EncryptedDataKey(
key_provider=MasterKeyInfo(provider_id=self.provider_id, key_info=key_id), encrypted_data_key=ciphertext
) | python | def _encrypt_data_key(self, data_key, algorithm, encryption_context=None):
"""Encrypts a data key and returns the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Placeholder to maintain API compatibility with parent
:param dict encryption_context: Encryption context to pass to KMS
:returns: Data key containing encrypted data key
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
:raises EncryptKeyError: if Master Key is unable to encrypt data key
"""
kms_params = {"KeyId": self._key_id, "Plaintext": data_key.data_key}
if encryption_context:
kms_params["EncryptionContext"] = encryption_context
if self.config.grant_tokens:
kms_params["GrantTokens"] = self.config.grant_tokens
# Catch any boto3 errors and normalize to expected EncryptKeyError
try:
response = self.config.client.encrypt(**kms_params)
ciphertext = response["CiphertextBlob"]
key_id = response["KeyId"]
except (ClientError, KeyError):
error_message = "Master Key {key_id} unable to encrypt data key".format(key_id=self._key_id)
_LOGGER.exception(error_message)
raise EncryptKeyError(error_message)
return EncryptedDataKey(
key_provider=MasterKeyInfo(provider_id=self.provider_id, key_info=key_id), encrypted_data_key=ciphertext
) | [
"def",
"_encrypt_data_key",
"(",
"self",
",",
"data_key",
",",
"algorithm",
",",
"encryption_context",
"=",
"None",
")",
":",
"kms_params",
"=",
"{",
"\"KeyId\"",
":",
"self",
".",
"_key_id",
",",
"\"Plaintext\"",
":",
"data_key",
".",
"data_key",
"}",
"if",
"encryption_context",
":",
"kms_params",
"[",
"\"EncryptionContext\"",
"]",
"=",
"encryption_context",
"if",
"self",
".",
"config",
".",
"grant_tokens",
":",
"kms_params",
"[",
"\"GrantTokens\"",
"]",
"=",
"self",
".",
"config",
".",
"grant_tokens",
"# Catch any boto3 errors and normalize to expected EncryptKeyError",
"try",
":",
"response",
"=",
"self",
".",
"config",
".",
"client",
".",
"encrypt",
"(",
"*",
"*",
"kms_params",
")",
"ciphertext",
"=",
"response",
"[",
"\"CiphertextBlob\"",
"]",
"key_id",
"=",
"response",
"[",
"\"KeyId\"",
"]",
"except",
"(",
"ClientError",
",",
"KeyError",
")",
":",
"error_message",
"=",
"\"Master Key {key_id} unable to encrypt data key\"",
".",
"format",
"(",
"key_id",
"=",
"self",
".",
"_key_id",
")",
"_LOGGER",
".",
"exception",
"(",
"error_message",
")",
"raise",
"EncryptKeyError",
"(",
"error_message",
")",
"return",
"EncryptedDataKey",
"(",
"key_provider",
"=",
"MasterKeyInfo",
"(",
"provider_id",
"=",
"self",
".",
"provider_id",
",",
"key_info",
"=",
"key_id",
")",
",",
"encrypted_data_key",
"=",
"ciphertext",
")"
] | Encrypts a data key and returns the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Placeholder to maintain API compatibility with parent
:param dict encryption_context: Encryption context to pass to KMS
:returns: Data key containing encrypted data key
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
:raises EncryptKeyError: if Master Key is unable to encrypt data key | [
"Encrypts",
"a",
"data",
"key",
"and",
"returns",
"the",
"ciphertext",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/kms.py#L274-L302 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_encrypted_data_key | def serialize_encrypted_data_key(encrypted_data_key):
"""Serializes an encrypted data key.
.. versionadded:: 1.3.0
:param encrypted_data_key: Encrypted data key to serialize
:type encrypted_data_key: aws_encryption_sdk.structures.EncryptedDataKey
:returns: Serialized encrypted data key
:rtype: bytes
"""
encrypted_data_key_format = (
">" # big endian
"H" # key provider ID length
"{provider_id_len}s" # key provider ID
"H" # key info length
"{provider_info_len}s" # key info
"H" # encrypted data key length
"{enc_data_key_len}s" # encrypted data key
)
return struct.pack(
encrypted_data_key_format.format(
provider_id_len=len(encrypted_data_key.key_provider.provider_id),
provider_info_len=len(encrypted_data_key.key_provider.key_info),
enc_data_key_len=len(encrypted_data_key.encrypted_data_key),
),
len(encrypted_data_key.key_provider.provider_id),
to_bytes(encrypted_data_key.key_provider.provider_id),
len(encrypted_data_key.key_provider.key_info),
to_bytes(encrypted_data_key.key_provider.key_info),
len(encrypted_data_key.encrypted_data_key),
encrypted_data_key.encrypted_data_key,
) | python | def serialize_encrypted_data_key(encrypted_data_key):
"""Serializes an encrypted data key.
.. versionadded:: 1.3.0
:param encrypted_data_key: Encrypted data key to serialize
:type encrypted_data_key: aws_encryption_sdk.structures.EncryptedDataKey
:returns: Serialized encrypted data key
:rtype: bytes
"""
encrypted_data_key_format = (
">" # big endian
"H" # key provider ID length
"{provider_id_len}s" # key provider ID
"H" # key info length
"{provider_info_len}s" # key info
"H" # encrypted data key length
"{enc_data_key_len}s" # encrypted data key
)
return struct.pack(
encrypted_data_key_format.format(
provider_id_len=len(encrypted_data_key.key_provider.provider_id),
provider_info_len=len(encrypted_data_key.key_provider.key_info),
enc_data_key_len=len(encrypted_data_key.encrypted_data_key),
),
len(encrypted_data_key.key_provider.provider_id),
to_bytes(encrypted_data_key.key_provider.provider_id),
len(encrypted_data_key.key_provider.key_info),
to_bytes(encrypted_data_key.key_provider.key_info),
len(encrypted_data_key.encrypted_data_key),
encrypted_data_key.encrypted_data_key,
) | [
"def",
"serialize_encrypted_data_key",
"(",
"encrypted_data_key",
")",
":",
"encrypted_data_key_format",
"=",
"(",
"\">\"",
"# big endian",
"\"H\"",
"# key provider ID length",
"\"{provider_id_len}s\"",
"# key provider ID",
"\"H\"",
"# key info length",
"\"{provider_info_len}s\"",
"# key info",
"\"H\"",
"# encrypted data key length",
"\"{enc_data_key_len}s\"",
"# encrypted data key",
")",
"return",
"struct",
".",
"pack",
"(",
"encrypted_data_key_format",
".",
"format",
"(",
"provider_id_len",
"=",
"len",
"(",
"encrypted_data_key",
".",
"key_provider",
".",
"provider_id",
")",
",",
"provider_info_len",
"=",
"len",
"(",
"encrypted_data_key",
".",
"key_provider",
".",
"key_info",
")",
",",
"enc_data_key_len",
"=",
"len",
"(",
"encrypted_data_key",
".",
"encrypted_data_key",
")",
",",
")",
",",
"len",
"(",
"encrypted_data_key",
".",
"key_provider",
".",
"provider_id",
")",
",",
"to_bytes",
"(",
"encrypted_data_key",
".",
"key_provider",
".",
"provider_id",
")",
",",
"len",
"(",
"encrypted_data_key",
".",
"key_provider",
".",
"key_info",
")",
",",
"to_bytes",
"(",
"encrypted_data_key",
".",
"key_provider",
".",
"key_info",
")",
",",
"len",
"(",
"encrypted_data_key",
".",
"encrypted_data_key",
")",
",",
"encrypted_data_key",
".",
"encrypted_data_key",
",",
")"
] | Serializes an encrypted data key.
.. versionadded:: 1.3.0
:param encrypted_data_key: Encrypted data key to serialize
:type encrypted_data_key: aws_encryption_sdk.structures.EncryptedDataKey
:returns: Serialized encrypted data key
:rtype: bytes | [
"Serializes",
"an",
"encrypted",
"data",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L29-L60 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_header | def serialize_header(header, signer=None):
"""Serializes a header object.
:param header: Header to serialize
:type header: aws_encryption_sdk.structures.MessageHeader
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized header
:rtype: bytes
"""
ec_serialized = aws_encryption_sdk.internal.formatting.encryption_context.serialize_encryption_context(
header.encryption_context
)
header_start_format = (
">" # big endian
"B" # version
"B" # type
"H" # algorithm ID
"16s" # message ID
"H" # encryption context length
"{}s" # serialized encryption context
).format(len(ec_serialized))
header_bytes = bytearray()
header_bytes.extend(
struct.pack(
header_start_format,
header.version.value,
header.type.value,
header.algorithm.algorithm_id,
header.message_id,
len(ec_serialized),
ec_serialized,
)
)
serialized_data_keys = bytearray()
for data_key in header.encrypted_data_keys:
serialized_data_keys.extend(serialize_encrypted_data_key(data_key))
header_bytes.extend(struct.pack(">H", len(header.encrypted_data_keys)))
header_bytes.extend(serialized_data_keys)
header_close_format = (
">" # big endian
"B" # content type (no framing vs framing)
"4x" # reserved (formerly content AAD length)
"B" # nonce/IV length, this applies to all IVs in this message
"I" # frame length
)
header_bytes.extend(
struct.pack(header_close_format, header.content_type.value, header.algorithm.iv_len, header.frame_length)
)
output = bytes(header_bytes)
if signer is not None:
signer.update(output)
return output | python | def serialize_header(header, signer=None):
"""Serializes a header object.
:param header: Header to serialize
:type header: aws_encryption_sdk.structures.MessageHeader
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized header
:rtype: bytes
"""
ec_serialized = aws_encryption_sdk.internal.formatting.encryption_context.serialize_encryption_context(
header.encryption_context
)
header_start_format = (
">" # big endian
"B" # version
"B" # type
"H" # algorithm ID
"16s" # message ID
"H" # encryption context length
"{}s" # serialized encryption context
).format(len(ec_serialized))
header_bytes = bytearray()
header_bytes.extend(
struct.pack(
header_start_format,
header.version.value,
header.type.value,
header.algorithm.algorithm_id,
header.message_id,
len(ec_serialized),
ec_serialized,
)
)
serialized_data_keys = bytearray()
for data_key in header.encrypted_data_keys:
serialized_data_keys.extend(serialize_encrypted_data_key(data_key))
header_bytes.extend(struct.pack(">H", len(header.encrypted_data_keys)))
header_bytes.extend(serialized_data_keys)
header_close_format = (
">" # big endian
"B" # content type (no framing vs framing)
"4x" # reserved (formerly content AAD length)
"B" # nonce/IV length, this applies to all IVs in this message
"I" # frame length
)
header_bytes.extend(
struct.pack(header_close_format, header.content_type.value, header.algorithm.iv_len, header.frame_length)
)
output = bytes(header_bytes)
if signer is not None:
signer.update(output)
return output | [
"def",
"serialize_header",
"(",
"header",
",",
"signer",
"=",
"None",
")",
":",
"ec_serialized",
"=",
"aws_encryption_sdk",
".",
"internal",
".",
"formatting",
".",
"encryption_context",
".",
"serialize_encryption_context",
"(",
"header",
".",
"encryption_context",
")",
"header_start_format",
"=",
"(",
"\">\"",
"# big endian",
"\"B\"",
"# version",
"\"B\"",
"# type",
"\"H\"",
"# algorithm ID",
"\"16s\"",
"# message ID",
"\"H\"",
"# encryption context length",
"\"{}s\"",
"# serialized encryption context",
")",
".",
"format",
"(",
"len",
"(",
"ec_serialized",
")",
")",
"header_bytes",
"=",
"bytearray",
"(",
")",
"header_bytes",
".",
"extend",
"(",
"struct",
".",
"pack",
"(",
"header_start_format",
",",
"header",
".",
"version",
".",
"value",
",",
"header",
".",
"type",
".",
"value",
",",
"header",
".",
"algorithm",
".",
"algorithm_id",
",",
"header",
".",
"message_id",
",",
"len",
"(",
"ec_serialized",
")",
",",
"ec_serialized",
",",
")",
")",
"serialized_data_keys",
"=",
"bytearray",
"(",
")",
"for",
"data_key",
"in",
"header",
".",
"encrypted_data_keys",
":",
"serialized_data_keys",
".",
"extend",
"(",
"serialize_encrypted_data_key",
"(",
"data_key",
")",
")",
"header_bytes",
".",
"extend",
"(",
"struct",
".",
"pack",
"(",
"\">H\"",
",",
"len",
"(",
"header",
".",
"encrypted_data_keys",
")",
")",
")",
"header_bytes",
".",
"extend",
"(",
"serialized_data_keys",
")",
"header_close_format",
"=",
"(",
"\">\"",
"# big endian",
"\"B\"",
"# content type (no framing vs framing)",
"\"4x\"",
"# reserved (formerly content AAD length)",
"\"B\"",
"# nonce/IV length, this applies to all IVs in this message",
"\"I\"",
"# frame length",
")",
"header_bytes",
".",
"extend",
"(",
"struct",
".",
"pack",
"(",
"header_close_format",
",",
"header",
".",
"content_type",
".",
"value",
",",
"header",
".",
"algorithm",
".",
"iv_len",
",",
"header",
".",
"frame_length",
")",
")",
"output",
"=",
"bytes",
"(",
"header_bytes",
")",
"if",
"signer",
"is",
"not",
"None",
":",
"signer",
".",
"update",
"(",
"output",
")",
"return",
"output"
] | Serializes a header object.
:param header: Header to serialize
:type header: aws_encryption_sdk.structures.MessageHeader
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized header
:rtype: bytes | [
"Serializes",
"a",
"header",
"object",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L63-L118 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_header_auth | def serialize_header_auth(algorithm, header, data_encryption_key, signer=None):
"""Creates serialized header authentication data.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes header: Serialized message header
:param bytes data_encryption_key: Data key with which to encrypt message
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.Signer
:returns: Serialized header authentication data
:rtype: bytes
"""
header_auth = encrypt(
algorithm=algorithm,
key=data_encryption_key,
plaintext=b"",
associated_data=header,
iv=header_auth_iv(algorithm),
)
output = struct.pack(
">{iv_len}s{tag_len}s".format(iv_len=algorithm.iv_len, tag_len=algorithm.tag_len),
header_auth.iv,
header_auth.tag,
)
if signer is not None:
signer.update(output)
return output | python | def serialize_header_auth(algorithm, header, data_encryption_key, signer=None):
"""Creates serialized header authentication data.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes header: Serialized message header
:param bytes data_encryption_key: Data key with which to encrypt message
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.Signer
:returns: Serialized header authentication data
:rtype: bytes
"""
header_auth = encrypt(
algorithm=algorithm,
key=data_encryption_key,
plaintext=b"",
associated_data=header,
iv=header_auth_iv(algorithm),
)
output = struct.pack(
">{iv_len}s{tag_len}s".format(iv_len=algorithm.iv_len, tag_len=algorithm.tag_len),
header_auth.iv,
header_auth.tag,
)
if signer is not None:
signer.update(output)
return output | [
"def",
"serialize_header_auth",
"(",
"algorithm",
",",
"header",
",",
"data_encryption_key",
",",
"signer",
"=",
"None",
")",
":",
"header_auth",
"=",
"encrypt",
"(",
"algorithm",
"=",
"algorithm",
",",
"key",
"=",
"data_encryption_key",
",",
"plaintext",
"=",
"b\"\"",
",",
"associated_data",
"=",
"header",
",",
"iv",
"=",
"header_auth_iv",
"(",
"algorithm",
")",
",",
")",
"output",
"=",
"struct",
".",
"pack",
"(",
"\">{iv_len}s{tag_len}s\"",
".",
"format",
"(",
"iv_len",
"=",
"algorithm",
".",
"iv_len",
",",
"tag_len",
"=",
"algorithm",
".",
"tag_len",
")",
",",
"header_auth",
".",
"iv",
",",
"header_auth",
".",
"tag",
",",
")",
"if",
"signer",
"is",
"not",
"None",
":",
"signer",
".",
"update",
"(",
"output",
")",
"return",
"output"
] | Creates serialized header authentication data.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes header: Serialized message header
:param bytes data_encryption_key: Data key with which to encrypt message
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.Signer
:returns: Serialized header authentication data
:rtype: bytes | [
"Creates",
"serialized",
"header",
"authentication",
"data",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L121-L147 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_non_framed_open | def serialize_non_framed_open(algorithm, iv, plaintext_length, signer=None):
"""Serializes the opening block for a non-framed message body.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes iv: IV value used to encrypt body
:param int plaintext_length: Length of plaintext (and thus ciphertext) in body
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized body start block
:rtype: bytes
"""
body_start_format = (">" "{iv_length}s" "Q").format(iv_length=algorithm.iv_len) # nonce (IV) # content length
body_start = struct.pack(body_start_format, iv, plaintext_length)
if signer:
signer.update(body_start)
return body_start | python | def serialize_non_framed_open(algorithm, iv, plaintext_length, signer=None):
"""Serializes the opening block for a non-framed message body.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes iv: IV value used to encrypt body
:param int plaintext_length: Length of plaintext (and thus ciphertext) in body
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized body start block
:rtype: bytes
"""
body_start_format = (">" "{iv_length}s" "Q").format(iv_length=algorithm.iv_len) # nonce (IV) # content length
body_start = struct.pack(body_start_format, iv, plaintext_length)
if signer:
signer.update(body_start)
return body_start | [
"def",
"serialize_non_framed_open",
"(",
"algorithm",
",",
"iv",
",",
"plaintext_length",
",",
"signer",
"=",
"None",
")",
":",
"body_start_format",
"=",
"(",
"\">\"",
"\"{iv_length}s\"",
"\"Q\"",
")",
".",
"format",
"(",
"iv_length",
"=",
"algorithm",
".",
"iv_len",
")",
"# nonce (IV) # content length",
"body_start",
"=",
"struct",
".",
"pack",
"(",
"body_start_format",
",",
"iv",
",",
"plaintext_length",
")",
"if",
"signer",
":",
"signer",
".",
"update",
"(",
"body_start",
")",
"return",
"body_start"
] | Serializes the opening block for a non-framed message body.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes iv: IV value used to encrypt body
:param int plaintext_length: Length of plaintext (and thus ciphertext) in body
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized body start block
:rtype: bytes | [
"Serializes",
"the",
"opening",
"block",
"for",
"a",
"non",
"-",
"framed",
"message",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L150-L166 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_non_framed_close | def serialize_non_framed_close(tag, signer=None):
"""Serializes the closing block for a non-framed message body.
:param bytes tag: Auth tag value from body encryptor
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized body close block
:rtype: bytes
"""
body_close = struct.pack("{auth_len}s".format(auth_len=len(tag)), tag)
if signer:
signer.update(body_close)
return body_close | python | def serialize_non_framed_close(tag, signer=None):
"""Serializes the closing block for a non-framed message body.
:param bytes tag: Auth tag value from body encryptor
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized body close block
:rtype: bytes
"""
body_close = struct.pack("{auth_len}s".format(auth_len=len(tag)), tag)
if signer:
signer.update(body_close)
return body_close | [
"def",
"serialize_non_framed_close",
"(",
"tag",
",",
"signer",
"=",
"None",
")",
":",
"body_close",
"=",
"struct",
".",
"pack",
"(",
"\"{auth_len}s\"",
".",
"format",
"(",
"auth_len",
"=",
"len",
"(",
"tag",
")",
")",
",",
"tag",
")",
"if",
"signer",
":",
"signer",
".",
"update",
"(",
"body_close",
")",
"return",
"body_close"
] | Serializes the closing block for a non-framed message body.
:param bytes tag: Auth tag value from body encryptor
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized body close block
:rtype: bytes | [
"Serializes",
"the",
"closing",
"block",
"for",
"a",
"non",
"-",
"framed",
"message",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L169-L181 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_frame | def serialize_frame(
algorithm, plaintext, message_id, data_encryption_key, frame_length, sequence_number, is_final_frame, signer=None
):
"""Receives a message plaintext, breaks off a frame, encrypts and serializes
the frame, and returns the encrypted frame and the remaining plaintext.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes plaintext: Source plaintext to encrypt and serialize
:param bytes message_id: Message ID
:param bytes data_encryption_key: Data key with which to encrypt message
:param int frame_length: Length of the framed data
:param int sequence_number: Sequence number for frame to be generated
:param bool is_final_frame: Boolean stating whether or not this frame is a final frame
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.Signer
:returns: Serialized frame and remaining plaintext
:rtype: tuple of bytes
:raises SerializationError: if number of frames is too large
"""
if sequence_number < 1:
raise SerializationError("Frame sequence number must be greater than 0")
if sequence_number > aws_encryption_sdk.internal.defaults.MAX_FRAME_COUNT:
raise SerializationError("Max frame count exceeded")
if is_final_frame:
content_string = ContentAADString.FINAL_FRAME_STRING_ID
else:
content_string = ContentAADString.FRAME_STRING_ID
frame_plaintext = plaintext[:frame_length]
frame_ciphertext = encrypt(
algorithm=algorithm,
key=data_encryption_key,
plaintext=frame_plaintext,
associated_data=aws_encryption_sdk.internal.formatting.encryption_context.assemble_content_aad(
message_id=message_id,
aad_content_string=content_string,
seq_num=sequence_number,
length=len(frame_plaintext),
),
iv=frame_iv(algorithm, sequence_number),
)
plaintext = plaintext[frame_length:]
if is_final_frame:
_LOGGER.debug("Serializing final frame")
packed_frame = struct.pack(
">II{iv_len}sI{content_len}s{auth_len}s".format(
iv_len=algorithm.iv_len, content_len=len(frame_ciphertext.ciphertext), auth_len=algorithm.auth_len
),
SequenceIdentifier.SEQUENCE_NUMBER_END.value,
sequence_number,
frame_ciphertext.iv,
len(frame_ciphertext.ciphertext),
frame_ciphertext.ciphertext,
frame_ciphertext.tag,
)
else:
_LOGGER.debug("Serializing frame")
packed_frame = struct.pack(
">I{iv_len}s{content_len}s{auth_len}s".format(
iv_len=algorithm.iv_len, content_len=frame_length, auth_len=algorithm.auth_len
),
sequence_number,
frame_ciphertext.iv,
frame_ciphertext.ciphertext,
frame_ciphertext.tag,
)
if signer is not None:
signer.update(packed_frame)
return packed_frame, plaintext | python | def serialize_frame(
algorithm, plaintext, message_id, data_encryption_key, frame_length, sequence_number, is_final_frame, signer=None
):
"""Receives a message plaintext, breaks off a frame, encrypts and serializes
the frame, and returns the encrypted frame and the remaining plaintext.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes plaintext: Source plaintext to encrypt and serialize
:param bytes message_id: Message ID
:param bytes data_encryption_key: Data key with which to encrypt message
:param int frame_length: Length of the framed data
:param int sequence_number: Sequence number for frame to be generated
:param bool is_final_frame: Boolean stating whether or not this frame is a final frame
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.Signer
:returns: Serialized frame and remaining plaintext
:rtype: tuple of bytes
:raises SerializationError: if number of frames is too large
"""
if sequence_number < 1:
raise SerializationError("Frame sequence number must be greater than 0")
if sequence_number > aws_encryption_sdk.internal.defaults.MAX_FRAME_COUNT:
raise SerializationError("Max frame count exceeded")
if is_final_frame:
content_string = ContentAADString.FINAL_FRAME_STRING_ID
else:
content_string = ContentAADString.FRAME_STRING_ID
frame_plaintext = plaintext[:frame_length]
frame_ciphertext = encrypt(
algorithm=algorithm,
key=data_encryption_key,
plaintext=frame_plaintext,
associated_data=aws_encryption_sdk.internal.formatting.encryption_context.assemble_content_aad(
message_id=message_id,
aad_content_string=content_string,
seq_num=sequence_number,
length=len(frame_plaintext),
),
iv=frame_iv(algorithm, sequence_number),
)
plaintext = plaintext[frame_length:]
if is_final_frame:
_LOGGER.debug("Serializing final frame")
packed_frame = struct.pack(
">II{iv_len}sI{content_len}s{auth_len}s".format(
iv_len=algorithm.iv_len, content_len=len(frame_ciphertext.ciphertext), auth_len=algorithm.auth_len
),
SequenceIdentifier.SEQUENCE_NUMBER_END.value,
sequence_number,
frame_ciphertext.iv,
len(frame_ciphertext.ciphertext),
frame_ciphertext.ciphertext,
frame_ciphertext.tag,
)
else:
_LOGGER.debug("Serializing frame")
packed_frame = struct.pack(
">I{iv_len}s{content_len}s{auth_len}s".format(
iv_len=algorithm.iv_len, content_len=frame_length, auth_len=algorithm.auth_len
),
sequence_number,
frame_ciphertext.iv,
frame_ciphertext.ciphertext,
frame_ciphertext.tag,
)
if signer is not None:
signer.update(packed_frame)
return packed_frame, plaintext | [
"def",
"serialize_frame",
"(",
"algorithm",
",",
"plaintext",
",",
"message_id",
",",
"data_encryption_key",
",",
"frame_length",
",",
"sequence_number",
",",
"is_final_frame",
",",
"signer",
"=",
"None",
")",
":",
"if",
"sequence_number",
"<",
"1",
":",
"raise",
"SerializationError",
"(",
"\"Frame sequence number must be greater than 0\"",
")",
"if",
"sequence_number",
">",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"MAX_FRAME_COUNT",
":",
"raise",
"SerializationError",
"(",
"\"Max frame count exceeded\"",
")",
"if",
"is_final_frame",
":",
"content_string",
"=",
"ContentAADString",
".",
"FINAL_FRAME_STRING_ID",
"else",
":",
"content_string",
"=",
"ContentAADString",
".",
"FRAME_STRING_ID",
"frame_plaintext",
"=",
"plaintext",
"[",
":",
"frame_length",
"]",
"frame_ciphertext",
"=",
"encrypt",
"(",
"algorithm",
"=",
"algorithm",
",",
"key",
"=",
"data_encryption_key",
",",
"plaintext",
"=",
"frame_plaintext",
",",
"associated_data",
"=",
"aws_encryption_sdk",
".",
"internal",
".",
"formatting",
".",
"encryption_context",
".",
"assemble_content_aad",
"(",
"message_id",
"=",
"message_id",
",",
"aad_content_string",
"=",
"content_string",
",",
"seq_num",
"=",
"sequence_number",
",",
"length",
"=",
"len",
"(",
"frame_plaintext",
")",
",",
")",
",",
"iv",
"=",
"frame_iv",
"(",
"algorithm",
",",
"sequence_number",
")",
",",
")",
"plaintext",
"=",
"plaintext",
"[",
"frame_length",
":",
"]",
"if",
"is_final_frame",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Serializing final frame\"",
")",
"packed_frame",
"=",
"struct",
".",
"pack",
"(",
"\">II{iv_len}sI{content_len}s{auth_len}s\"",
".",
"format",
"(",
"iv_len",
"=",
"algorithm",
".",
"iv_len",
",",
"content_len",
"=",
"len",
"(",
"frame_ciphertext",
".",
"ciphertext",
")",
",",
"auth_len",
"=",
"algorithm",
".",
"auth_len",
")",
",",
"SequenceIdentifier",
".",
"SEQUENCE_NUMBER_END",
".",
"value",
",",
"sequence_number",
",",
"frame_ciphertext",
".",
"iv",
",",
"len",
"(",
"frame_ciphertext",
".",
"ciphertext",
")",
",",
"frame_ciphertext",
".",
"ciphertext",
",",
"frame_ciphertext",
".",
"tag",
",",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Serializing frame\"",
")",
"packed_frame",
"=",
"struct",
".",
"pack",
"(",
"\">I{iv_len}s{content_len}s{auth_len}s\"",
".",
"format",
"(",
"iv_len",
"=",
"algorithm",
".",
"iv_len",
",",
"content_len",
"=",
"frame_length",
",",
"auth_len",
"=",
"algorithm",
".",
"auth_len",
")",
",",
"sequence_number",
",",
"frame_ciphertext",
".",
"iv",
",",
"frame_ciphertext",
".",
"ciphertext",
",",
"frame_ciphertext",
".",
"tag",
",",
")",
"if",
"signer",
"is",
"not",
"None",
":",
"signer",
".",
"update",
"(",
"packed_frame",
")",
"return",
"packed_frame",
",",
"plaintext"
] | Receives a message plaintext, breaks off a frame, encrypts and serializes
the frame, and returns the encrypted frame and the remaining plaintext.
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes plaintext: Source plaintext to encrypt and serialize
:param bytes message_id: Message ID
:param bytes data_encryption_key: Data key with which to encrypt message
:param int frame_length: Length of the framed data
:param int sequence_number: Sequence number for frame to be generated
:param bool is_final_frame: Boolean stating whether or not this frame is a final frame
:param signer: Cryptographic signer object (optional)
:type signer: aws_encryption_sdk.Signer
:returns: Serialized frame and remaining plaintext
:rtype: tuple of bytes
:raises SerializationError: if number of frames is too large | [
"Receives",
"a",
"message",
"plaintext",
"breaks",
"off",
"a",
"frame",
"encrypts",
"and",
"serializes",
"the",
"frame",
"and",
"returns",
"the",
"encrypted",
"frame",
"and",
"the",
"remaining",
"plaintext",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L184-L252 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_footer | def serialize_footer(signer):
"""Uses the signer object which has been used to sign the message to generate
the signature, then serializes that signature.
:param signer: Cryptographic signer object
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized footer
:rtype: bytes
"""
footer = b""
if signer is not None:
signature = signer.finalize()
footer = struct.pack(">H{sig_len}s".format(sig_len=len(signature)), len(signature), signature)
return footer | python | def serialize_footer(signer):
"""Uses the signer object which has been used to sign the message to generate
the signature, then serializes that signature.
:param signer: Cryptographic signer object
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized footer
:rtype: bytes
"""
footer = b""
if signer is not None:
signature = signer.finalize()
footer = struct.pack(">H{sig_len}s".format(sig_len=len(signature)), len(signature), signature)
return footer | [
"def",
"serialize_footer",
"(",
"signer",
")",
":",
"footer",
"=",
"b\"\"",
"if",
"signer",
"is",
"not",
"None",
":",
"signature",
"=",
"signer",
".",
"finalize",
"(",
")",
"footer",
"=",
"struct",
".",
"pack",
"(",
"\">H{sig_len}s\"",
".",
"format",
"(",
"sig_len",
"=",
"len",
"(",
"signature",
")",
")",
",",
"len",
"(",
"signature",
")",
",",
"signature",
")",
"return",
"footer"
] | Uses the signer object which has been used to sign the message to generate
the signature, then serializes that signature.
:param signer: Cryptographic signer object
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized footer
:rtype: bytes | [
"Uses",
"the",
"signer",
"object",
"which",
"has",
"been",
"used",
"to",
"sign",
"the",
"message",
"to",
"generate",
"the",
"signature",
"then",
"serializes",
"that",
"signature",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L255-L268 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_raw_master_key_prefix | def serialize_raw_master_key_prefix(raw_master_key):
"""Produces the prefix that a RawMasterKey will always use for the
key_info value of keys which require additional information.
:param raw_master_key: RawMasterKey for which to produce a prefix
:type raw_master_key: aws_encryption_sdk.key_providers.raw.RawMasterKey
:returns: Serialized key_info prefix
:rtype: bytes
"""
if raw_master_key.config.wrapping_key.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC:
return to_bytes(raw_master_key.key_id)
return struct.pack(
">{}sII".format(len(raw_master_key.key_id)),
to_bytes(raw_master_key.key_id),
# Tag Length is stored in bits, not bytes
raw_master_key.config.wrapping_key.wrapping_algorithm.algorithm.tag_len * 8,
raw_master_key.config.wrapping_key.wrapping_algorithm.algorithm.iv_len,
) | python | def serialize_raw_master_key_prefix(raw_master_key):
"""Produces the prefix that a RawMasterKey will always use for the
key_info value of keys which require additional information.
:param raw_master_key: RawMasterKey for which to produce a prefix
:type raw_master_key: aws_encryption_sdk.key_providers.raw.RawMasterKey
:returns: Serialized key_info prefix
:rtype: bytes
"""
if raw_master_key.config.wrapping_key.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC:
return to_bytes(raw_master_key.key_id)
return struct.pack(
">{}sII".format(len(raw_master_key.key_id)),
to_bytes(raw_master_key.key_id),
# Tag Length is stored in bits, not bytes
raw_master_key.config.wrapping_key.wrapping_algorithm.algorithm.tag_len * 8,
raw_master_key.config.wrapping_key.wrapping_algorithm.algorithm.iv_len,
) | [
"def",
"serialize_raw_master_key_prefix",
"(",
"raw_master_key",
")",
":",
"if",
"raw_master_key",
".",
"config",
".",
"wrapping_key",
".",
"wrapping_algorithm",
".",
"encryption_type",
"is",
"EncryptionType",
".",
"ASYMMETRIC",
":",
"return",
"to_bytes",
"(",
"raw_master_key",
".",
"key_id",
")",
"return",
"struct",
".",
"pack",
"(",
"\">{}sII\"",
".",
"format",
"(",
"len",
"(",
"raw_master_key",
".",
"key_id",
")",
")",
",",
"to_bytes",
"(",
"raw_master_key",
".",
"key_id",
")",
",",
"# Tag Length is stored in bits, not bytes",
"raw_master_key",
".",
"config",
".",
"wrapping_key",
".",
"wrapping_algorithm",
".",
"algorithm",
".",
"tag_len",
"*",
"8",
",",
"raw_master_key",
".",
"config",
".",
"wrapping_key",
".",
"wrapping_algorithm",
".",
"algorithm",
".",
"iv_len",
",",
")"
] | Produces the prefix that a RawMasterKey will always use for the
key_info value of keys which require additional information.
:param raw_master_key: RawMasterKey for which to produce a prefix
:type raw_master_key: aws_encryption_sdk.key_providers.raw.RawMasterKey
:returns: Serialized key_info prefix
:rtype: bytes | [
"Produces",
"the",
"prefix",
"that",
"a",
"RawMasterKey",
"will",
"always",
"use",
"for",
"the",
"key_info",
"value",
"of",
"keys",
"which",
"require",
"additional",
"information",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L271-L288 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/serialize.py | serialize_wrapped_key | def serialize_wrapped_key(key_provider, wrapping_algorithm, wrapping_key_id, encrypted_wrapped_key):
"""Serializes EncryptedData into a Wrapped EncryptedDataKey.
:param key_provider: Info for Wrapping MasterKey
:type key_provider: aws_encryption_sdk.structures.MasterKeyInfo
:param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key
:type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm
:param bytes wrapping_key_id: Key ID of wrapping MasterKey
:param encrypted_wrapped_key: Encrypted data key
:type encrypted_wrapped_key: aws_encryption_sdk.internal.structures.EncryptedData
:returns: Wrapped EncryptedDataKey
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
"""
if encrypted_wrapped_key.iv is None:
key_info = wrapping_key_id
key_ciphertext = encrypted_wrapped_key.ciphertext
else:
key_info = struct.pack(
">{key_id_len}sII{iv_len}s".format(
key_id_len=len(wrapping_key_id), iv_len=wrapping_algorithm.algorithm.iv_len
),
to_bytes(wrapping_key_id),
len(encrypted_wrapped_key.tag) * 8, # Tag Length is stored in bits, not bytes
wrapping_algorithm.algorithm.iv_len,
encrypted_wrapped_key.iv,
)
key_ciphertext = encrypted_wrapped_key.ciphertext + encrypted_wrapped_key.tag
return EncryptedDataKey(
key_provider=MasterKeyInfo(provider_id=key_provider.provider_id, key_info=key_info),
encrypted_data_key=key_ciphertext,
) | python | def serialize_wrapped_key(key_provider, wrapping_algorithm, wrapping_key_id, encrypted_wrapped_key):
"""Serializes EncryptedData into a Wrapped EncryptedDataKey.
:param key_provider: Info for Wrapping MasterKey
:type key_provider: aws_encryption_sdk.structures.MasterKeyInfo
:param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key
:type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm
:param bytes wrapping_key_id: Key ID of wrapping MasterKey
:param encrypted_wrapped_key: Encrypted data key
:type encrypted_wrapped_key: aws_encryption_sdk.internal.structures.EncryptedData
:returns: Wrapped EncryptedDataKey
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
"""
if encrypted_wrapped_key.iv is None:
key_info = wrapping_key_id
key_ciphertext = encrypted_wrapped_key.ciphertext
else:
key_info = struct.pack(
">{key_id_len}sII{iv_len}s".format(
key_id_len=len(wrapping_key_id), iv_len=wrapping_algorithm.algorithm.iv_len
),
to_bytes(wrapping_key_id),
len(encrypted_wrapped_key.tag) * 8, # Tag Length is stored in bits, not bytes
wrapping_algorithm.algorithm.iv_len,
encrypted_wrapped_key.iv,
)
key_ciphertext = encrypted_wrapped_key.ciphertext + encrypted_wrapped_key.tag
return EncryptedDataKey(
key_provider=MasterKeyInfo(provider_id=key_provider.provider_id, key_info=key_info),
encrypted_data_key=key_ciphertext,
) | [
"def",
"serialize_wrapped_key",
"(",
"key_provider",
",",
"wrapping_algorithm",
",",
"wrapping_key_id",
",",
"encrypted_wrapped_key",
")",
":",
"if",
"encrypted_wrapped_key",
".",
"iv",
"is",
"None",
":",
"key_info",
"=",
"wrapping_key_id",
"key_ciphertext",
"=",
"encrypted_wrapped_key",
".",
"ciphertext",
"else",
":",
"key_info",
"=",
"struct",
".",
"pack",
"(",
"\">{key_id_len}sII{iv_len}s\"",
".",
"format",
"(",
"key_id_len",
"=",
"len",
"(",
"wrapping_key_id",
")",
",",
"iv_len",
"=",
"wrapping_algorithm",
".",
"algorithm",
".",
"iv_len",
")",
",",
"to_bytes",
"(",
"wrapping_key_id",
")",
",",
"len",
"(",
"encrypted_wrapped_key",
".",
"tag",
")",
"*",
"8",
",",
"# Tag Length is stored in bits, not bytes",
"wrapping_algorithm",
".",
"algorithm",
".",
"iv_len",
",",
"encrypted_wrapped_key",
".",
"iv",
",",
")",
"key_ciphertext",
"=",
"encrypted_wrapped_key",
".",
"ciphertext",
"+",
"encrypted_wrapped_key",
".",
"tag",
"return",
"EncryptedDataKey",
"(",
"key_provider",
"=",
"MasterKeyInfo",
"(",
"provider_id",
"=",
"key_provider",
".",
"provider_id",
",",
"key_info",
"=",
"key_info",
")",
",",
"encrypted_data_key",
"=",
"key_ciphertext",
",",
")"
] | Serializes EncryptedData into a Wrapped EncryptedDataKey.
:param key_provider: Info for Wrapping MasterKey
:type key_provider: aws_encryption_sdk.structures.MasterKeyInfo
:param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key
:type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm
:param bytes wrapping_key_id: Key ID of wrapping MasterKey
:param encrypted_wrapped_key: Encrypted data key
:type encrypted_wrapped_key: aws_encryption_sdk.internal.structures.EncryptedData
:returns: Wrapped EncryptedDataKey
:rtype: aws_encryption_sdk.structures.EncryptedDataKey | [
"Serializes",
"EncryptedData",
"into",
"a",
"Wrapped",
"EncryptedDataKey",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/serialize.py#L291-L321 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/encryption_context.py | assemble_content_aad | def assemble_content_aad(message_id, aad_content_string, seq_num, length):
"""Assembles the Body AAD string for a message body structure.
:param message_id: Message ID
:type message_id: str
:param aad_content_string: ContentAADString object for frame type
:type aad_content_string: aws_encryption_sdk.identifiers.ContentAADString
:param seq_num: Sequence number of frame
:type seq_num: int
:param length: Content Length
:type length: int
:returns: Properly formatted AAD bytes for message body structure.
:rtype: bytes
:raises SerializationError: if aad_content_string is not known
"""
if not isinstance(aad_content_string, aws_encryption_sdk.identifiers.ContentAADString):
raise SerializationError("Unknown aad_content_string")
fmt = ">16s{}sIQ".format(len(aad_content_string.value))
return struct.pack(fmt, message_id, aad_content_string.value, seq_num, length) | python | def assemble_content_aad(message_id, aad_content_string, seq_num, length):
"""Assembles the Body AAD string for a message body structure.
:param message_id: Message ID
:type message_id: str
:param aad_content_string: ContentAADString object for frame type
:type aad_content_string: aws_encryption_sdk.identifiers.ContentAADString
:param seq_num: Sequence number of frame
:type seq_num: int
:param length: Content Length
:type length: int
:returns: Properly formatted AAD bytes for message body structure.
:rtype: bytes
:raises SerializationError: if aad_content_string is not known
"""
if not isinstance(aad_content_string, aws_encryption_sdk.identifiers.ContentAADString):
raise SerializationError("Unknown aad_content_string")
fmt = ">16s{}sIQ".format(len(aad_content_string.value))
return struct.pack(fmt, message_id, aad_content_string.value, seq_num, length) | [
"def",
"assemble_content_aad",
"(",
"message_id",
",",
"aad_content_string",
",",
"seq_num",
",",
"length",
")",
":",
"if",
"not",
"isinstance",
"(",
"aad_content_string",
",",
"aws_encryption_sdk",
".",
"identifiers",
".",
"ContentAADString",
")",
":",
"raise",
"SerializationError",
"(",
"\"Unknown aad_content_string\"",
")",
"fmt",
"=",
"\">16s{}sIQ\"",
".",
"format",
"(",
"len",
"(",
"aad_content_string",
".",
"value",
")",
")",
"return",
"struct",
".",
"pack",
"(",
"fmt",
",",
"message_id",
",",
"aad_content_string",
".",
"value",
",",
"seq_num",
",",
"length",
")"
] | Assembles the Body AAD string for a message body structure.
:param message_id: Message ID
:type message_id: str
:param aad_content_string: ContentAADString object for frame type
:type aad_content_string: aws_encryption_sdk.identifiers.ContentAADString
:param seq_num: Sequence number of frame
:type seq_num: int
:param length: Content Length
:type length: int
:returns: Properly formatted AAD bytes for message body structure.
:rtype: bytes
:raises SerializationError: if aad_content_string is not known | [
"Assembles",
"the",
"Body",
"AAD",
"string",
"for",
"a",
"message",
"body",
"structure",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/encryption_context.py#L29-L47 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/encryption_context.py | serialize_encryption_context | def serialize_encryption_context(encryption_context):
"""Serializes the contents of a dictionary into a byte string.
:param dict encryption_context: Dictionary of encrytion context keys/values.
:returns: Serialized encryption context
:rtype: bytes
"""
if not encryption_context:
return bytes()
serialized_context = bytearray()
dict_size = len(encryption_context)
if dict_size > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
raise SerializationError("The encryption context contains too many elements.")
serialized_context.extend(struct.pack(">H", dict_size))
# Encode strings first to catch bad values.
encryption_context_list = []
for key, value in encryption_context.items():
try:
if isinstance(key, bytes):
key = codecs.decode(key)
if isinstance(value, bytes):
value = codecs.decode(value)
encryption_context_list.append(
(aws_encryption_sdk.internal.str_ops.to_bytes(key), aws_encryption_sdk.internal.str_ops.to_bytes(value))
)
except Exception:
raise SerializationError(
"Cannot encode dictionary key or value using {}.".format(aws_encryption_sdk.internal.defaults.ENCODING)
)
for key, value in sorted(encryption_context_list, key=lambda x: x[0]):
serialized_context.extend(
struct.pack(
">H{key_size}sH{value_size}s".format(key_size=len(key), value_size=len(value)),
len(key),
key,
len(value),
value,
)
)
if len(serialized_context) > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
raise SerializationError("The serialized context is too large.")
return bytes(serialized_context) | python | def serialize_encryption_context(encryption_context):
"""Serializes the contents of a dictionary into a byte string.
:param dict encryption_context: Dictionary of encrytion context keys/values.
:returns: Serialized encryption context
:rtype: bytes
"""
if not encryption_context:
return bytes()
serialized_context = bytearray()
dict_size = len(encryption_context)
if dict_size > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
raise SerializationError("The encryption context contains too many elements.")
serialized_context.extend(struct.pack(">H", dict_size))
# Encode strings first to catch bad values.
encryption_context_list = []
for key, value in encryption_context.items():
try:
if isinstance(key, bytes):
key = codecs.decode(key)
if isinstance(value, bytes):
value = codecs.decode(value)
encryption_context_list.append(
(aws_encryption_sdk.internal.str_ops.to_bytes(key), aws_encryption_sdk.internal.str_ops.to_bytes(value))
)
except Exception:
raise SerializationError(
"Cannot encode dictionary key or value using {}.".format(aws_encryption_sdk.internal.defaults.ENCODING)
)
for key, value in sorted(encryption_context_list, key=lambda x: x[0]):
serialized_context.extend(
struct.pack(
">H{key_size}sH{value_size}s".format(key_size=len(key), value_size=len(value)),
len(key),
key,
len(value),
value,
)
)
if len(serialized_context) > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
raise SerializationError("The serialized context is too large.")
return bytes(serialized_context) | [
"def",
"serialize_encryption_context",
"(",
"encryption_context",
")",
":",
"if",
"not",
"encryption_context",
":",
"return",
"bytes",
"(",
")",
"serialized_context",
"=",
"bytearray",
"(",
")",
"dict_size",
"=",
"len",
"(",
"encryption_context",
")",
"if",
"dict_size",
">",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"MAX_BYTE_ARRAY_SIZE",
":",
"raise",
"SerializationError",
"(",
"\"The encryption context contains too many elements.\"",
")",
"serialized_context",
".",
"extend",
"(",
"struct",
".",
"pack",
"(",
"\">H\"",
",",
"dict_size",
")",
")",
"# Encode strings first to catch bad values.",
"encryption_context_list",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"encryption_context",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"key",
",",
"bytes",
")",
":",
"key",
"=",
"codecs",
".",
"decode",
"(",
"key",
")",
"if",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"value",
"=",
"codecs",
".",
"decode",
"(",
"value",
")",
"encryption_context_list",
".",
"append",
"(",
"(",
"aws_encryption_sdk",
".",
"internal",
".",
"str_ops",
".",
"to_bytes",
"(",
"key",
")",
",",
"aws_encryption_sdk",
".",
"internal",
".",
"str_ops",
".",
"to_bytes",
"(",
"value",
")",
")",
")",
"except",
"Exception",
":",
"raise",
"SerializationError",
"(",
"\"Cannot encode dictionary key or value using {}.\"",
".",
"format",
"(",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"ENCODING",
")",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"encryption_context_list",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
":",
"serialized_context",
".",
"extend",
"(",
"struct",
".",
"pack",
"(",
"\">H{key_size}sH{value_size}s\"",
".",
"format",
"(",
"key_size",
"=",
"len",
"(",
"key",
")",
",",
"value_size",
"=",
"len",
"(",
"value",
")",
")",
",",
"len",
"(",
"key",
")",
",",
"key",
",",
"len",
"(",
"value",
")",
",",
"value",
",",
")",
")",
"if",
"len",
"(",
"serialized_context",
")",
">",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"MAX_BYTE_ARRAY_SIZE",
":",
"raise",
"SerializationError",
"(",
"\"The serialized context is too large.\"",
")",
"return",
"bytes",
"(",
"serialized_context",
")"
] | Serializes the contents of a dictionary into a byte string.
:param dict encryption_context: Dictionary of encrytion context keys/values.
:returns: Serialized encryption context
:rtype: bytes | [
"Serializes",
"the",
"contents",
"of",
"a",
"dictionary",
"into",
"a",
"byte",
"string",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/encryption_context.py#L50-L96 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/encryption_context.py | read_short | def read_short(source, offset):
"""Reads a number from a byte array.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:returns: Read number and offset at point after read data
:rtype: tuple of ints
:raises: SerializationError if unable to unpack
"""
try:
(short,) = struct.unpack_from(">H", source, offset)
return short, offset + struct.calcsize(">H")
except struct.error:
raise SerializationError("Bad format of serialized context.") | python | def read_short(source, offset):
"""Reads a number from a byte array.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:returns: Read number and offset at point after read data
:rtype: tuple of ints
:raises: SerializationError if unable to unpack
"""
try:
(short,) = struct.unpack_from(">H", source, offset)
return short, offset + struct.calcsize(">H")
except struct.error:
raise SerializationError("Bad format of serialized context.") | [
"def",
"read_short",
"(",
"source",
",",
"offset",
")",
":",
"try",
":",
"(",
"short",
",",
")",
"=",
"struct",
".",
"unpack_from",
"(",
"\">H\"",
",",
"source",
",",
"offset",
")",
"return",
"short",
",",
"offset",
"+",
"struct",
".",
"calcsize",
"(",
"\">H\"",
")",
"except",
"struct",
".",
"error",
":",
"raise",
"SerializationError",
"(",
"\"Bad format of serialized context.\"",
")"
] | Reads a number from a byte array.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:returns: Read number and offset at point after read data
:rtype: tuple of ints
:raises: SerializationError if unable to unpack | [
"Reads",
"a",
"number",
"from",
"a",
"byte",
"array",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/encryption_context.py#L99-L112 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/encryption_context.py | read_string | def read_string(source, offset, length):
"""Reads a string from a byte string.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:param int length: Length of string to read
:returns: Read string and offset at point after read data
:rtype: tuple of str and int
:raises SerializationError: if unable to unpack
"""
end = offset + length
try:
return (codecs.decode(source[offset:end], aws_encryption_sdk.internal.defaults.ENCODING), end)
except Exception:
raise SerializationError("Bad format of serialized context.") | python | def read_string(source, offset, length):
"""Reads a string from a byte string.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:param int length: Length of string to read
:returns: Read string and offset at point after read data
:rtype: tuple of str and int
:raises SerializationError: if unable to unpack
"""
end = offset + length
try:
return (codecs.decode(source[offset:end], aws_encryption_sdk.internal.defaults.ENCODING), end)
except Exception:
raise SerializationError("Bad format of serialized context.") | [
"def",
"read_string",
"(",
"source",
",",
"offset",
",",
"length",
")",
":",
"end",
"=",
"offset",
"+",
"length",
"try",
":",
"return",
"(",
"codecs",
".",
"decode",
"(",
"source",
"[",
"offset",
":",
"end",
"]",
",",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"ENCODING",
")",
",",
"end",
")",
"except",
"Exception",
":",
"raise",
"SerializationError",
"(",
"\"Bad format of serialized context.\"",
")"
] | Reads a string from a byte string.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:param int length: Length of string to read
:returns: Read string and offset at point after read data
:rtype: tuple of str and int
:raises SerializationError: if unable to unpack | [
"Reads",
"a",
"string",
"from",
"a",
"byte",
"string",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/encryption_context.py#L115-L129 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/encryption_context.py | deserialize_encryption_context | def deserialize_encryption_context(serialized_encryption_context):
"""Deserializes the contents of a byte string into a dictionary.
:param bytes serialized_encryption_context: Source byte string containing serialized dictionary
:returns: Deserialized encryption context
:rtype: dict
:raises SerializationError: if serialized encryption context is too large
:raises SerializationError: if duplicate key found in serialized encryption context
:raises SerializationError: if malformed data found in serialized encryption context
"""
if len(serialized_encryption_context) > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
raise SerializationError("Serialized context is too long.")
if serialized_encryption_context == b"":
_LOGGER.debug("No encryption context data found")
return {}
deserialized_size = 0
encryption_context = {}
dict_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)
_LOGGER.debug("Found %d keys", dict_size)
for _ in range(dict_size):
key_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)
key, deserialized_size = read_string(
source=serialized_encryption_context, offset=deserialized_size, length=key_size
)
value_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)
value, deserialized_size = read_string(
source=serialized_encryption_context, offset=deserialized_size, length=value_size
)
if key in encryption_context:
raise SerializationError("Duplicate key in serialized context.")
encryption_context[key] = value
if deserialized_size != len(serialized_encryption_context):
raise SerializationError("Formatting error: Extra data in serialized context.")
return encryption_context | python | def deserialize_encryption_context(serialized_encryption_context):
"""Deserializes the contents of a byte string into a dictionary.
:param bytes serialized_encryption_context: Source byte string containing serialized dictionary
:returns: Deserialized encryption context
:rtype: dict
:raises SerializationError: if serialized encryption context is too large
:raises SerializationError: if duplicate key found in serialized encryption context
:raises SerializationError: if malformed data found in serialized encryption context
"""
if len(serialized_encryption_context) > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
raise SerializationError("Serialized context is too long.")
if serialized_encryption_context == b"":
_LOGGER.debug("No encryption context data found")
return {}
deserialized_size = 0
encryption_context = {}
dict_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)
_LOGGER.debug("Found %d keys", dict_size)
for _ in range(dict_size):
key_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)
key, deserialized_size = read_string(
source=serialized_encryption_context, offset=deserialized_size, length=key_size
)
value_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)
value, deserialized_size = read_string(
source=serialized_encryption_context, offset=deserialized_size, length=value_size
)
if key in encryption_context:
raise SerializationError("Duplicate key in serialized context.")
encryption_context[key] = value
if deserialized_size != len(serialized_encryption_context):
raise SerializationError("Formatting error: Extra data in serialized context.")
return encryption_context | [
"def",
"deserialize_encryption_context",
"(",
"serialized_encryption_context",
")",
":",
"if",
"len",
"(",
"serialized_encryption_context",
")",
">",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"MAX_BYTE_ARRAY_SIZE",
":",
"raise",
"SerializationError",
"(",
"\"Serialized context is too long.\"",
")",
"if",
"serialized_encryption_context",
"==",
"b\"\"",
":",
"_LOGGER",
".",
"debug",
"(",
"\"No encryption context data found\"",
")",
"return",
"{",
"}",
"deserialized_size",
"=",
"0",
"encryption_context",
"=",
"{",
"}",
"dict_size",
",",
"deserialized_size",
"=",
"read_short",
"(",
"source",
"=",
"serialized_encryption_context",
",",
"offset",
"=",
"deserialized_size",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Found %d keys\"",
",",
"dict_size",
")",
"for",
"_",
"in",
"range",
"(",
"dict_size",
")",
":",
"key_size",
",",
"deserialized_size",
"=",
"read_short",
"(",
"source",
"=",
"serialized_encryption_context",
",",
"offset",
"=",
"deserialized_size",
")",
"key",
",",
"deserialized_size",
"=",
"read_string",
"(",
"source",
"=",
"serialized_encryption_context",
",",
"offset",
"=",
"deserialized_size",
",",
"length",
"=",
"key_size",
")",
"value_size",
",",
"deserialized_size",
"=",
"read_short",
"(",
"source",
"=",
"serialized_encryption_context",
",",
"offset",
"=",
"deserialized_size",
")",
"value",
",",
"deserialized_size",
"=",
"read_string",
"(",
"source",
"=",
"serialized_encryption_context",
",",
"offset",
"=",
"deserialized_size",
",",
"length",
"=",
"value_size",
")",
"if",
"key",
"in",
"encryption_context",
":",
"raise",
"SerializationError",
"(",
"\"Duplicate key in serialized context.\"",
")",
"encryption_context",
"[",
"key",
"]",
"=",
"value",
"if",
"deserialized_size",
"!=",
"len",
"(",
"serialized_encryption_context",
")",
":",
"raise",
"SerializationError",
"(",
"\"Formatting error: Extra data in serialized context.\"",
")",
"return",
"encryption_context"
] | Deserializes the contents of a byte string into a dictionary.
:param bytes serialized_encryption_context: Source byte string containing serialized dictionary
:returns: Deserialized encryption context
:rtype: dict
:raises SerializationError: if serialized encryption context is too large
:raises SerializationError: if duplicate key found in serialized encryption context
:raises SerializationError: if malformed data found in serialized encryption context | [
"Deserializes",
"the",
"contents",
"of",
"a",
"byte",
"string",
"into",
"a",
"dictionary",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/encryption_context.py#L132-L170 | train |
aws/aws-encryption-sdk-python | decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/null.py | NullMasterKey.owns_data_key | def owns_data_key(self, data_key: DataKey) -> bool:
"""Determine whether the data key is owned by a ``null`` or ``zero`` provider.
:param data_key: Data key to evaluate
:type data_key: :class:`aws_encryption_sdk.structures.DataKey`,
:class:`aws_encryption_sdk.structures.RawDataKey`,
or :class:`aws_encryption_sdk.structures.EncryptedDataKey`
:returns: Boolean statement of ownership
:rtype: bool
"""
return data_key.key_provider.provider_id in self._allowed_provider_ids | python | def owns_data_key(self, data_key: DataKey) -> bool:
"""Determine whether the data key is owned by a ``null`` or ``zero`` provider.
:param data_key: Data key to evaluate
:type data_key: :class:`aws_encryption_sdk.structures.DataKey`,
:class:`aws_encryption_sdk.structures.RawDataKey`,
or :class:`aws_encryption_sdk.structures.EncryptedDataKey`
:returns: Boolean statement of ownership
:rtype: bool
"""
return data_key.key_provider.provider_id in self._allowed_provider_ids | [
"def",
"owns_data_key",
"(",
"self",
",",
"data_key",
":",
"DataKey",
")",
"->",
"bool",
":",
"return",
"data_key",
".",
"key_provider",
".",
"provider_id",
"in",
"self",
".",
"_allowed_provider_ids"
] | Determine whether the data key is owned by a ``null`` or ``zero`` provider.
:param data_key: Data key to evaluate
:type data_key: :class:`aws_encryption_sdk.structures.DataKey`,
:class:`aws_encryption_sdk.structures.RawDataKey`,
or :class:`aws_encryption_sdk.structures.EncryptedDataKey`
:returns: Boolean statement of ownership
:rtype: bool | [
"Determine",
"whether",
"the",
"data",
"key",
"is",
"owned",
"by",
"a",
"null",
"or",
"zero",
"provider",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/null.py#L46-L56 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/iv.py | frame_iv | def frame_iv(algorithm, sequence_number):
"""Builds the deterministic IV for a body frame.
:param algorithm: Algorithm for which to build IV
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int sequence_number: Frame sequence number
:returns: Generated IV
:rtype: bytes
:raises ActionNotAllowedError: if sequence number of out bounds
"""
if sequence_number < 1 or sequence_number > MAX_FRAME_COUNT:
raise ActionNotAllowedError(
"Invalid frame sequence number: {actual}\nMust be between 1 and {max}".format(
actual=sequence_number, max=MAX_FRAME_COUNT
)
)
prefix_len = algorithm.iv_len - 4
prefix = b"\x00" * prefix_len
return prefix + struct.pack(">I", sequence_number) | python | def frame_iv(algorithm, sequence_number):
"""Builds the deterministic IV for a body frame.
:param algorithm: Algorithm for which to build IV
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int sequence_number: Frame sequence number
:returns: Generated IV
:rtype: bytes
:raises ActionNotAllowedError: if sequence number of out bounds
"""
if sequence_number < 1 or sequence_number > MAX_FRAME_COUNT:
raise ActionNotAllowedError(
"Invalid frame sequence number: {actual}\nMust be between 1 and {max}".format(
actual=sequence_number, max=MAX_FRAME_COUNT
)
)
prefix_len = algorithm.iv_len - 4
prefix = b"\x00" * prefix_len
return prefix + struct.pack(">I", sequence_number) | [
"def",
"frame_iv",
"(",
"algorithm",
",",
"sequence_number",
")",
":",
"if",
"sequence_number",
"<",
"1",
"or",
"sequence_number",
">",
"MAX_FRAME_COUNT",
":",
"raise",
"ActionNotAllowedError",
"(",
"\"Invalid frame sequence number: {actual}\\nMust be between 1 and {max}\"",
".",
"format",
"(",
"actual",
"=",
"sequence_number",
",",
"max",
"=",
"MAX_FRAME_COUNT",
")",
")",
"prefix_len",
"=",
"algorithm",
".",
"iv_len",
"-",
"4",
"prefix",
"=",
"b\"\\x00\"",
"*",
"prefix_len",
"return",
"prefix",
"+",
"struct",
".",
"pack",
"(",
"\">I\"",
",",
"sequence_number",
")"
] | Builds the deterministic IV for a body frame.
:param algorithm: Algorithm for which to build IV
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int sequence_number: Frame sequence number
:returns: Generated IV
:rtype: bytes
:raises ActionNotAllowedError: if sequence number of out bounds | [
"Builds",
"the",
"deterministic",
"IV",
"for",
"a",
"body",
"frame",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/iv.py#L46-L64 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/identifiers.py | EncryptionSuite.valid_kdf | def valid_kdf(self, kdf):
"""Determine whether a KDFSuite can be used with this EncryptionSuite.
:param kdf: KDFSuite to evaluate
:type kdf: aws_encryption_sdk.identifiers.KDFSuite
:rtype: bool
"""
if kdf.input_length is None:
return True
if self.data_key_length > kdf.input_length(self):
raise InvalidAlgorithmError(
"Invalid Algorithm definition: data_key_len must not be greater than kdf_input_len"
)
return True | python | def valid_kdf(self, kdf):
"""Determine whether a KDFSuite can be used with this EncryptionSuite.
:param kdf: KDFSuite to evaluate
:type kdf: aws_encryption_sdk.identifiers.KDFSuite
:rtype: bool
"""
if kdf.input_length is None:
return True
if self.data_key_length > kdf.input_length(self):
raise InvalidAlgorithmError(
"Invalid Algorithm definition: data_key_len must not be greater than kdf_input_len"
)
return True | [
"def",
"valid_kdf",
"(",
"self",
",",
"kdf",
")",
":",
"if",
"kdf",
".",
"input_length",
"is",
"None",
":",
"return",
"True",
"if",
"self",
".",
"data_key_length",
">",
"kdf",
".",
"input_length",
"(",
"self",
")",
":",
"raise",
"InvalidAlgorithmError",
"(",
"\"Invalid Algorithm definition: data_key_len must not be greater than kdf_input_len\"",
")",
"return",
"True"
] | Determine whether a KDFSuite can be used with this EncryptionSuite.
:param kdf: KDFSuite to evaluate
:type kdf: aws_encryption_sdk.identifiers.KDFSuite
:rtype: bool | [
"Determine",
"whether",
"a",
"KDFSuite",
"can",
"be",
"used",
"with",
"this",
"EncryptionSuite",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/identifiers.py#L63-L78 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/__init__.py | header_length | def header_length(header):
"""Calculates the ciphertext message header length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
# Because encrypted data key lengths may not be knowable until the ciphertext
# is received from the providers, just serialize the header directly.
header_length = len(serialize_header(header))
header_length += header.algorithm.iv_len # Header Authentication IV
header_length += header.algorithm.auth_len # Header Authentication Tag
return header_length | python | def header_length(header):
"""Calculates the ciphertext message header length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
# Because encrypted data key lengths may not be knowable until the ciphertext
# is received from the providers, just serialize the header directly.
header_length = len(serialize_header(header))
header_length += header.algorithm.iv_len # Header Authentication IV
header_length += header.algorithm.auth_len # Header Authentication Tag
return header_length | [
"def",
"header_length",
"(",
"header",
")",
":",
"# Because encrypted data key lengths may not be knowable until the ciphertext",
"# is received from the providers, just serialize the header directly.",
"header_length",
"=",
"len",
"(",
"serialize_header",
"(",
"header",
")",
")",
"header_length",
"+=",
"header",
".",
"algorithm",
".",
"iv_len",
"# Header Authentication IV",
"header_length",
"+=",
"header",
".",
"algorithm",
".",
"auth_len",
"# Header Authentication Tag",
"return",
"header_length"
] | Calculates the ciphertext message header length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int | [
"Calculates",
"the",
"ciphertext",
"message",
"header",
"length",
"given",
"a",
"complete",
"header",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L17-L29 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/__init__.py | _non_framed_body_length | def _non_framed_body_length(header, plaintext_length):
"""Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int
"""
body_length = header.algorithm.iv_len # IV
body_length += 8 # Encrypted Content Length
body_length += plaintext_length # Encrypted Content
body_length += header.algorithm.auth_len # Authentication Tag
return body_length | python | def _non_framed_body_length(header, plaintext_length):
"""Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int
"""
body_length = header.algorithm.iv_len # IV
body_length += 8 # Encrypted Content Length
body_length += plaintext_length # Encrypted Content
body_length += header.algorithm.auth_len # Authentication Tag
return body_length | [
"def",
"_non_framed_body_length",
"(",
"header",
",",
"plaintext_length",
")",
":",
"body_length",
"=",
"header",
".",
"algorithm",
".",
"iv_len",
"# IV",
"body_length",
"+=",
"8",
"# Encrypted Content Length",
"body_length",
"+=",
"plaintext_length",
"# Encrypted Content",
"body_length",
"+=",
"header",
".",
"algorithm",
".",
"auth_len",
"# Authentication Tag",
"return",
"body_length"
] | Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int | [
"Calculates",
"the",
"length",
"of",
"a",
"non",
"-",
"framed",
"message",
"body",
"given",
"a",
"complete",
"header",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L32-L44 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/__init__.py | _standard_frame_length | def _standard_frame_length(header):
"""Calculates the length of a standard ciphertext frame, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
frame_length = 4 # Sequence Number
frame_length += header.algorithm.iv_len # IV
frame_length += header.frame_length # Encrypted Content
frame_length += header.algorithm.auth_len # Authentication Tag
return frame_length | python | def _standard_frame_length(header):
"""Calculates the length of a standard ciphertext frame, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
frame_length = 4 # Sequence Number
frame_length += header.algorithm.iv_len # IV
frame_length += header.frame_length # Encrypted Content
frame_length += header.algorithm.auth_len # Authentication Tag
return frame_length | [
"def",
"_standard_frame_length",
"(",
"header",
")",
":",
"frame_length",
"=",
"4",
"# Sequence Number",
"frame_length",
"+=",
"header",
".",
"algorithm",
".",
"iv_len",
"# IV",
"frame_length",
"+=",
"header",
".",
"frame_length",
"# Encrypted Content",
"frame_length",
"+=",
"header",
".",
"algorithm",
".",
"auth_len",
"# Authentication Tag",
"return",
"frame_length"
] | Calculates the length of a standard ciphertext frame, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int | [
"Calculates",
"the",
"length",
"of",
"a",
"standard",
"ciphertext",
"frame",
"given",
"a",
"complete",
"header",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L47-L58 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/__init__.py | _final_frame_length | def _final_frame_length(header, final_frame_bytes):
"""Calculates the length of a final ciphertext frame, given a complete header
and the number of bytes of ciphertext in the final frame.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int final_frame_bytes: Bytes of ciphertext in the final frame
:rtype: int
"""
final_frame_length = 4 # Sequence Number End
final_frame_length += 4 # Sequence Number
final_frame_length += header.algorithm.iv_len # IV
final_frame_length += 4 # Encrypted Content Length
final_frame_length += final_frame_bytes # Encrypted Content
final_frame_length += header.algorithm.auth_len # Authentication Tag
return final_frame_length | python | def _final_frame_length(header, final_frame_bytes):
"""Calculates the length of a final ciphertext frame, given a complete header
and the number of bytes of ciphertext in the final frame.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int final_frame_bytes: Bytes of ciphertext in the final frame
:rtype: int
"""
final_frame_length = 4 # Sequence Number End
final_frame_length += 4 # Sequence Number
final_frame_length += header.algorithm.iv_len # IV
final_frame_length += 4 # Encrypted Content Length
final_frame_length += final_frame_bytes # Encrypted Content
final_frame_length += header.algorithm.auth_len # Authentication Tag
return final_frame_length | [
"def",
"_final_frame_length",
"(",
"header",
",",
"final_frame_bytes",
")",
":",
"final_frame_length",
"=",
"4",
"# Sequence Number End",
"final_frame_length",
"+=",
"4",
"# Sequence Number",
"final_frame_length",
"+=",
"header",
".",
"algorithm",
".",
"iv_len",
"# IV",
"final_frame_length",
"+=",
"4",
"# Encrypted Content Length",
"final_frame_length",
"+=",
"final_frame_bytes",
"# Encrypted Content",
"final_frame_length",
"+=",
"header",
".",
"algorithm",
".",
"auth_len",
"# Authentication Tag",
"return",
"final_frame_length"
] | Calculates the length of a final ciphertext frame, given a complete header
and the number of bytes of ciphertext in the final frame.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int final_frame_bytes: Bytes of ciphertext in the final frame
:rtype: int | [
"Calculates",
"the",
"length",
"of",
"a",
"final",
"ciphertext",
"frame",
"given",
"a",
"complete",
"header",
"and",
"the",
"number",
"of",
"bytes",
"of",
"ciphertext",
"in",
"the",
"final",
"frame",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L61-L76 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/__init__.py | body_length | def body_length(header, plaintext_length):
"""Calculates the ciphertext message body length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int
"""
body_length = 0
if header.frame_length == 0: # Non-framed
body_length += _non_framed_body_length(header, plaintext_length)
else: # Framed
frames, final_frame_bytes = divmod(plaintext_length, header.frame_length)
body_length += frames * _standard_frame_length(header)
body_length += _final_frame_length(header, final_frame_bytes) # Final frame is always written
return body_length | python | def body_length(header, plaintext_length):
"""Calculates the ciphertext message body length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int
"""
body_length = 0
if header.frame_length == 0: # Non-framed
body_length += _non_framed_body_length(header, plaintext_length)
else: # Framed
frames, final_frame_bytes = divmod(plaintext_length, header.frame_length)
body_length += frames * _standard_frame_length(header)
body_length += _final_frame_length(header, final_frame_bytes) # Final frame is always written
return body_length | [
"def",
"body_length",
"(",
"header",
",",
"plaintext_length",
")",
":",
"body_length",
"=",
"0",
"if",
"header",
".",
"frame_length",
"==",
"0",
":",
"# Non-framed",
"body_length",
"+=",
"_non_framed_body_length",
"(",
"header",
",",
"plaintext_length",
")",
"else",
":",
"# Framed",
"frames",
",",
"final_frame_bytes",
"=",
"divmod",
"(",
"plaintext_length",
",",
"header",
".",
"frame_length",
")",
"body_length",
"+=",
"frames",
"*",
"_standard_frame_length",
"(",
"header",
")",
"body_length",
"+=",
"_final_frame_length",
"(",
"header",
",",
"final_frame_bytes",
")",
"# Final frame is always written",
"return",
"body_length"
] | Calculates the ciphertext message body length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int | [
"Calculates",
"the",
"ciphertext",
"message",
"body",
"length",
"given",
"a",
"complete",
"header",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L79-L94 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/__init__.py | footer_length | def footer_length(header):
"""Calculates the ciphertext message footer length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
footer_length = 0
if header.algorithm.signing_algorithm_info is not None:
footer_length += 2 # Signature Length
footer_length += header.algorithm.signature_len # Signature
return footer_length | python | def footer_length(header):
"""Calculates the ciphertext message footer length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
footer_length = 0
if header.algorithm.signing_algorithm_info is not None:
footer_length += 2 # Signature Length
footer_length += header.algorithm.signature_len # Signature
return footer_length | [
"def",
"footer_length",
"(",
"header",
")",
":",
"footer_length",
"=",
"0",
"if",
"header",
".",
"algorithm",
".",
"signing_algorithm_info",
"is",
"not",
"None",
":",
"footer_length",
"+=",
"2",
"# Signature Length",
"footer_length",
"+=",
"header",
".",
"algorithm",
".",
"signature_len",
"# Signature",
"return",
"footer_length"
] | Calculates the ciphertext message footer length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int | [
"Calculates",
"the",
"ciphertext",
"message",
"footer",
"length",
"given",
"a",
"complete",
"header",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L97-L108 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/__init__.py | ciphertext_length | def ciphertext_length(header, plaintext_length):
"""Calculates the complete ciphertext message length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int
"""
ciphertext_length = header_length(header)
ciphertext_length += body_length(header, plaintext_length)
ciphertext_length += footer_length(header)
return ciphertext_length | python | def ciphertext_length(header, plaintext_length):
"""Calculates the complete ciphertext message length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int
"""
ciphertext_length = header_length(header)
ciphertext_length += body_length(header, plaintext_length)
ciphertext_length += footer_length(header)
return ciphertext_length | [
"def",
"ciphertext_length",
"(",
"header",
",",
"plaintext_length",
")",
":",
"ciphertext_length",
"=",
"header_length",
"(",
"header",
")",
"ciphertext_length",
"+=",
"body_length",
"(",
"header",
",",
"plaintext_length",
")",
"ciphertext_length",
"+=",
"footer_length",
"(",
"header",
")",
"return",
"ciphertext_length"
] | Calculates the complete ciphertext message length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int | [
"Calculates",
"the",
"complete",
"ciphertext",
"message",
"length",
"given",
"a",
"complete",
"header",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L111-L122 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/raw.py | RawMasterKey.owns_data_key | def owns_data_key(self, data_key):
"""Determines if data_key object is owned by this RawMasterKey.
:param data_key: Data key to evaluate
:type data_key: :class:`aws_encryption_sdk.structures.DataKey`,
:class:`aws_encryption_sdk.structures.RawDataKey`,
or :class:`aws_encryption_sdk.structures.EncryptedDataKey`
:returns: Boolean statement of ownership
:rtype: bool
"""
expected_key_info_len = -1
if (
self.config.wrapping_key.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC
and data_key.key_provider == self.key_provider
):
return True
elif self.config.wrapping_key.wrapping_algorithm.encryption_type is EncryptionType.SYMMETRIC:
expected_key_info_len = (
len(self._key_info_prefix) + self.config.wrapping_key.wrapping_algorithm.algorithm.iv_len
)
if (
data_key.key_provider.provider_id == self.provider_id
and len(data_key.key_provider.key_info) == expected_key_info_len
and data_key.key_provider.key_info.startswith(self._key_info_prefix)
):
return True
_LOGGER.debug(
(
"RawMasterKey does not own data_key: %s\n"
"Expected provider_id: %s\n"
"Expected key_info len: %s\n"
"Expected key_info prefix: %s"
),
data_key,
self.provider_id,
expected_key_info_len,
self._key_info_prefix,
)
return False | python | def owns_data_key(self, data_key):
"""Determines if data_key object is owned by this RawMasterKey.
:param data_key: Data key to evaluate
:type data_key: :class:`aws_encryption_sdk.structures.DataKey`,
:class:`aws_encryption_sdk.structures.RawDataKey`,
or :class:`aws_encryption_sdk.structures.EncryptedDataKey`
:returns: Boolean statement of ownership
:rtype: bool
"""
expected_key_info_len = -1
if (
self.config.wrapping_key.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC
and data_key.key_provider == self.key_provider
):
return True
elif self.config.wrapping_key.wrapping_algorithm.encryption_type is EncryptionType.SYMMETRIC:
expected_key_info_len = (
len(self._key_info_prefix) + self.config.wrapping_key.wrapping_algorithm.algorithm.iv_len
)
if (
data_key.key_provider.provider_id == self.provider_id
and len(data_key.key_provider.key_info) == expected_key_info_len
and data_key.key_provider.key_info.startswith(self._key_info_prefix)
):
return True
_LOGGER.debug(
(
"RawMasterKey does not own data_key: %s\n"
"Expected provider_id: %s\n"
"Expected key_info len: %s\n"
"Expected key_info prefix: %s"
),
data_key,
self.provider_id,
expected_key_info_len,
self._key_info_prefix,
)
return False | [
"def",
"owns_data_key",
"(",
"self",
",",
"data_key",
")",
":",
"expected_key_info_len",
"=",
"-",
"1",
"if",
"(",
"self",
".",
"config",
".",
"wrapping_key",
".",
"wrapping_algorithm",
".",
"encryption_type",
"is",
"EncryptionType",
".",
"ASYMMETRIC",
"and",
"data_key",
".",
"key_provider",
"==",
"self",
".",
"key_provider",
")",
":",
"return",
"True",
"elif",
"self",
".",
"config",
".",
"wrapping_key",
".",
"wrapping_algorithm",
".",
"encryption_type",
"is",
"EncryptionType",
".",
"SYMMETRIC",
":",
"expected_key_info_len",
"=",
"(",
"len",
"(",
"self",
".",
"_key_info_prefix",
")",
"+",
"self",
".",
"config",
".",
"wrapping_key",
".",
"wrapping_algorithm",
".",
"algorithm",
".",
"iv_len",
")",
"if",
"(",
"data_key",
".",
"key_provider",
".",
"provider_id",
"==",
"self",
".",
"provider_id",
"and",
"len",
"(",
"data_key",
".",
"key_provider",
".",
"key_info",
")",
"==",
"expected_key_info_len",
"and",
"data_key",
".",
"key_provider",
".",
"key_info",
".",
"startswith",
"(",
"self",
".",
"_key_info_prefix",
")",
")",
":",
"return",
"True",
"_LOGGER",
".",
"debug",
"(",
"(",
"\"RawMasterKey does not own data_key: %s\\n\"",
"\"Expected provider_id: %s\\n\"",
"\"Expected key_info len: %s\\n\"",
"\"Expected key_info prefix: %s\"",
")",
",",
"data_key",
",",
"self",
".",
"provider_id",
",",
"expected_key_info_len",
",",
"self",
".",
"_key_info_prefix",
",",
")",
"return",
"False"
] | Determines if data_key object is owned by this RawMasterKey.
:param data_key: Data key to evaluate
:type data_key: :class:`aws_encryption_sdk.structures.DataKey`,
:class:`aws_encryption_sdk.structures.RawDataKey`,
or :class:`aws_encryption_sdk.structures.EncryptedDataKey`
:returns: Boolean statement of ownership
:rtype: bool | [
"Determines",
"if",
"data_key",
"object",
"is",
"owned",
"by",
"this",
"RawMasterKey",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/raw.py#L75-L113 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/key_providers/raw.py | RawMasterKey._encrypt_data_key | def _encrypt_data_key(self, data_key, algorithm, encryption_context):
"""Performs the provider-specific key encryption actions.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this Master Key will encrypt the data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:returns: Decrypted data key
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
:raises EncryptKeyError: if Master Key is unable to encrypt data key
"""
# Raw key string to EncryptedData
encrypted_wrapped_key = self.config.wrapping_key.encrypt(
plaintext_data_key=data_key.data_key, encryption_context=encryption_context
)
# EncryptedData to EncryptedDataKey
return aws_encryption_sdk.internal.formatting.serialize.serialize_wrapped_key(
key_provider=self.key_provider,
wrapping_algorithm=self.config.wrapping_key.wrapping_algorithm,
wrapping_key_id=self.key_id,
encrypted_wrapped_key=encrypted_wrapped_key,
) | python | def _encrypt_data_key(self, data_key, algorithm, encryption_context):
"""Performs the provider-specific key encryption actions.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this Master Key will encrypt the data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:returns: Decrypted data key
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
:raises EncryptKeyError: if Master Key is unable to encrypt data key
"""
# Raw key string to EncryptedData
encrypted_wrapped_key = self.config.wrapping_key.encrypt(
plaintext_data_key=data_key.data_key, encryption_context=encryption_context
)
# EncryptedData to EncryptedDataKey
return aws_encryption_sdk.internal.formatting.serialize.serialize_wrapped_key(
key_provider=self.key_provider,
wrapping_algorithm=self.config.wrapping_key.wrapping_algorithm,
wrapping_key_id=self.key_id,
encrypted_wrapped_key=encrypted_wrapped_key,
) | [
"def",
"_encrypt_data_key",
"(",
"self",
",",
"data_key",
",",
"algorithm",
",",
"encryption_context",
")",
":",
"# Raw key string to EncryptedData",
"encrypted_wrapped_key",
"=",
"self",
".",
"config",
".",
"wrapping_key",
".",
"encrypt",
"(",
"plaintext_data_key",
"=",
"data_key",
".",
"data_key",
",",
"encryption_context",
"=",
"encryption_context",
")",
"# EncryptedData to EncryptedDataKey",
"return",
"aws_encryption_sdk",
".",
"internal",
".",
"formatting",
".",
"serialize",
".",
"serialize_wrapped_key",
"(",
"key_provider",
"=",
"self",
".",
"key_provider",
",",
"wrapping_algorithm",
"=",
"self",
".",
"config",
".",
"wrapping_key",
".",
"wrapping_algorithm",
",",
"wrapping_key_id",
"=",
"self",
".",
"key_id",
",",
"encrypted_wrapped_key",
"=",
"encrypted_wrapped_key",
",",
")"
] | Performs the provider-specific key encryption actions.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this Master Key will encrypt the data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:returns: Decrypted data key
:rtype: aws_encryption_sdk.structures.EncryptedDataKey
:raises EncryptKeyError: if Master Key is unable to encrypt data key | [
"Performs",
"the",
"provider",
"-",
"specific",
"key",
"encryption",
"actions",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/raw.py#L136-L159 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/caches/null.py | NullCryptoMaterialsCache.put_encryption_materials | def put_encryption_materials(self, cache_key, encryption_materials, plaintext_length, entry_hints=None):
"""Does not add encryption materials to the cache since there is no cache to which to add them.
:param bytes cache_key: Identifier for entries in cache
:param encryption_materials: Encryption materials to add to cache
:type encryption_materials: aws_encryption_sdk.materials_managers.EncryptionMaterials
:param int plaintext_length: Length of plaintext associated with this request to the cache
:param entry_hints: Metadata to associate with entry (optional)
:type entry_hints: aws_encryption_sdk.caches.CryptoCacheEntryHints
:rtype: aws_encryption_sdk.caches.CryptoMaterialsCacheEntry
"""
return CryptoMaterialsCacheEntry(cache_key=cache_key, value=encryption_materials) | python | def put_encryption_materials(self, cache_key, encryption_materials, plaintext_length, entry_hints=None):
"""Does not add encryption materials to the cache since there is no cache to which to add them.
:param bytes cache_key: Identifier for entries in cache
:param encryption_materials: Encryption materials to add to cache
:type encryption_materials: aws_encryption_sdk.materials_managers.EncryptionMaterials
:param int plaintext_length: Length of plaintext associated with this request to the cache
:param entry_hints: Metadata to associate with entry (optional)
:type entry_hints: aws_encryption_sdk.caches.CryptoCacheEntryHints
:rtype: aws_encryption_sdk.caches.CryptoMaterialsCacheEntry
"""
return CryptoMaterialsCacheEntry(cache_key=cache_key, value=encryption_materials) | [
"def",
"put_encryption_materials",
"(",
"self",
",",
"cache_key",
",",
"encryption_materials",
",",
"plaintext_length",
",",
"entry_hints",
"=",
"None",
")",
":",
"return",
"CryptoMaterialsCacheEntry",
"(",
"cache_key",
"=",
"cache_key",
",",
"value",
"=",
"encryption_materials",
")"
] | Does not add encryption materials to the cache since there is no cache to which to add them.
:param bytes cache_key: Identifier for entries in cache
:param encryption_materials: Encryption materials to add to cache
:type encryption_materials: aws_encryption_sdk.materials_managers.EncryptionMaterials
:param int plaintext_length: Length of plaintext associated with this request to the cache
:param entry_hints: Metadata to associate with entry (optional)
:type entry_hints: aws_encryption_sdk.caches.CryptoCacheEntryHints
:rtype: aws_encryption_sdk.caches.CryptoMaterialsCacheEntry | [
"Does",
"not",
"add",
"encryption",
"materials",
"to",
"the",
"cache",
"since",
"there",
"is",
"no",
"cache",
"to",
"which",
"to",
"add",
"them",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/caches/null.py#L25-L36 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | _PrehashingAuthenticator._set_signature_type | def _set_signature_type(self):
"""Ensures that the algorithm signature type is a known type and sets a reference value."""
try:
verify_interface(ec.EllipticCurve, self.algorithm.signing_algorithm_info)
return ec.EllipticCurve
except InterfaceNotImplemented:
raise NotSupportedError("Unsupported signing algorithm info") | python | def _set_signature_type(self):
"""Ensures that the algorithm signature type is a known type and sets a reference value."""
try:
verify_interface(ec.EllipticCurve, self.algorithm.signing_algorithm_info)
return ec.EllipticCurve
except InterfaceNotImplemented:
raise NotSupportedError("Unsupported signing algorithm info") | [
"def",
"_set_signature_type",
"(",
"self",
")",
":",
"try",
":",
"verify_interface",
"(",
"ec",
".",
"EllipticCurve",
",",
"self",
".",
"algorithm",
".",
"signing_algorithm_info",
")",
"return",
"ec",
".",
"EllipticCurve",
"except",
"InterfaceNotImplemented",
":",
"raise",
"NotSupportedError",
"(",
"\"Unsupported signing algorithm info\"",
")"
] | Ensures that the algorithm signature type is a known type and sets a reference value. | [
"Ensures",
"that",
"the",
"algorithm",
"signature",
"type",
"is",
"a",
"known",
"type",
"and",
"sets",
"a",
"reference",
"value",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L48-L54 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | Signer.from_key_bytes | def from_key_bytes(cls, algorithm, key_bytes):
"""Builds a `Signer` from an algorithm suite and a raw signing key.
:param algorithm: Algorithm on which to base signer
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key_bytes: Raw signing key
:rtype: aws_encryption_sdk.internal.crypto.Signer
"""
key = serialization.load_der_private_key(data=key_bytes, password=None, backend=default_backend())
return cls(algorithm, key) | python | def from_key_bytes(cls, algorithm, key_bytes):
"""Builds a `Signer` from an algorithm suite and a raw signing key.
:param algorithm: Algorithm on which to base signer
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key_bytes: Raw signing key
:rtype: aws_encryption_sdk.internal.crypto.Signer
"""
key = serialization.load_der_private_key(data=key_bytes, password=None, backend=default_backend())
return cls(algorithm, key) | [
"def",
"from_key_bytes",
"(",
"cls",
",",
"algorithm",
",",
"key_bytes",
")",
":",
"key",
"=",
"serialization",
".",
"load_der_private_key",
"(",
"data",
"=",
"key_bytes",
",",
"password",
"=",
"None",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"return",
"cls",
"(",
"algorithm",
",",
"key",
")"
] | Builds a `Signer` from an algorithm suite and a raw signing key.
:param algorithm: Algorithm on which to base signer
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key_bytes: Raw signing key
:rtype: aws_encryption_sdk.internal.crypto.Signer | [
"Builds",
"a",
"Signer",
"from",
"an",
"algorithm",
"suite",
"and",
"a",
"raw",
"signing",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L74-L83 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | Signer.key_bytes | def key_bytes(self):
"""Returns the raw signing key.
:rtype: bytes
"""
return self.key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
) | python | def key_bytes(self):
"""Returns the raw signing key.
:rtype: bytes
"""
return self.key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
) | [
"def",
"key_bytes",
"(",
"self",
")",
":",
"return",
"self",
".",
"key",
".",
"private_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"DER",
",",
"format",
"=",
"serialization",
".",
"PrivateFormat",
".",
"PKCS8",
",",
"encryption_algorithm",
"=",
"serialization",
".",
"NoEncryption",
"(",
")",
",",
")"
] | Returns the raw signing key.
:rtype: bytes | [
"Returns",
"the",
"raw",
"signing",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L85-L94 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | Signer.finalize | def finalize(self):
"""Finalizes the signer and returns the signature.
:returns: Calculated signer signature
:rtype: bytes
"""
prehashed_digest = self._hasher.finalize()
return _ecc_static_length_signature(key=self.key, algorithm=self.algorithm, digest=prehashed_digest) | python | def finalize(self):
"""Finalizes the signer and returns the signature.
:returns: Calculated signer signature
:rtype: bytes
"""
prehashed_digest = self._hasher.finalize()
return _ecc_static_length_signature(key=self.key, algorithm=self.algorithm, digest=prehashed_digest) | [
"def",
"finalize",
"(",
"self",
")",
":",
"prehashed_digest",
"=",
"self",
".",
"_hasher",
".",
"finalize",
"(",
")",
"return",
"_ecc_static_length_signature",
"(",
"key",
"=",
"self",
".",
"key",
",",
"algorithm",
"=",
"self",
".",
"algorithm",
",",
"digest",
"=",
"prehashed_digest",
")"
] | Finalizes the signer and returns the signature.
:returns: Calculated signer signature
:rtype: bytes | [
"Finalizes",
"the",
"signer",
"and",
"returns",
"the",
"signature",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L114-L121 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | Verifier.from_encoded_point | def from_encoded_point(cls, algorithm, encoded_point):
"""Creates a Verifier object based on the supplied algorithm and encoded compressed ECC curve point.
:param algorithm: Algorithm on which to base verifier
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes encoded_point: ECC public point compressed and encoded with _ecc_encode_compressed_point
:returns: Instance of Verifier generated from encoded point
:rtype: aws_encryption_sdk.internal.crypto.Verifier
"""
return cls(
algorithm=algorithm,
key=_ecc_public_numbers_from_compressed_point(
curve=algorithm.signing_algorithm_info(), compressed_point=base64.b64decode(encoded_point)
).public_key(default_backend()),
) | python | def from_encoded_point(cls, algorithm, encoded_point):
"""Creates a Verifier object based on the supplied algorithm and encoded compressed ECC curve point.
:param algorithm: Algorithm on which to base verifier
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes encoded_point: ECC public point compressed and encoded with _ecc_encode_compressed_point
:returns: Instance of Verifier generated from encoded point
:rtype: aws_encryption_sdk.internal.crypto.Verifier
"""
return cls(
algorithm=algorithm,
key=_ecc_public_numbers_from_compressed_point(
curve=algorithm.signing_algorithm_info(), compressed_point=base64.b64decode(encoded_point)
).public_key(default_backend()),
) | [
"def",
"from_encoded_point",
"(",
"cls",
",",
"algorithm",
",",
"encoded_point",
")",
":",
"return",
"cls",
"(",
"algorithm",
"=",
"algorithm",
",",
"key",
"=",
"_ecc_public_numbers_from_compressed_point",
"(",
"curve",
"=",
"algorithm",
".",
"signing_algorithm_info",
"(",
")",
",",
"compressed_point",
"=",
"base64",
".",
"b64decode",
"(",
"encoded_point",
")",
")",
".",
"public_key",
"(",
"default_backend",
"(",
")",
")",
",",
")"
] | Creates a Verifier object based on the supplied algorithm and encoded compressed ECC curve point.
:param algorithm: Algorithm on which to base verifier
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes encoded_point: ECC public point compressed and encoded with _ecc_encode_compressed_point
:returns: Instance of Verifier generated from encoded point
:rtype: aws_encryption_sdk.internal.crypto.Verifier | [
"Creates",
"a",
"Verifier",
"object",
"based",
"on",
"the",
"supplied",
"algorithm",
"and",
"encoded",
"compressed",
"ECC",
"curve",
"point",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L137-L151 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | Verifier.from_key_bytes | def from_key_bytes(cls, algorithm, key_bytes):
"""Creates a `Verifier` object based on the supplied algorithm and raw verification key.
:param algorithm: Algorithm on which to base verifier
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes encoded_point: Raw verification key
:returns: Instance of Verifier generated from encoded point
:rtype: aws_encryption_sdk.internal.crypto.Verifier
"""
return cls(
algorithm=algorithm, key=serialization.load_der_public_key(data=key_bytes, backend=default_backend())
) | python | def from_key_bytes(cls, algorithm, key_bytes):
"""Creates a `Verifier` object based on the supplied algorithm and raw verification key.
:param algorithm: Algorithm on which to base verifier
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes encoded_point: Raw verification key
:returns: Instance of Verifier generated from encoded point
:rtype: aws_encryption_sdk.internal.crypto.Verifier
"""
return cls(
algorithm=algorithm, key=serialization.load_der_public_key(data=key_bytes, backend=default_backend())
) | [
"def",
"from_key_bytes",
"(",
"cls",
",",
"algorithm",
",",
"key_bytes",
")",
":",
"return",
"cls",
"(",
"algorithm",
"=",
"algorithm",
",",
"key",
"=",
"serialization",
".",
"load_der_public_key",
"(",
"data",
"=",
"key_bytes",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
")"
] | Creates a `Verifier` object based on the supplied algorithm and raw verification key.
:param algorithm: Algorithm on which to base verifier
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes encoded_point: Raw verification key
:returns: Instance of Verifier generated from encoded point
:rtype: aws_encryption_sdk.internal.crypto.Verifier | [
"Creates",
"a",
"Verifier",
"object",
"based",
"on",
"the",
"supplied",
"algorithm",
"and",
"raw",
"verification",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L154-L165 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | Verifier.key_bytes | def key_bytes(self):
"""Returns the raw verification key.
:rtype: bytes
"""
return self.key.public_bytes(
encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo
) | python | def key_bytes(self):
"""Returns the raw verification key.
:rtype: bytes
"""
return self.key.public_bytes(
encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo
) | [
"def",
"key_bytes",
"(",
"self",
")",
":",
"return",
"self",
".",
"key",
".",
"public_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"DER",
",",
"format",
"=",
"serialization",
".",
"PublicFormat",
".",
"SubjectPublicKeyInfo",
")"
] | Returns the raw verification key.
:rtype: bytes | [
"Returns",
"the",
"raw",
"verification",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L167-L174 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/authentication.py | Verifier.verify | def verify(self, signature):
"""Verifies the signature against the current cryptographic verifier state.
:param bytes signature: The signature to verify
"""
prehashed_digest = self._hasher.finalize()
self.key.verify(
signature=signature,
data=prehashed_digest,
signature_algorithm=ec.ECDSA(Prehashed(self.algorithm.signing_hash_type())),
) | python | def verify(self, signature):
"""Verifies the signature against the current cryptographic verifier state.
:param bytes signature: The signature to verify
"""
prehashed_digest = self._hasher.finalize()
self.key.verify(
signature=signature,
data=prehashed_digest,
signature_algorithm=ec.ECDSA(Prehashed(self.algorithm.signing_hash_type())),
) | [
"def",
"verify",
"(",
"self",
",",
"signature",
")",
":",
"prehashed_digest",
"=",
"self",
".",
"_hasher",
".",
"finalize",
"(",
")",
"self",
".",
"key",
".",
"verify",
"(",
"signature",
"=",
"signature",
",",
"data",
"=",
"prehashed_digest",
",",
"signature_algorithm",
"=",
"ec",
".",
"ECDSA",
"(",
"Prehashed",
"(",
"self",
".",
"algorithm",
".",
"signing_hash_type",
"(",
")",
")",
")",
",",
")"
] | Verifies the signature against the current cryptographic verifier state.
:param bytes signature: The signature to verify | [
"Verifies",
"the",
"signature",
"against",
"the",
"current",
"cryptographic",
"verifier",
"state",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L183-L193 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/wrapping_keys.py | WrappingKey.encrypt | def encrypt(self, plaintext_data_key, encryption_context):
"""Encrypts a data key using a direct wrapping key.
:param bytes plaintext_data_key: Data key to encrypt
:param dict encryption_context: Encryption context to use in encryption
:returns: Deserialized object containing encrypted key
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
"""
if self.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC:
if self.wrapping_key_type is EncryptionKeyType.PRIVATE:
encrypted_key = self._wrapping_key.public_key().encrypt(
plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding
)
else:
encrypted_key = self._wrapping_key.encrypt(
plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding
)
return EncryptedData(iv=None, ciphertext=encrypted_key, tag=None)
serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context)
iv = os.urandom(self.wrapping_algorithm.algorithm.iv_len)
return encrypt(
algorithm=self.wrapping_algorithm.algorithm,
key=self._derived_wrapping_key,
plaintext=plaintext_data_key,
associated_data=serialized_encryption_context,
iv=iv,
) | python | def encrypt(self, plaintext_data_key, encryption_context):
"""Encrypts a data key using a direct wrapping key.
:param bytes plaintext_data_key: Data key to encrypt
:param dict encryption_context: Encryption context to use in encryption
:returns: Deserialized object containing encrypted key
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
"""
if self.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC:
if self.wrapping_key_type is EncryptionKeyType.PRIVATE:
encrypted_key = self._wrapping_key.public_key().encrypt(
plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding
)
else:
encrypted_key = self._wrapping_key.encrypt(
plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding
)
return EncryptedData(iv=None, ciphertext=encrypted_key, tag=None)
serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context)
iv = os.urandom(self.wrapping_algorithm.algorithm.iv_len)
return encrypt(
algorithm=self.wrapping_algorithm.algorithm,
key=self._derived_wrapping_key,
plaintext=plaintext_data_key,
associated_data=serialized_encryption_context,
iv=iv,
) | [
"def",
"encrypt",
"(",
"self",
",",
"plaintext_data_key",
",",
"encryption_context",
")",
":",
"if",
"self",
".",
"wrapping_algorithm",
".",
"encryption_type",
"is",
"EncryptionType",
".",
"ASYMMETRIC",
":",
"if",
"self",
".",
"wrapping_key_type",
"is",
"EncryptionKeyType",
".",
"PRIVATE",
":",
"encrypted_key",
"=",
"self",
".",
"_wrapping_key",
".",
"public_key",
"(",
")",
".",
"encrypt",
"(",
"plaintext",
"=",
"plaintext_data_key",
",",
"padding",
"=",
"self",
".",
"wrapping_algorithm",
".",
"padding",
")",
"else",
":",
"encrypted_key",
"=",
"self",
".",
"_wrapping_key",
".",
"encrypt",
"(",
"plaintext",
"=",
"plaintext_data_key",
",",
"padding",
"=",
"self",
".",
"wrapping_algorithm",
".",
"padding",
")",
"return",
"EncryptedData",
"(",
"iv",
"=",
"None",
",",
"ciphertext",
"=",
"encrypted_key",
",",
"tag",
"=",
"None",
")",
"serialized_encryption_context",
"=",
"serialize_encryption_context",
"(",
"encryption_context",
"=",
"encryption_context",
")",
"iv",
"=",
"os",
".",
"urandom",
"(",
"self",
".",
"wrapping_algorithm",
".",
"algorithm",
".",
"iv_len",
")",
"return",
"encrypt",
"(",
"algorithm",
"=",
"self",
".",
"wrapping_algorithm",
".",
"algorithm",
",",
"key",
"=",
"self",
".",
"_derived_wrapping_key",
",",
"plaintext",
"=",
"plaintext_data_key",
",",
"associated_data",
"=",
"serialized_encryption_context",
",",
"iv",
"=",
"iv",
",",
")"
] | Encrypts a data key using a direct wrapping key.
:param bytes plaintext_data_key: Data key to encrypt
:param dict encryption_context: Encryption context to use in encryption
:returns: Deserialized object containing encrypted key
:rtype: aws_encryption_sdk.internal.structures.EncryptedData | [
"Encrypts",
"a",
"data",
"key",
"using",
"a",
"direct",
"wrapping",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/wrapping_keys.py#L61-L87 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/wrapping_keys.py | WrappingKey.decrypt | def decrypt(self, encrypted_wrapped_data_key, encryption_context):
"""Decrypts a wrapped, encrypted, data key.
:param encrypted_wrapped_data_key: Encrypted, wrapped, data key
:type encrypted_wrapped_data_key: aws_encryption_sdk.internal.structures.EncryptedData
:param dict encryption_context: Encryption context to use in decryption
:returns: Plaintext of data key
:rtype: bytes
"""
if self.wrapping_key_type is EncryptionKeyType.PUBLIC:
raise IncorrectMasterKeyError("Public key cannot decrypt")
if self.wrapping_key_type is EncryptionKeyType.PRIVATE:
return self._wrapping_key.decrypt(
ciphertext=encrypted_wrapped_data_key.ciphertext, padding=self.wrapping_algorithm.padding
)
serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context)
return decrypt(
algorithm=self.wrapping_algorithm.algorithm,
key=self._derived_wrapping_key,
encrypted_data=encrypted_wrapped_data_key,
associated_data=serialized_encryption_context,
) | python | def decrypt(self, encrypted_wrapped_data_key, encryption_context):
"""Decrypts a wrapped, encrypted, data key.
:param encrypted_wrapped_data_key: Encrypted, wrapped, data key
:type encrypted_wrapped_data_key: aws_encryption_sdk.internal.structures.EncryptedData
:param dict encryption_context: Encryption context to use in decryption
:returns: Plaintext of data key
:rtype: bytes
"""
if self.wrapping_key_type is EncryptionKeyType.PUBLIC:
raise IncorrectMasterKeyError("Public key cannot decrypt")
if self.wrapping_key_type is EncryptionKeyType.PRIVATE:
return self._wrapping_key.decrypt(
ciphertext=encrypted_wrapped_data_key.ciphertext, padding=self.wrapping_algorithm.padding
)
serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context)
return decrypt(
algorithm=self.wrapping_algorithm.algorithm,
key=self._derived_wrapping_key,
encrypted_data=encrypted_wrapped_data_key,
associated_data=serialized_encryption_context,
) | [
"def",
"decrypt",
"(",
"self",
",",
"encrypted_wrapped_data_key",
",",
"encryption_context",
")",
":",
"if",
"self",
".",
"wrapping_key_type",
"is",
"EncryptionKeyType",
".",
"PUBLIC",
":",
"raise",
"IncorrectMasterKeyError",
"(",
"\"Public key cannot decrypt\"",
")",
"if",
"self",
".",
"wrapping_key_type",
"is",
"EncryptionKeyType",
".",
"PRIVATE",
":",
"return",
"self",
".",
"_wrapping_key",
".",
"decrypt",
"(",
"ciphertext",
"=",
"encrypted_wrapped_data_key",
".",
"ciphertext",
",",
"padding",
"=",
"self",
".",
"wrapping_algorithm",
".",
"padding",
")",
"serialized_encryption_context",
"=",
"serialize_encryption_context",
"(",
"encryption_context",
"=",
"encryption_context",
")",
"return",
"decrypt",
"(",
"algorithm",
"=",
"self",
".",
"wrapping_algorithm",
".",
"algorithm",
",",
"key",
"=",
"self",
".",
"_derived_wrapping_key",
",",
"encrypted_data",
"=",
"encrypted_wrapped_data_key",
",",
"associated_data",
"=",
"serialized_encryption_context",
",",
")"
] | Decrypts a wrapped, encrypted, data key.
:param encrypted_wrapped_data_key: Encrypted, wrapped, data key
:type encrypted_wrapped_data_key: aws_encryption_sdk.internal.structures.EncryptedData
:param dict encryption_context: Encryption context to use in decryption
:returns: Plaintext of data key
:rtype: bytes | [
"Decrypts",
"a",
"wrapped",
"encrypted",
"data",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/wrapping_keys.py#L89-L110 | train |
aws/aws-encryption-sdk-python | decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py | CountingMasterKey._generate_data_key | def _generate_data_key(self, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]) -> DataKey:
"""Perform the provider-specific data key generation task.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:returns: Generated data key
:rtype: aws_encryption_sdk.structures.DataKey
"""
data_key = b"".join([chr(i).encode("utf-8") for i in range(1, algorithm.data_key_len + 1)])
return DataKey(key_provider=self.key_provider, data_key=data_key, encrypted_data_key=self._encrypted_data_key) | python | def _generate_data_key(self, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]) -> DataKey:
"""Perform the provider-specific data key generation task.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:returns: Generated data key
:rtype: aws_encryption_sdk.structures.DataKey
"""
data_key = b"".join([chr(i).encode("utf-8") for i in range(1, algorithm.data_key_len + 1)])
return DataKey(key_provider=self.key_provider, data_key=data_key, encrypted_data_key=self._encrypted_data_key) | [
"def",
"_generate_data_key",
"(",
"self",
",",
"algorithm",
":",
"AlgorithmSuite",
",",
"encryption_context",
":",
"Dict",
"[",
"Text",
",",
"Text",
"]",
")",
"->",
"DataKey",
":",
"data_key",
"=",
"b\"\"",
".",
"join",
"(",
"[",
"chr",
"(",
"i",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"algorithm",
".",
"data_key_len",
"+",
"1",
")",
"]",
")",
"return",
"DataKey",
"(",
"key_provider",
"=",
"self",
".",
"key_provider",
",",
"data_key",
"=",
"data_key",
",",
"encrypted_data_key",
"=",
"self",
".",
"_encrypted_data_key",
")"
] | Perform the provider-specific data key generation task.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:returns: Generated data key
:rtype: aws_encryption_sdk.structures.DataKey | [
"Perform",
"the",
"provider",
"-",
"specific",
"data",
"key",
"generation",
"task",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py#L53-L63 | train |
aws/aws-encryption-sdk-python | decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py | CountingMasterKey._encrypt_data_key | def _encrypt_data_key(
self, data_key: DataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]
) -> NoReturn:
"""Encrypt a data key and return the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this Master Key will encrypt the data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:raises NotImplementedError: when called
"""
raise NotImplementedError("CountingMasterKey does not support encrypt_data_key") | python | def _encrypt_data_key(
self, data_key: DataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]
) -> NoReturn:
"""Encrypt a data key and return the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this Master Key will encrypt the data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:raises NotImplementedError: when called
"""
raise NotImplementedError("CountingMasterKey does not support encrypt_data_key") | [
"def",
"_encrypt_data_key",
"(",
"self",
",",
"data_key",
":",
"DataKey",
",",
"algorithm",
":",
"AlgorithmSuite",
",",
"encryption_context",
":",
"Dict",
"[",
"Text",
",",
"Text",
"]",
")",
"->",
"NoReturn",
":",
"raise",
"NotImplementedError",
"(",
"\"CountingMasterKey does not support encrypt_data_key\"",
")"
] | Encrypt a data key and return the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this Master Key will encrypt the data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use in encryption
:raises NotImplementedError: when called | [
"Encrypt",
"a",
"data",
"key",
"and",
"return",
"the",
"ciphertext",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py#L65-L78 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | validate_header | def validate_header(header, header_auth, raw_header, data_key):
"""Validates the header using the header authentication data.
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param header_auth: Deserialized header auth
:type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:type stream: io.BytesIO
:param bytes raw_header: Raw header bytes
:param bytes data_key: Data key with which to perform validation
:raises SerializationError: if header authorization fails
"""
_LOGGER.debug("Starting header validation")
try:
decrypt(
algorithm=header.algorithm,
key=data_key,
encrypted_data=EncryptedData(header_auth.iv, b"", header_auth.tag),
associated_data=raw_header,
)
except InvalidTag:
raise SerializationError("Header authorization failed") | python | def validate_header(header, header_auth, raw_header, data_key):
"""Validates the header using the header authentication data.
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param header_auth: Deserialized header auth
:type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:type stream: io.BytesIO
:param bytes raw_header: Raw header bytes
:param bytes data_key: Data key with which to perform validation
:raises SerializationError: if header authorization fails
"""
_LOGGER.debug("Starting header validation")
try:
decrypt(
algorithm=header.algorithm,
key=data_key,
encrypted_data=EncryptedData(header_auth.iv, b"", header_auth.tag),
associated_data=raw_header,
)
except InvalidTag:
raise SerializationError("Header authorization failed") | [
"def",
"validate_header",
"(",
"header",
",",
"header_auth",
",",
"raw_header",
",",
"data_key",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting header validation\"",
")",
"try",
":",
"decrypt",
"(",
"algorithm",
"=",
"header",
".",
"algorithm",
",",
"key",
"=",
"data_key",
",",
"encrypted_data",
"=",
"EncryptedData",
"(",
"header_auth",
".",
"iv",
",",
"b\"\"",
",",
"header_auth",
".",
"tag",
")",
",",
"associated_data",
"=",
"raw_header",
",",
")",
"except",
"InvalidTag",
":",
"raise",
"SerializationError",
"(",
"\"Header authorization failed\"",
")"
] | Validates the header using the header authentication data.
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param header_auth: Deserialized header auth
:type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:type stream: io.BytesIO
:param bytes raw_header: Raw header bytes
:param bytes data_key: Data key with which to perform validation
:raises SerializationError: if header authorization fails | [
"Validates",
"the",
"header",
"using",
"the",
"header",
"authentication",
"data",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L52-L73 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | _deserialize_encrypted_data_keys | def _deserialize_encrypted_data_keys(stream):
# type: (IO) -> Set[EncryptedDataKey]
"""Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey`
"""
(encrypted_data_key_count,) = unpack_values(">H", stream)
encrypted_data_keys = set([])
for _ in range(encrypted_data_key_count):
(key_provider_length,) = unpack_values(">H", stream)
(key_provider_identifier,) = unpack_values(">{}s".format(key_provider_length), stream)
(key_provider_information_length,) = unpack_values(">H", stream)
(key_provider_information,) = unpack_values(">{}s".format(key_provider_information_length), stream)
(encrypted_data_key_length,) = unpack_values(">H", stream)
encrypted_data_key = stream.read(encrypted_data_key_length)
encrypted_data_keys.add(
EncryptedDataKey(
key_provider=MasterKeyInfo(
provider_id=to_str(key_provider_identifier), key_info=key_provider_information
),
encrypted_data_key=encrypted_data_key,
)
)
return encrypted_data_keys | python | def _deserialize_encrypted_data_keys(stream):
# type: (IO) -> Set[EncryptedDataKey]
"""Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey`
"""
(encrypted_data_key_count,) = unpack_values(">H", stream)
encrypted_data_keys = set([])
for _ in range(encrypted_data_key_count):
(key_provider_length,) = unpack_values(">H", stream)
(key_provider_identifier,) = unpack_values(">{}s".format(key_provider_length), stream)
(key_provider_information_length,) = unpack_values(">H", stream)
(key_provider_information,) = unpack_values(">{}s".format(key_provider_information_length), stream)
(encrypted_data_key_length,) = unpack_values(">H", stream)
encrypted_data_key = stream.read(encrypted_data_key_length)
encrypted_data_keys.add(
EncryptedDataKey(
key_provider=MasterKeyInfo(
provider_id=to_str(key_provider_identifier), key_info=key_provider_information
),
encrypted_data_key=encrypted_data_key,
)
)
return encrypted_data_keys | [
"def",
"_deserialize_encrypted_data_keys",
"(",
"stream",
")",
":",
"# type: (IO) -> Set[EncryptedDataKey]",
"(",
"encrypted_data_key_count",
",",
")",
"=",
"unpack_values",
"(",
"\">H\"",
",",
"stream",
")",
"encrypted_data_keys",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"_",
"in",
"range",
"(",
"encrypted_data_key_count",
")",
":",
"(",
"key_provider_length",
",",
")",
"=",
"unpack_values",
"(",
"\">H\"",
",",
"stream",
")",
"(",
"key_provider_identifier",
",",
")",
"=",
"unpack_values",
"(",
"\">{}s\"",
".",
"format",
"(",
"key_provider_length",
")",
",",
"stream",
")",
"(",
"key_provider_information_length",
",",
")",
"=",
"unpack_values",
"(",
"\">H\"",
",",
"stream",
")",
"(",
"key_provider_information",
",",
")",
"=",
"unpack_values",
"(",
"\">{}s\"",
".",
"format",
"(",
"key_provider_information_length",
")",
",",
"stream",
")",
"(",
"encrypted_data_key_length",
",",
")",
"=",
"unpack_values",
"(",
"\">H\"",
",",
"stream",
")",
"encrypted_data_key",
"=",
"stream",
".",
"read",
"(",
"encrypted_data_key_length",
")",
"encrypted_data_keys",
".",
"add",
"(",
"EncryptedDataKey",
"(",
"key_provider",
"=",
"MasterKeyInfo",
"(",
"provider_id",
"=",
"to_str",
"(",
"key_provider_identifier",
")",
",",
"key_info",
"=",
"key_provider_information",
")",
",",
"encrypted_data_key",
"=",
"encrypted_data_key",
",",
")",
")",
"return",
"encrypted_data_keys"
] | Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey` | [
"Deserialize",
"some",
"encrypted",
"data",
"keys",
"from",
"a",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L127-L152 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | _verified_iv_length | def _verified_iv_length(iv_length, algorithm_suite):
# type: (int, AlgorithmSuite) -> int
"""Verify an IV length for an algorithm suite.
:param int iv_length: IV length to verify
:param AlgorithmSuite algorithm_suite: Algorithm suite to verify against
:return: IV length
:rtype: int
:raises SerializationError: if IV length does not match algorithm suite
"""
if iv_length != algorithm_suite.iv_len:
raise SerializationError(
"Specified IV length ({length}) does not match algorithm IV length ({algorithm})".format(
length=iv_length, algorithm=algorithm_suite
)
)
return iv_length | python | def _verified_iv_length(iv_length, algorithm_suite):
# type: (int, AlgorithmSuite) -> int
"""Verify an IV length for an algorithm suite.
:param int iv_length: IV length to verify
:param AlgorithmSuite algorithm_suite: Algorithm suite to verify against
:return: IV length
:rtype: int
:raises SerializationError: if IV length does not match algorithm suite
"""
if iv_length != algorithm_suite.iv_len:
raise SerializationError(
"Specified IV length ({length}) does not match algorithm IV length ({algorithm})".format(
length=iv_length, algorithm=algorithm_suite
)
)
return iv_length | [
"def",
"_verified_iv_length",
"(",
"iv_length",
",",
"algorithm_suite",
")",
":",
"# type: (int, AlgorithmSuite) -> int",
"if",
"iv_length",
"!=",
"algorithm_suite",
".",
"iv_len",
":",
"raise",
"SerializationError",
"(",
"\"Specified IV length ({length}) does not match algorithm IV length ({algorithm})\"",
".",
"format",
"(",
"length",
"=",
"iv_length",
",",
"algorithm",
"=",
"algorithm_suite",
")",
")",
"return",
"iv_length"
] | Verify an IV length for an algorithm suite.
:param int iv_length: IV length to verify
:param AlgorithmSuite algorithm_suite: Algorithm suite to verify against
:return: IV length
:rtype: int
:raises SerializationError: if IV length does not match algorithm suite | [
"Verify",
"an",
"IV",
"length",
"for",
"an",
"algorithm",
"suite",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L185-L202 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | _verified_frame_length | def _verified_frame_length(frame_length, content_type):
# type: (int, ContentType) -> int
"""Verify a frame length value for a message content type.
:param int frame_length: Frame length to verify
:param ContentType content_type: Message content type to verify against
:return: frame length
:rtype: int
:raises SerializationError: if frame length is too large
:raises SerializationError: if frame length is not zero for unframed content type
"""
if content_type == ContentType.FRAMED_DATA and frame_length > MAX_FRAME_SIZE:
raise SerializationError(
"Specified frame length larger than allowed maximum: {found} > {max}".format(
found=frame_length, max=MAX_FRAME_SIZE
)
)
if content_type == ContentType.NO_FRAMING and frame_length != 0:
raise SerializationError("Non-zero frame length found for non-framed message")
return frame_length | python | def _verified_frame_length(frame_length, content_type):
# type: (int, ContentType) -> int
"""Verify a frame length value for a message content type.
:param int frame_length: Frame length to verify
:param ContentType content_type: Message content type to verify against
:return: frame length
:rtype: int
:raises SerializationError: if frame length is too large
:raises SerializationError: if frame length is not zero for unframed content type
"""
if content_type == ContentType.FRAMED_DATA and frame_length > MAX_FRAME_SIZE:
raise SerializationError(
"Specified frame length larger than allowed maximum: {found} > {max}".format(
found=frame_length, max=MAX_FRAME_SIZE
)
)
if content_type == ContentType.NO_FRAMING and frame_length != 0:
raise SerializationError("Non-zero frame length found for non-framed message")
return frame_length | [
"def",
"_verified_frame_length",
"(",
"frame_length",
",",
"content_type",
")",
":",
"# type: (int, ContentType) -> int",
"if",
"content_type",
"==",
"ContentType",
".",
"FRAMED_DATA",
"and",
"frame_length",
">",
"MAX_FRAME_SIZE",
":",
"raise",
"SerializationError",
"(",
"\"Specified frame length larger than allowed maximum: {found} > {max}\"",
".",
"format",
"(",
"found",
"=",
"frame_length",
",",
"max",
"=",
"MAX_FRAME_SIZE",
")",
")",
"if",
"content_type",
"==",
"ContentType",
".",
"NO_FRAMING",
"and",
"frame_length",
"!=",
"0",
":",
"raise",
"SerializationError",
"(",
"\"Non-zero frame length found for non-framed message\"",
")",
"return",
"frame_length"
] | Verify a frame length value for a message content type.
:param int frame_length: Frame length to verify
:param ContentType content_type: Message content type to verify against
:return: frame length
:rtype: int
:raises SerializationError: if frame length is too large
:raises SerializationError: if frame length is not zero for unframed content type | [
"Verify",
"a",
"frame",
"length",
"value",
"for",
"a",
"message",
"content",
"type",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L205-L226 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | deserialize_header | def deserialize_header(stream):
# type: (IO) -> MessageHeader
"""Deserializes the header from a source stream
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Deserialized MessageHeader object
:rtype: :class:`aws_encryption_sdk.structures.MessageHeader` and bytes
:raises NotSupportedError: if unsupported data types are found
:raises UnknownIdentityError: if unknown data types are found
:raises SerializationError: if IV length does not match algorithm
"""
_LOGGER.debug("Starting header deserialization")
tee = io.BytesIO()
tee_stream = TeeStream(stream, tee)
version_id, message_type_id = unpack_values(">BB", tee_stream)
header = dict()
header["version"] = _verified_version_from_id(version_id)
header["type"] = _verified_message_type_from_id(message_type_id)
algorithm_id, message_id, ser_encryption_context_length = unpack_values(">H16sH", tee_stream)
header["algorithm"] = _verified_algorithm_from_id(algorithm_id)
header["message_id"] = message_id
header["encryption_context"] = deserialize_encryption_context(tee_stream.read(ser_encryption_context_length))
header["encrypted_data_keys"] = _deserialize_encrypted_data_keys(tee_stream)
(content_type_id,) = unpack_values(">B", tee_stream)
header["content_type"] = _verified_content_type_from_id(content_type_id)
(content_aad_length,) = unpack_values(">I", tee_stream)
header["content_aad_length"] = _verified_content_aad_length(content_aad_length)
(iv_length,) = unpack_values(">B", tee_stream)
header["header_iv_length"] = _verified_iv_length(iv_length, header["algorithm"])
(frame_length,) = unpack_values(">I", tee_stream)
header["frame_length"] = _verified_frame_length(frame_length, header["content_type"])
return MessageHeader(**header), tee.getvalue() | python | def deserialize_header(stream):
# type: (IO) -> MessageHeader
"""Deserializes the header from a source stream
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Deserialized MessageHeader object
:rtype: :class:`aws_encryption_sdk.structures.MessageHeader` and bytes
:raises NotSupportedError: if unsupported data types are found
:raises UnknownIdentityError: if unknown data types are found
:raises SerializationError: if IV length does not match algorithm
"""
_LOGGER.debug("Starting header deserialization")
tee = io.BytesIO()
tee_stream = TeeStream(stream, tee)
version_id, message_type_id = unpack_values(">BB", tee_stream)
header = dict()
header["version"] = _verified_version_from_id(version_id)
header["type"] = _verified_message_type_from_id(message_type_id)
algorithm_id, message_id, ser_encryption_context_length = unpack_values(">H16sH", tee_stream)
header["algorithm"] = _verified_algorithm_from_id(algorithm_id)
header["message_id"] = message_id
header["encryption_context"] = deserialize_encryption_context(tee_stream.read(ser_encryption_context_length))
header["encrypted_data_keys"] = _deserialize_encrypted_data_keys(tee_stream)
(content_type_id,) = unpack_values(">B", tee_stream)
header["content_type"] = _verified_content_type_from_id(content_type_id)
(content_aad_length,) = unpack_values(">I", tee_stream)
header["content_aad_length"] = _verified_content_aad_length(content_aad_length)
(iv_length,) = unpack_values(">B", tee_stream)
header["header_iv_length"] = _verified_iv_length(iv_length, header["algorithm"])
(frame_length,) = unpack_values(">I", tee_stream)
header["frame_length"] = _verified_frame_length(frame_length, header["content_type"])
return MessageHeader(**header), tee.getvalue() | [
"def",
"deserialize_header",
"(",
"stream",
")",
":",
"# type: (IO) -> MessageHeader",
"_LOGGER",
".",
"debug",
"(",
"\"Starting header deserialization\"",
")",
"tee",
"=",
"io",
".",
"BytesIO",
"(",
")",
"tee_stream",
"=",
"TeeStream",
"(",
"stream",
",",
"tee",
")",
"version_id",
",",
"message_type_id",
"=",
"unpack_values",
"(",
"\">BB\"",
",",
"tee_stream",
")",
"header",
"=",
"dict",
"(",
")",
"header",
"[",
"\"version\"",
"]",
"=",
"_verified_version_from_id",
"(",
"version_id",
")",
"header",
"[",
"\"type\"",
"]",
"=",
"_verified_message_type_from_id",
"(",
"message_type_id",
")",
"algorithm_id",
",",
"message_id",
",",
"ser_encryption_context_length",
"=",
"unpack_values",
"(",
"\">H16sH\"",
",",
"tee_stream",
")",
"header",
"[",
"\"algorithm\"",
"]",
"=",
"_verified_algorithm_from_id",
"(",
"algorithm_id",
")",
"header",
"[",
"\"message_id\"",
"]",
"=",
"message_id",
"header",
"[",
"\"encryption_context\"",
"]",
"=",
"deserialize_encryption_context",
"(",
"tee_stream",
".",
"read",
"(",
"ser_encryption_context_length",
")",
")",
"header",
"[",
"\"encrypted_data_keys\"",
"]",
"=",
"_deserialize_encrypted_data_keys",
"(",
"tee_stream",
")",
"(",
"content_type_id",
",",
")",
"=",
"unpack_values",
"(",
"\">B\"",
",",
"tee_stream",
")",
"header",
"[",
"\"content_type\"",
"]",
"=",
"_verified_content_type_from_id",
"(",
"content_type_id",
")",
"(",
"content_aad_length",
",",
")",
"=",
"unpack_values",
"(",
"\">I\"",
",",
"tee_stream",
")",
"header",
"[",
"\"content_aad_length\"",
"]",
"=",
"_verified_content_aad_length",
"(",
"content_aad_length",
")",
"(",
"iv_length",
",",
")",
"=",
"unpack_values",
"(",
"\">B\"",
",",
"tee_stream",
")",
"header",
"[",
"\"header_iv_length\"",
"]",
"=",
"_verified_iv_length",
"(",
"iv_length",
",",
"header",
"[",
"\"algorithm\"",
"]",
")",
"(",
"frame_length",
",",
")",
"=",
"unpack_values",
"(",
"\">I\"",
",",
"tee_stream",
")",
"header",
"[",
"\"frame_length\"",
"]",
"=",
"_verified_frame_length",
"(",
"frame_length",
",",
"header",
"[",
"\"content_type\"",
"]",
")",
"return",
"MessageHeader",
"(",
"*",
"*",
"header",
")",
",",
"tee",
".",
"getvalue",
"(",
")"
] | Deserializes the header from a source stream
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Deserialized MessageHeader object
:rtype: :class:`aws_encryption_sdk.structures.MessageHeader` and bytes
:raises NotSupportedError: if unsupported data types are found
:raises UnknownIdentityError: if unknown data types are found
:raises SerializationError: if IV length does not match algorithm | [
"Deserializes",
"the",
"header",
"from",
"a",
"source",
"stream"
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L229-L270 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | deserialize_header_auth | def deserialize_header_auth(stream, algorithm, verifier=None):
"""Deserializes a MessageHeaderAuthentication object from a source stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param algorithm: The AlgorithmSuite object type contained in the header
:type algorith: aws_encryption_sdk.identifiers.AlgorithmSuite
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized MessageHeaderAuthentication object
:rtype: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
"""
_LOGGER.debug("Starting header auth deserialization")
format_string = ">{iv_len}s{tag_len}s".format(iv_len=algorithm.iv_len, tag_len=algorithm.tag_len)
return MessageHeaderAuthentication(*unpack_values(format_string, stream, verifier)) | python | def deserialize_header_auth(stream, algorithm, verifier=None):
"""Deserializes a MessageHeaderAuthentication object from a source stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param algorithm: The AlgorithmSuite object type contained in the header
:type algorith: aws_encryption_sdk.identifiers.AlgorithmSuite
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized MessageHeaderAuthentication object
:rtype: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
"""
_LOGGER.debug("Starting header auth deserialization")
format_string = ">{iv_len}s{tag_len}s".format(iv_len=algorithm.iv_len, tag_len=algorithm.tag_len)
return MessageHeaderAuthentication(*unpack_values(format_string, stream, verifier)) | [
"def",
"deserialize_header_auth",
"(",
"stream",
",",
"algorithm",
",",
"verifier",
"=",
"None",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting header auth deserialization\"",
")",
"format_string",
"=",
"\">{iv_len}s{tag_len}s\"",
".",
"format",
"(",
"iv_len",
"=",
"algorithm",
".",
"iv_len",
",",
"tag_len",
"=",
"algorithm",
".",
"tag_len",
")",
"return",
"MessageHeaderAuthentication",
"(",
"*",
"unpack_values",
"(",
"format_string",
",",
"stream",
",",
"verifier",
")",
")"
] | Deserializes a MessageHeaderAuthentication object from a source stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param algorithm: The AlgorithmSuite object type contained in the header
:type algorith: aws_encryption_sdk.identifiers.AlgorithmSuite
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized MessageHeaderAuthentication object
:rtype: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication | [
"Deserializes",
"a",
"MessageHeaderAuthentication",
"object",
"from",
"a",
"source",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L273-L287 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | deserialize_non_framed_values | def deserialize_non_framed_values(stream, header, verifier=None):
"""Deserializes the IV and body length from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: IV and Data Length values for body
:rtype: tuple of bytes and int
"""
_LOGGER.debug("Starting non-framed body iv/tag deserialization")
(data_iv, data_length) = unpack_values(">{}sQ".format(header.algorithm.iv_len), stream, verifier)
return data_iv, data_length | python | def deserialize_non_framed_values(stream, header, verifier=None):
"""Deserializes the IV and body length from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: IV and Data Length values for body
:rtype: tuple of bytes and int
"""
_LOGGER.debug("Starting non-framed body iv/tag deserialization")
(data_iv, data_length) = unpack_values(">{}sQ".format(header.algorithm.iv_len), stream, verifier)
return data_iv, data_length | [
"def",
"deserialize_non_framed_values",
"(",
"stream",
",",
"header",
",",
"verifier",
"=",
"None",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting non-framed body iv/tag deserialization\"",
")",
"(",
"data_iv",
",",
"data_length",
")",
"=",
"unpack_values",
"(",
"\">{}sQ\"",
".",
"format",
"(",
"header",
".",
"algorithm",
".",
"iv_len",
")",
",",
"stream",
",",
"verifier",
")",
"return",
"data_iv",
",",
"data_length"
] | Deserializes the IV and body length from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: IV and Data Length values for body
:rtype: tuple of bytes and int | [
"Deserializes",
"the",
"IV",
"and",
"body",
"length",
"from",
"a",
"non",
"-",
"framed",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L290-L304 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | deserialize_tag | def deserialize_tag(stream, header, verifier=None):
"""Deserialize the Tag value from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Tag value for body
:rtype: bytes
"""
(data_tag,) = unpack_values(
format_string=">{auth_len}s".format(auth_len=header.algorithm.auth_len), stream=stream, verifier=verifier
)
return data_tag | python | def deserialize_tag(stream, header, verifier=None):
"""Deserialize the Tag value from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Tag value for body
:rtype: bytes
"""
(data_tag,) = unpack_values(
format_string=">{auth_len}s".format(auth_len=header.algorithm.auth_len), stream=stream, verifier=verifier
)
return data_tag | [
"def",
"deserialize_tag",
"(",
"stream",
",",
"header",
",",
"verifier",
"=",
"None",
")",
":",
"(",
"data_tag",
",",
")",
"=",
"unpack_values",
"(",
"format_string",
"=",
"\">{auth_len}s\"",
".",
"format",
"(",
"auth_len",
"=",
"header",
".",
"algorithm",
".",
"auth_len",
")",
",",
"stream",
"=",
"stream",
",",
"verifier",
"=",
"verifier",
")",
"return",
"data_tag"
] | Deserialize the Tag value from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Tag value for body
:rtype: bytes | [
"Deserialize",
"the",
"Tag",
"value",
"from",
"a",
"non",
"-",
"framed",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L307-L322 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | deserialize_frame | def deserialize_frame(stream, header, verifier=None):
"""Deserializes a frame from a body.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized frame and a boolean stating if this is the final frame
:rtype: :class:`aws_encryption_sdk.internal.structures.MessageFrameBody` and bool
"""
_LOGGER.debug("Starting frame deserialization")
frame_data = {}
final_frame = False
(sequence_number,) = unpack_values(">I", stream, verifier)
if sequence_number == SequenceIdentifier.SEQUENCE_NUMBER_END.value:
_LOGGER.debug("Deserializing final frame")
(sequence_number,) = unpack_values(">I", stream, verifier)
final_frame = True
else:
_LOGGER.debug("Deserializing frame sequence number %d", int(sequence_number))
frame_data["final_frame"] = final_frame
frame_data["sequence_number"] = sequence_number
(frame_iv,) = unpack_values(">{iv_len}s".format(iv_len=header.algorithm.iv_len), stream, verifier)
frame_data["iv"] = frame_iv
if final_frame is True:
(content_length,) = unpack_values(">I", stream, verifier)
if content_length >= header.frame_length:
raise SerializationError(
"Invalid final frame length: {final} >= {normal}".format(
final=content_length, normal=header.frame_length
)
)
else:
content_length = header.frame_length
(frame_content, frame_tag) = unpack_values(
">{content_len}s{auth_len}s".format(content_len=content_length, auth_len=header.algorithm.auth_len),
stream,
verifier,
)
frame_data["ciphertext"] = frame_content
frame_data["tag"] = frame_tag
return MessageFrameBody(**frame_data), final_frame | python | def deserialize_frame(stream, header, verifier=None):
"""Deserializes a frame from a body.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized frame and a boolean stating if this is the final frame
:rtype: :class:`aws_encryption_sdk.internal.structures.MessageFrameBody` and bool
"""
_LOGGER.debug("Starting frame deserialization")
frame_data = {}
final_frame = False
(sequence_number,) = unpack_values(">I", stream, verifier)
if sequence_number == SequenceIdentifier.SEQUENCE_NUMBER_END.value:
_LOGGER.debug("Deserializing final frame")
(sequence_number,) = unpack_values(">I", stream, verifier)
final_frame = True
else:
_LOGGER.debug("Deserializing frame sequence number %d", int(sequence_number))
frame_data["final_frame"] = final_frame
frame_data["sequence_number"] = sequence_number
(frame_iv,) = unpack_values(">{iv_len}s".format(iv_len=header.algorithm.iv_len), stream, verifier)
frame_data["iv"] = frame_iv
if final_frame is True:
(content_length,) = unpack_values(">I", stream, verifier)
if content_length >= header.frame_length:
raise SerializationError(
"Invalid final frame length: {final} >= {normal}".format(
final=content_length, normal=header.frame_length
)
)
else:
content_length = header.frame_length
(frame_content, frame_tag) = unpack_values(
">{content_len}s{auth_len}s".format(content_len=content_length, auth_len=header.algorithm.auth_len),
stream,
verifier,
)
frame_data["ciphertext"] = frame_content
frame_data["tag"] = frame_tag
return MessageFrameBody(**frame_data), final_frame | [
"def",
"deserialize_frame",
"(",
"stream",
",",
"header",
",",
"verifier",
"=",
"None",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting frame deserialization\"",
")",
"frame_data",
"=",
"{",
"}",
"final_frame",
"=",
"False",
"(",
"sequence_number",
",",
")",
"=",
"unpack_values",
"(",
"\">I\"",
",",
"stream",
",",
"verifier",
")",
"if",
"sequence_number",
"==",
"SequenceIdentifier",
".",
"SEQUENCE_NUMBER_END",
".",
"value",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Deserializing final frame\"",
")",
"(",
"sequence_number",
",",
")",
"=",
"unpack_values",
"(",
"\">I\"",
",",
"stream",
",",
"verifier",
")",
"final_frame",
"=",
"True",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Deserializing frame sequence number %d\"",
",",
"int",
"(",
"sequence_number",
")",
")",
"frame_data",
"[",
"\"final_frame\"",
"]",
"=",
"final_frame",
"frame_data",
"[",
"\"sequence_number\"",
"]",
"=",
"sequence_number",
"(",
"frame_iv",
",",
")",
"=",
"unpack_values",
"(",
"\">{iv_len}s\"",
".",
"format",
"(",
"iv_len",
"=",
"header",
".",
"algorithm",
".",
"iv_len",
")",
",",
"stream",
",",
"verifier",
")",
"frame_data",
"[",
"\"iv\"",
"]",
"=",
"frame_iv",
"if",
"final_frame",
"is",
"True",
":",
"(",
"content_length",
",",
")",
"=",
"unpack_values",
"(",
"\">I\"",
",",
"stream",
",",
"verifier",
")",
"if",
"content_length",
">=",
"header",
".",
"frame_length",
":",
"raise",
"SerializationError",
"(",
"\"Invalid final frame length: {final} >= {normal}\"",
".",
"format",
"(",
"final",
"=",
"content_length",
",",
"normal",
"=",
"header",
".",
"frame_length",
")",
")",
"else",
":",
"content_length",
"=",
"header",
".",
"frame_length",
"(",
"frame_content",
",",
"frame_tag",
")",
"=",
"unpack_values",
"(",
"\">{content_len}s{auth_len}s\"",
".",
"format",
"(",
"content_len",
"=",
"content_length",
",",
"auth_len",
"=",
"header",
".",
"algorithm",
".",
"auth_len",
")",
",",
"stream",
",",
"verifier",
",",
")",
"frame_data",
"[",
"\"ciphertext\"",
"]",
"=",
"frame_content",
"frame_data",
"[",
"\"tag\"",
"]",
"=",
"frame_tag",
"return",
"MessageFrameBody",
"(",
"*",
"*",
"frame_data",
")",
",",
"final_frame"
] | Deserializes a frame from a body.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized frame and a boolean stating if this is the final frame
:rtype: :class:`aws_encryption_sdk.internal.structures.MessageFrameBody` and bool | [
"Deserializes",
"a",
"frame",
"from",
"a",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L325-L368 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | deserialize_footer | def deserialize_footer(stream, verifier=None):
"""Deserializes a footer.
:param stream: Source data stream
:type stream: io.BytesIO
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized footer
:rtype: aws_encryption_sdk.internal.structures.MessageFooter
:raises SerializationError: if verifier supplied and no footer found
"""
_LOGGER.debug("Starting footer deserialization")
signature = b""
if verifier is None:
return MessageFooter(signature=signature)
try:
(sig_len,) = unpack_values(">H", stream)
(signature,) = unpack_values(">{sig_len}s".format(sig_len=sig_len), stream)
except SerializationError:
raise SerializationError("No signature found in message")
if verifier:
verifier.verify(signature)
return MessageFooter(signature=signature) | python | def deserialize_footer(stream, verifier=None):
"""Deserializes a footer.
:param stream: Source data stream
:type stream: io.BytesIO
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized footer
:rtype: aws_encryption_sdk.internal.structures.MessageFooter
:raises SerializationError: if verifier supplied and no footer found
"""
_LOGGER.debug("Starting footer deserialization")
signature = b""
if verifier is None:
return MessageFooter(signature=signature)
try:
(sig_len,) = unpack_values(">H", stream)
(signature,) = unpack_values(">{sig_len}s".format(sig_len=sig_len), stream)
except SerializationError:
raise SerializationError("No signature found in message")
if verifier:
verifier.verify(signature)
return MessageFooter(signature=signature) | [
"def",
"deserialize_footer",
"(",
"stream",
",",
"verifier",
"=",
"None",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting footer deserialization\"",
")",
"signature",
"=",
"b\"\"",
"if",
"verifier",
"is",
"None",
":",
"return",
"MessageFooter",
"(",
"signature",
"=",
"signature",
")",
"try",
":",
"(",
"sig_len",
",",
")",
"=",
"unpack_values",
"(",
"\">H\"",
",",
"stream",
")",
"(",
"signature",
",",
")",
"=",
"unpack_values",
"(",
"\">{sig_len}s\"",
".",
"format",
"(",
"sig_len",
"=",
"sig_len",
")",
",",
"stream",
")",
"except",
"SerializationError",
":",
"raise",
"SerializationError",
"(",
"\"No signature found in message\"",
")",
"if",
"verifier",
":",
"verifier",
".",
"verify",
"(",
"signature",
")",
"return",
"MessageFooter",
"(",
"signature",
"=",
"signature",
")"
] | Deserializes a footer.
:param stream: Source data stream
:type stream: io.BytesIO
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized footer
:rtype: aws_encryption_sdk.internal.structures.MessageFooter
:raises SerializationError: if verifier supplied and no footer found | [
"Deserializes",
"a",
"footer",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L371-L393 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | deserialize_wrapped_key | def deserialize_wrapped_key(wrapping_algorithm, wrapping_key_id, wrapped_encrypted_key):
"""Extracts and deserializes EncryptedData from a Wrapped EncryptedDataKey.
:param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key
:type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm
:param bytes wrapping_key_id: Key ID of wrapping MasterKey
:param wrapped_encrypted_key: Raw Wrapped EncryptedKey
:type wrapped_encrypted_key: aws_encryption_sdk.structures.EncryptedDataKey
:returns: EncryptedData of deserialized Wrapped EncryptedKey
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
:raises SerializationError: if wrapping_key_id does not match deserialized wrapping key id
:raises SerializationError: if wrapping_algorithm IV length does not match deserialized IV length
"""
if wrapping_key_id == wrapped_encrypted_key.key_provider.key_info:
encrypted_wrapped_key = EncryptedData(iv=None, ciphertext=wrapped_encrypted_key.encrypted_data_key, tag=None)
else:
if not wrapped_encrypted_key.key_provider.key_info.startswith(wrapping_key_id):
raise SerializationError("Master Key mismatch for wrapped data key")
_key_info = wrapped_encrypted_key.key_provider.key_info[len(wrapping_key_id) :]
try:
tag_len, iv_len = struct.unpack(">II", _key_info[:8])
except struct.error:
raise SerializationError("Malformed key info: key info missing data")
tag_len //= 8 # Tag Length is stored in bits, not bytes
if iv_len != wrapping_algorithm.algorithm.iv_len:
raise SerializationError("Wrapping AlgorithmSuite mismatch for wrapped data key")
iv = _key_info[8:]
if len(iv) != iv_len:
raise SerializationError("Malformed key info: incomplete iv")
ciphertext = wrapped_encrypted_key.encrypted_data_key[: -1 * tag_len]
tag = wrapped_encrypted_key.encrypted_data_key[-1 * tag_len :]
if not ciphertext or len(tag) != tag_len:
raise SerializationError("Malformed key info: incomplete ciphertext or tag")
encrypted_wrapped_key = EncryptedData(iv=iv, ciphertext=ciphertext, tag=tag)
return encrypted_wrapped_key | python | def deserialize_wrapped_key(wrapping_algorithm, wrapping_key_id, wrapped_encrypted_key):
"""Extracts and deserializes EncryptedData from a Wrapped EncryptedDataKey.
:param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key
:type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm
:param bytes wrapping_key_id: Key ID of wrapping MasterKey
:param wrapped_encrypted_key: Raw Wrapped EncryptedKey
:type wrapped_encrypted_key: aws_encryption_sdk.structures.EncryptedDataKey
:returns: EncryptedData of deserialized Wrapped EncryptedKey
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
:raises SerializationError: if wrapping_key_id does not match deserialized wrapping key id
:raises SerializationError: if wrapping_algorithm IV length does not match deserialized IV length
"""
if wrapping_key_id == wrapped_encrypted_key.key_provider.key_info:
encrypted_wrapped_key = EncryptedData(iv=None, ciphertext=wrapped_encrypted_key.encrypted_data_key, tag=None)
else:
if not wrapped_encrypted_key.key_provider.key_info.startswith(wrapping_key_id):
raise SerializationError("Master Key mismatch for wrapped data key")
_key_info = wrapped_encrypted_key.key_provider.key_info[len(wrapping_key_id) :]
try:
tag_len, iv_len = struct.unpack(">II", _key_info[:8])
except struct.error:
raise SerializationError("Malformed key info: key info missing data")
tag_len //= 8 # Tag Length is stored in bits, not bytes
if iv_len != wrapping_algorithm.algorithm.iv_len:
raise SerializationError("Wrapping AlgorithmSuite mismatch for wrapped data key")
iv = _key_info[8:]
if len(iv) != iv_len:
raise SerializationError("Malformed key info: incomplete iv")
ciphertext = wrapped_encrypted_key.encrypted_data_key[: -1 * tag_len]
tag = wrapped_encrypted_key.encrypted_data_key[-1 * tag_len :]
if not ciphertext or len(tag) != tag_len:
raise SerializationError("Malformed key info: incomplete ciphertext or tag")
encrypted_wrapped_key = EncryptedData(iv=iv, ciphertext=ciphertext, tag=tag)
return encrypted_wrapped_key | [
"def",
"deserialize_wrapped_key",
"(",
"wrapping_algorithm",
",",
"wrapping_key_id",
",",
"wrapped_encrypted_key",
")",
":",
"if",
"wrapping_key_id",
"==",
"wrapped_encrypted_key",
".",
"key_provider",
".",
"key_info",
":",
"encrypted_wrapped_key",
"=",
"EncryptedData",
"(",
"iv",
"=",
"None",
",",
"ciphertext",
"=",
"wrapped_encrypted_key",
".",
"encrypted_data_key",
",",
"tag",
"=",
"None",
")",
"else",
":",
"if",
"not",
"wrapped_encrypted_key",
".",
"key_provider",
".",
"key_info",
".",
"startswith",
"(",
"wrapping_key_id",
")",
":",
"raise",
"SerializationError",
"(",
"\"Master Key mismatch for wrapped data key\"",
")",
"_key_info",
"=",
"wrapped_encrypted_key",
".",
"key_provider",
".",
"key_info",
"[",
"len",
"(",
"wrapping_key_id",
")",
":",
"]",
"try",
":",
"tag_len",
",",
"iv_len",
"=",
"struct",
".",
"unpack",
"(",
"\">II\"",
",",
"_key_info",
"[",
":",
"8",
"]",
")",
"except",
"struct",
".",
"error",
":",
"raise",
"SerializationError",
"(",
"\"Malformed key info: key info missing data\"",
")",
"tag_len",
"//=",
"8",
"# Tag Length is stored in bits, not bytes",
"if",
"iv_len",
"!=",
"wrapping_algorithm",
".",
"algorithm",
".",
"iv_len",
":",
"raise",
"SerializationError",
"(",
"\"Wrapping AlgorithmSuite mismatch for wrapped data key\"",
")",
"iv",
"=",
"_key_info",
"[",
"8",
":",
"]",
"if",
"len",
"(",
"iv",
")",
"!=",
"iv_len",
":",
"raise",
"SerializationError",
"(",
"\"Malformed key info: incomplete iv\"",
")",
"ciphertext",
"=",
"wrapped_encrypted_key",
".",
"encrypted_data_key",
"[",
":",
"-",
"1",
"*",
"tag_len",
"]",
"tag",
"=",
"wrapped_encrypted_key",
".",
"encrypted_data_key",
"[",
"-",
"1",
"*",
"tag_len",
":",
"]",
"if",
"not",
"ciphertext",
"or",
"len",
"(",
"tag",
")",
"!=",
"tag_len",
":",
"raise",
"SerializationError",
"(",
"\"Malformed key info: incomplete ciphertext or tag\"",
")",
"encrypted_wrapped_key",
"=",
"EncryptedData",
"(",
"iv",
"=",
"iv",
",",
"ciphertext",
"=",
"ciphertext",
",",
"tag",
"=",
"tag",
")",
"return",
"encrypted_wrapped_key"
] | Extracts and deserializes EncryptedData from a Wrapped EncryptedDataKey.
:param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key
:type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm
:param bytes wrapping_key_id: Key ID of wrapping MasterKey
:param wrapped_encrypted_key: Raw Wrapped EncryptedKey
:type wrapped_encrypted_key: aws_encryption_sdk.structures.EncryptedDataKey
:returns: EncryptedData of deserialized Wrapped EncryptedKey
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
:raises SerializationError: if wrapping_key_id does not match deserialized wrapping key id
:raises SerializationError: if wrapping_algorithm IV length does not match deserialized IV length | [
"Extracts",
"and",
"deserializes",
"EncryptedData",
"from",
"a",
"Wrapped",
"EncryptedDataKey",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L417-L451 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/utils/__init__.py | validate_frame_length | def validate_frame_length(frame_length, algorithm):
"""Validates that frame length is within the defined limits and is compatible with the selected algorithm.
:param int frame_length: Frame size in bytes
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:raises SerializationError: if frame size is negative or not a multiple of the algorithm block size
:raises SerializationError: if frame size is larger than the maximum allowed frame size
"""
if frame_length < 0 or frame_length % algorithm.encryption_algorithm.block_size != 0:
raise SerializationError(
"Frame size must be a non-negative multiple of the block size of the crypto algorithm: {block_size}".format(
block_size=algorithm.encryption_algorithm.block_size
)
)
if frame_length > aws_encryption_sdk.internal.defaults.MAX_FRAME_SIZE:
raise SerializationError(
"Frame size too large: {frame} > {max}".format(
frame=frame_length, max=aws_encryption_sdk.internal.defaults.MAX_FRAME_SIZE
)
) | python | def validate_frame_length(frame_length, algorithm):
"""Validates that frame length is within the defined limits and is compatible with the selected algorithm.
:param int frame_length: Frame size in bytes
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:raises SerializationError: if frame size is negative or not a multiple of the algorithm block size
:raises SerializationError: if frame size is larger than the maximum allowed frame size
"""
if frame_length < 0 or frame_length % algorithm.encryption_algorithm.block_size != 0:
raise SerializationError(
"Frame size must be a non-negative multiple of the block size of the crypto algorithm: {block_size}".format(
block_size=algorithm.encryption_algorithm.block_size
)
)
if frame_length > aws_encryption_sdk.internal.defaults.MAX_FRAME_SIZE:
raise SerializationError(
"Frame size too large: {frame} > {max}".format(
frame=frame_length, max=aws_encryption_sdk.internal.defaults.MAX_FRAME_SIZE
)
) | [
"def",
"validate_frame_length",
"(",
"frame_length",
",",
"algorithm",
")",
":",
"if",
"frame_length",
"<",
"0",
"or",
"frame_length",
"%",
"algorithm",
".",
"encryption_algorithm",
".",
"block_size",
"!=",
"0",
":",
"raise",
"SerializationError",
"(",
"\"Frame size must be a non-negative multiple of the block size of the crypto algorithm: {block_size}\"",
".",
"format",
"(",
"block_size",
"=",
"algorithm",
".",
"encryption_algorithm",
".",
"block_size",
")",
")",
"if",
"frame_length",
">",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"MAX_FRAME_SIZE",
":",
"raise",
"SerializationError",
"(",
"\"Frame size too large: {frame} > {max}\"",
".",
"format",
"(",
"frame",
"=",
"frame_length",
",",
"max",
"=",
"aws_encryption_sdk",
".",
"internal",
".",
"defaults",
".",
"MAX_FRAME_SIZE",
")",
")"
] | Validates that frame length is within the defined limits and is compatible with the selected algorithm.
:param int frame_length: Frame size in bytes
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:raises SerializationError: if frame size is negative or not a multiple of the algorithm block size
:raises SerializationError: if frame size is larger than the maximum allowed frame size | [
"Validates",
"that",
"frame",
"length",
"is",
"within",
"the",
"defined",
"limits",
"and",
"is",
"compatible",
"with",
"the",
"selected",
"algorithm",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/utils/__init__.py#L44-L64 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/utils/__init__.py | get_aad_content_string | def get_aad_content_string(content_type, is_final_frame):
"""Prepares the appropriate Body AAD Value for a message body.
:param content_type: Defines the type of content for which to prepare AAD String
:type content_type: aws_encryption_sdk.identifiers.ContentType
:param bool is_final_frame: Boolean stating whether this is the final frame in a body
:returns: Appropriate AAD Content String
:rtype: bytes
:raises UnknownIdentityError: if unknown content type
"""
if content_type == ContentType.NO_FRAMING:
aad_content_string = ContentAADString.NON_FRAMED_STRING_ID
elif content_type == ContentType.FRAMED_DATA:
if is_final_frame:
aad_content_string = ContentAADString.FINAL_FRAME_STRING_ID
else:
aad_content_string = ContentAADString.FRAME_STRING_ID
else:
raise UnknownIdentityError("Unhandled content type")
return aad_content_string | python | def get_aad_content_string(content_type, is_final_frame):
"""Prepares the appropriate Body AAD Value for a message body.
:param content_type: Defines the type of content for which to prepare AAD String
:type content_type: aws_encryption_sdk.identifiers.ContentType
:param bool is_final_frame: Boolean stating whether this is the final frame in a body
:returns: Appropriate AAD Content String
:rtype: bytes
:raises UnknownIdentityError: if unknown content type
"""
if content_type == ContentType.NO_FRAMING:
aad_content_string = ContentAADString.NON_FRAMED_STRING_ID
elif content_type == ContentType.FRAMED_DATA:
if is_final_frame:
aad_content_string = ContentAADString.FINAL_FRAME_STRING_ID
else:
aad_content_string = ContentAADString.FRAME_STRING_ID
else:
raise UnknownIdentityError("Unhandled content type")
return aad_content_string | [
"def",
"get_aad_content_string",
"(",
"content_type",
",",
"is_final_frame",
")",
":",
"if",
"content_type",
"==",
"ContentType",
".",
"NO_FRAMING",
":",
"aad_content_string",
"=",
"ContentAADString",
".",
"NON_FRAMED_STRING_ID",
"elif",
"content_type",
"==",
"ContentType",
".",
"FRAMED_DATA",
":",
"if",
"is_final_frame",
":",
"aad_content_string",
"=",
"ContentAADString",
".",
"FINAL_FRAME_STRING_ID",
"else",
":",
"aad_content_string",
"=",
"ContentAADString",
".",
"FRAME_STRING_ID",
"else",
":",
"raise",
"UnknownIdentityError",
"(",
"\"Unhandled content type\"",
")",
"return",
"aad_content_string"
] | Prepares the appropriate Body AAD Value for a message body.
:param content_type: Defines the type of content for which to prepare AAD String
:type content_type: aws_encryption_sdk.identifiers.ContentType
:param bool is_final_frame: Boolean stating whether this is the final frame in a body
:returns: Appropriate AAD Content String
:rtype: bytes
:raises UnknownIdentityError: if unknown content type | [
"Prepares",
"the",
"appropriate",
"Body",
"AAD",
"Value",
"for",
"a",
"message",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/utils/__init__.py#L76-L95 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/utils/__init__.py | prepare_data_keys | def prepare_data_keys(primary_master_key, master_keys, algorithm, encryption_context):
"""Prepares a DataKey to be used for encrypting message and list
of EncryptedDataKey objects to be serialized into header.
:param primary_master_key: Master key with which to generate the encryption data key
:type primary_master_key: aws_encryption_sdk.key_providers.base.MasterKey
:param master_keys: All master keys with which to encrypt data keys
:type master_keys: list of :class:`aws_encryption_sdk.key_providers.base.MasterKey`
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use when generating data key
:rtype: tuple containing :class:`aws_encryption_sdk.structures.DataKey`
and set of :class:`aws_encryption_sdk.structures.EncryptedDataKey`
"""
encrypted_data_keys = set()
encrypted_data_encryption_key = None
data_encryption_key = primary_master_key.generate_data_key(algorithm, encryption_context)
_LOGGER.debug("encryption data generated with master key: %s", data_encryption_key.key_provider)
for master_key in master_keys:
# Don't re-encrypt the encryption data key; we already have the ciphertext
if master_key is primary_master_key:
encrypted_data_encryption_key = EncryptedDataKey(
key_provider=data_encryption_key.key_provider, encrypted_data_key=data_encryption_key.encrypted_data_key
)
encrypted_data_keys.add(encrypted_data_encryption_key)
continue
encrypted_key = master_key.encrypt_data_key(
data_key=data_encryption_key, algorithm=algorithm, encryption_context=encryption_context
)
encrypted_data_keys.add(encrypted_key)
_LOGGER.debug("encryption key encrypted with master key: %s", master_key.key_provider)
return data_encryption_key, encrypted_data_keys | python | def prepare_data_keys(primary_master_key, master_keys, algorithm, encryption_context):
"""Prepares a DataKey to be used for encrypting message and list
of EncryptedDataKey objects to be serialized into header.
:param primary_master_key: Master key with which to generate the encryption data key
:type primary_master_key: aws_encryption_sdk.key_providers.base.MasterKey
:param master_keys: All master keys with which to encrypt data keys
:type master_keys: list of :class:`aws_encryption_sdk.key_providers.base.MasterKey`
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use when generating data key
:rtype: tuple containing :class:`aws_encryption_sdk.structures.DataKey`
and set of :class:`aws_encryption_sdk.structures.EncryptedDataKey`
"""
encrypted_data_keys = set()
encrypted_data_encryption_key = None
data_encryption_key = primary_master_key.generate_data_key(algorithm, encryption_context)
_LOGGER.debug("encryption data generated with master key: %s", data_encryption_key.key_provider)
for master_key in master_keys:
# Don't re-encrypt the encryption data key; we already have the ciphertext
if master_key is primary_master_key:
encrypted_data_encryption_key = EncryptedDataKey(
key_provider=data_encryption_key.key_provider, encrypted_data_key=data_encryption_key.encrypted_data_key
)
encrypted_data_keys.add(encrypted_data_encryption_key)
continue
encrypted_key = master_key.encrypt_data_key(
data_key=data_encryption_key, algorithm=algorithm, encryption_context=encryption_context
)
encrypted_data_keys.add(encrypted_key)
_LOGGER.debug("encryption key encrypted with master key: %s", master_key.key_provider)
return data_encryption_key, encrypted_data_keys | [
"def",
"prepare_data_keys",
"(",
"primary_master_key",
",",
"master_keys",
",",
"algorithm",
",",
"encryption_context",
")",
":",
"encrypted_data_keys",
"=",
"set",
"(",
")",
"encrypted_data_encryption_key",
"=",
"None",
"data_encryption_key",
"=",
"primary_master_key",
".",
"generate_data_key",
"(",
"algorithm",
",",
"encryption_context",
")",
"_LOGGER",
".",
"debug",
"(",
"\"encryption data generated with master key: %s\"",
",",
"data_encryption_key",
".",
"key_provider",
")",
"for",
"master_key",
"in",
"master_keys",
":",
"# Don't re-encrypt the encryption data key; we already have the ciphertext",
"if",
"master_key",
"is",
"primary_master_key",
":",
"encrypted_data_encryption_key",
"=",
"EncryptedDataKey",
"(",
"key_provider",
"=",
"data_encryption_key",
".",
"key_provider",
",",
"encrypted_data_key",
"=",
"data_encryption_key",
".",
"encrypted_data_key",
")",
"encrypted_data_keys",
".",
"add",
"(",
"encrypted_data_encryption_key",
")",
"continue",
"encrypted_key",
"=",
"master_key",
".",
"encrypt_data_key",
"(",
"data_key",
"=",
"data_encryption_key",
",",
"algorithm",
"=",
"algorithm",
",",
"encryption_context",
"=",
"encryption_context",
")",
"encrypted_data_keys",
".",
"add",
"(",
"encrypted_key",
")",
"_LOGGER",
".",
"debug",
"(",
"\"encryption key encrypted with master key: %s\"",
",",
"master_key",
".",
"key_provider",
")",
"return",
"data_encryption_key",
",",
"encrypted_data_keys"
] | Prepares a DataKey to be used for encrypting message and list
of EncryptedDataKey objects to be serialized into header.
:param primary_master_key: Master key with which to generate the encryption data key
:type primary_master_key: aws_encryption_sdk.key_providers.base.MasterKey
:param master_keys: All master keys with which to encrypt data keys
:type master_keys: list of :class:`aws_encryption_sdk.key_providers.base.MasterKey`
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption context to use when generating data key
:rtype: tuple containing :class:`aws_encryption_sdk.structures.DataKey`
and set of :class:`aws_encryption_sdk.structures.EncryptedDataKey` | [
"Prepares",
"a",
"DataKey",
"to",
"be",
"used",
"for",
"encrypting",
"message",
"and",
"list",
"of",
"EncryptedDataKey",
"objects",
"to",
"be",
"serialized",
"into",
"header",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/utils/__init__.py#L98-L129 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/utils/__init__.py | prep_stream_data | def prep_stream_data(data):
"""Take an input and prepare it for use as a stream.
:param data: Input data
:returns: Prepared stream
:rtype: InsistentReaderBytesIO
"""
if isinstance(data, (six.string_types, six.binary_type)):
stream = io.BytesIO(to_bytes(data))
else:
stream = data
return InsistentReaderBytesIO(stream) | python | def prep_stream_data(data):
"""Take an input and prepare it for use as a stream.
:param data: Input data
:returns: Prepared stream
:rtype: InsistentReaderBytesIO
"""
if isinstance(data, (six.string_types, six.binary_type)):
stream = io.BytesIO(to_bytes(data))
else:
stream = data
return InsistentReaderBytesIO(stream) | [
"def",
"prep_stream_data",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"six",
".",
"string_types",
",",
"six",
".",
"binary_type",
")",
")",
":",
"stream",
"=",
"io",
".",
"BytesIO",
"(",
"to_bytes",
"(",
"data",
")",
")",
"else",
":",
"stream",
"=",
"data",
"return",
"InsistentReaderBytesIO",
"(",
"stream",
")"
] | Take an input and prepare it for use as a stream.
:param data: Input data
:returns: Prepared stream
:rtype: InsistentReaderBytesIO | [
"Take",
"an",
"input",
"and",
"prepare",
"it",
"for",
"use",
"as",
"a",
"stream",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/utils/__init__.py#L132-L144 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/utils/__init__.py | source_data_key_length_check | def source_data_key_length_check(source_data_key, algorithm):
"""Validates that the supplied source_data_key's data_key is the
correct length for the supplied algorithm's kdf_input_len value.
:param source_data_key: Source data key object received from MasterKey decrypt or generate data_key methods
:type source_data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this data key will be used
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:raises InvalidDataKeyError: if data key length does not match required kdf input length
"""
if len(source_data_key.data_key) != algorithm.kdf_input_len:
raise InvalidDataKeyError(
"Invalid Source Data Key length {actual} for algorithm required: {required}".format(
actual=len(source_data_key.data_key), required=algorithm.kdf_input_len
)
) | python | def source_data_key_length_check(source_data_key, algorithm):
"""Validates that the supplied source_data_key's data_key is the
correct length for the supplied algorithm's kdf_input_len value.
:param source_data_key: Source data key object received from MasterKey decrypt or generate data_key methods
:type source_data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this data key will be used
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:raises InvalidDataKeyError: if data key length does not match required kdf input length
"""
if len(source_data_key.data_key) != algorithm.kdf_input_len:
raise InvalidDataKeyError(
"Invalid Source Data Key length {actual} for algorithm required: {required}".format(
actual=len(source_data_key.data_key), required=algorithm.kdf_input_len
)
) | [
"def",
"source_data_key_length_check",
"(",
"source_data_key",
",",
"algorithm",
")",
":",
"if",
"len",
"(",
"source_data_key",
".",
"data_key",
")",
"!=",
"algorithm",
".",
"kdf_input_len",
":",
"raise",
"InvalidDataKeyError",
"(",
"\"Invalid Source Data Key length {actual} for algorithm required: {required}\"",
".",
"format",
"(",
"actual",
"=",
"len",
"(",
"source_data_key",
".",
"data_key",
")",
",",
"required",
"=",
"algorithm",
".",
"kdf_input_len",
")",
")"
] | Validates that the supplied source_data_key's data_key is the
correct length for the supplied algorithm's kdf_input_len value.
:param source_data_key: Source data key object received from MasterKey decrypt or generate data_key methods
:type source_data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
:param algorithm: Algorithm object which directs how this data key will be used
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:raises InvalidDataKeyError: if data key length does not match required kdf input length | [
"Validates",
"that",
"the",
"supplied",
"source_data_key",
"s",
"data_key",
"is",
"the",
"correct",
"length",
"for",
"the",
"supplied",
"algorithm",
"s",
"kdf_input_len",
"value",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/utils/__init__.py#L147-L163 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/encryption.py | encrypt | def encrypt(algorithm, key, plaintext, associated_data, iv):
"""Encrypts a frame body.
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key: Encryption key
:param bytes plaintext: Body plaintext
:param bytes associated_data: Body AAD Data
:param bytes iv: IV to use when encrypting message
:returns: Deserialized object containing encrypted body
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
"""
encryptor = Encryptor(algorithm, key, associated_data, iv)
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return EncryptedData(encryptor.iv, ciphertext, encryptor.tag) | python | def encrypt(algorithm, key, plaintext, associated_data, iv):
"""Encrypts a frame body.
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key: Encryption key
:param bytes plaintext: Body plaintext
:param bytes associated_data: Body AAD Data
:param bytes iv: IV to use when encrypting message
:returns: Deserialized object containing encrypted body
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
"""
encryptor = Encryptor(algorithm, key, associated_data, iv)
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return EncryptedData(encryptor.iv, ciphertext, encryptor.tag) | [
"def",
"encrypt",
"(",
"algorithm",
",",
"key",
",",
"plaintext",
",",
"associated_data",
",",
"iv",
")",
":",
"encryptor",
"=",
"Encryptor",
"(",
"algorithm",
",",
"key",
",",
"associated_data",
",",
"iv",
")",
"ciphertext",
"=",
"encryptor",
".",
"update",
"(",
"plaintext",
")",
"+",
"encryptor",
".",
"finalize",
"(",
")",
"return",
"EncryptedData",
"(",
"encryptor",
".",
"iv",
",",
"ciphertext",
",",
"encryptor",
".",
"tag",
")"
] | Encrypts a frame body.
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key: Encryption key
:param bytes plaintext: Body plaintext
:param bytes associated_data: Body AAD Data
:param bytes iv: IV to use when encrypting message
:returns: Deserialized object containing encrypted body
:rtype: aws_encryption_sdk.internal.structures.EncryptedData | [
"Encrypts",
"a",
"frame",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/encryption.py#L76-L90 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/encryption.py | decrypt | def decrypt(algorithm, key, encrypted_data, associated_data):
"""Decrypts a frame body.
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key: Plaintext data key
:param encrypted_data: EncryptedData containing body data
:type encrypted_data: :class:`aws_encryption_sdk.internal.structures.EncryptedData`,
:class:`aws_encryption_sdk.internal.structures.FrameBody`,
or :class:`aws_encryption_sdk.internal.structures.MessageNoFrameBody`
:param bytes associated_data: AAD string generated for body
:type associated_data: bytes
:returns: Plaintext of body
:rtype: bytes
"""
decryptor = Decryptor(algorithm, key, associated_data, encrypted_data.iv, encrypted_data.tag)
return decryptor.update(encrypted_data.ciphertext) + decryptor.finalize() | python | def decrypt(algorithm, key, encrypted_data, associated_data):
"""Decrypts a frame body.
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key: Plaintext data key
:param encrypted_data: EncryptedData containing body data
:type encrypted_data: :class:`aws_encryption_sdk.internal.structures.EncryptedData`,
:class:`aws_encryption_sdk.internal.structures.FrameBody`,
or :class:`aws_encryption_sdk.internal.structures.MessageNoFrameBody`
:param bytes associated_data: AAD string generated for body
:type associated_data: bytes
:returns: Plaintext of body
:rtype: bytes
"""
decryptor = Decryptor(algorithm, key, associated_data, encrypted_data.iv, encrypted_data.tag)
return decryptor.update(encrypted_data.ciphertext) + decryptor.finalize() | [
"def",
"decrypt",
"(",
"algorithm",
",",
"key",
",",
"encrypted_data",
",",
"associated_data",
")",
":",
"decryptor",
"=",
"Decryptor",
"(",
"algorithm",
",",
"key",
",",
"associated_data",
",",
"encrypted_data",
".",
"iv",
",",
"encrypted_data",
".",
"tag",
")",
"return",
"decryptor",
".",
"update",
"(",
"encrypted_data",
".",
"ciphertext",
")",
"+",
"decryptor",
".",
"finalize",
"(",
")"
] | Decrypts a frame body.
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key: Plaintext data key
:param encrypted_data: EncryptedData containing body data
:type encrypted_data: :class:`aws_encryption_sdk.internal.structures.EncryptedData`,
:class:`aws_encryption_sdk.internal.structures.FrameBody`,
or :class:`aws_encryption_sdk.internal.structures.MessageNoFrameBody`
:param bytes associated_data: AAD string generated for body
:type associated_data: bytes
:returns: Plaintext of body
:rtype: bytes | [
"Decrypts",
"a",
"frame",
"body",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/encryption.py#L135-L151 | train |
aws/aws-encryption-sdk-python | decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/app.py | _master_key_provider | def _master_key_provider() -> KMSMasterKeyProvider:
"""Build the V0 master key provider."""
master_key_provider = KMSMasterKeyProvider()
master_key_provider.add_master_key_provider(NullMasterKey())
master_key_provider.add_master_key_provider(CountingMasterKey())
return master_key_provider | python | def _master_key_provider() -> KMSMasterKeyProvider:
"""Build the V0 master key provider."""
master_key_provider = KMSMasterKeyProvider()
master_key_provider.add_master_key_provider(NullMasterKey())
master_key_provider.add_master_key_provider(CountingMasterKey())
return master_key_provider | [
"def",
"_master_key_provider",
"(",
")",
"->",
"KMSMasterKeyProvider",
":",
"master_key_provider",
"=",
"KMSMasterKeyProvider",
"(",
")",
"master_key_provider",
".",
"add_master_key_provider",
"(",
"NullMasterKey",
"(",
")",
")",
"master_key_provider",
".",
"add_master_key_provider",
"(",
"CountingMasterKey",
"(",
")",
")",
"return",
"master_key_provider"
] | Build the V0 master key provider. | [
"Build",
"the",
"V0",
"master",
"key",
"provider",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/app.py#L30-L35 | train |
aws/aws-encryption-sdk-python | decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/app.py | basic_decrypt | def basic_decrypt() -> Response:
"""Basic decrypt handler for decrypt oracle v0.
**Request**
* **Method**: POST
* **Body**: Raw ciphertext bytes
* **Headers**:
* **Content-Type**: ``application/octet-stream``
* **Accept**: ``application/octet-stream``
**Response**
* 200 response code with the raw plaintext bytes as the body
* 400 response code with whatever error code was encountered as the body
"""
APP.log.debug("Request:")
APP.log.debug(json.dumps(APP.current_request.to_dict()))
APP.log.debug("Ciphertext:")
APP.log.debug(APP.current_request.raw_body)
try:
ciphertext = APP.current_request.raw_body
plaintext, _header = aws_encryption_sdk.decrypt(source=ciphertext, key_provider=_master_key_provider())
APP.log.debug("Plaintext:")
APP.log.debug(plaintext)
response = Response(body=plaintext, headers={"Content-Type": "application/octet-stream"}, status_code=200)
except Exception as error: # pylint: disable=broad-except
response = Response(body=str(error), status_code=400)
APP.log.debug("Response:")
APP.log.debug(json.dumps(response.to_dict(binary_types=["application/octet-stream"])))
return response | python | def basic_decrypt() -> Response:
"""Basic decrypt handler for decrypt oracle v0.
**Request**
* **Method**: POST
* **Body**: Raw ciphertext bytes
* **Headers**:
* **Content-Type**: ``application/octet-stream``
* **Accept**: ``application/octet-stream``
**Response**
* 200 response code with the raw plaintext bytes as the body
* 400 response code with whatever error code was encountered as the body
"""
APP.log.debug("Request:")
APP.log.debug(json.dumps(APP.current_request.to_dict()))
APP.log.debug("Ciphertext:")
APP.log.debug(APP.current_request.raw_body)
try:
ciphertext = APP.current_request.raw_body
plaintext, _header = aws_encryption_sdk.decrypt(source=ciphertext, key_provider=_master_key_provider())
APP.log.debug("Plaintext:")
APP.log.debug(plaintext)
response = Response(body=plaintext, headers={"Content-Type": "application/octet-stream"}, status_code=200)
except Exception as error: # pylint: disable=broad-except
response = Response(body=str(error), status_code=400)
APP.log.debug("Response:")
APP.log.debug(json.dumps(response.to_dict(binary_types=["application/octet-stream"])))
return response | [
"def",
"basic_decrypt",
"(",
")",
"->",
"Response",
":",
"APP",
".",
"log",
".",
"debug",
"(",
"\"Request:\"",
")",
"APP",
".",
"log",
".",
"debug",
"(",
"json",
".",
"dumps",
"(",
"APP",
".",
"current_request",
".",
"to_dict",
"(",
")",
")",
")",
"APP",
".",
"log",
".",
"debug",
"(",
"\"Ciphertext:\"",
")",
"APP",
".",
"log",
".",
"debug",
"(",
"APP",
".",
"current_request",
".",
"raw_body",
")",
"try",
":",
"ciphertext",
"=",
"APP",
".",
"current_request",
".",
"raw_body",
"plaintext",
",",
"_header",
"=",
"aws_encryption_sdk",
".",
"decrypt",
"(",
"source",
"=",
"ciphertext",
",",
"key_provider",
"=",
"_master_key_provider",
"(",
")",
")",
"APP",
".",
"log",
".",
"debug",
"(",
"\"Plaintext:\"",
")",
"APP",
".",
"log",
".",
"debug",
"(",
"plaintext",
")",
"response",
"=",
"Response",
"(",
"body",
"=",
"plaintext",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/octet-stream\"",
"}",
",",
"status_code",
"=",
"200",
")",
"except",
"Exception",
"as",
"error",
":",
"# pylint: disable=broad-except",
"response",
"=",
"Response",
"(",
"body",
"=",
"str",
"(",
"error",
")",
",",
"status_code",
"=",
"400",
")",
"APP",
".",
"log",
".",
"debug",
"(",
"\"Response:\"",
")",
"APP",
".",
"log",
".",
"debug",
"(",
"json",
".",
"dumps",
"(",
"response",
".",
"to_dict",
"(",
"binary_types",
"=",
"[",
"\"application/octet-stream\"",
"]",
")",
")",
")",
"return",
"response"
] | Basic decrypt handler for decrypt oracle v0.
**Request**
* **Method**: POST
* **Body**: Raw ciphertext bytes
* **Headers**:
* **Content-Type**: ``application/octet-stream``
* **Accept**: ``application/octet-stream``
**Response**
* 200 response code with the raw plaintext bytes as the body
* 400 response code with whatever error code was encountered as the body | [
"Basic",
"decrypt",
"handler",
"for",
"decrypt",
"oracle",
"v0",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/app.py#L39-L72 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/utils/streams.py | TeeStream.read | def read(self, b=None):
"""Reads data from source, copying it into ``tee`` before returning.
:param int b: number of bytes to read
"""
data = self.__wrapped__.read(b)
self.__tee.write(data)
return data | python | def read(self, b=None):
"""Reads data from source, copying it into ``tee`` before returning.
:param int b: number of bytes to read
"""
data = self.__wrapped__.read(b)
self.__tee.write(data)
return data | [
"def",
"read",
"(",
"self",
",",
"b",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"__wrapped__",
".",
"read",
"(",
"b",
")",
"self",
".",
"__tee",
".",
"write",
"(",
"data",
")",
"return",
"data"
] | Reads data from source, copying it into ``tee`` before returning.
:param int b: number of bytes to read | [
"Reads",
"data",
"from",
"source",
"copying",
"it",
"into",
"tee",
"before",
"returning",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/utils/streams.py#L54-L61 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/utils/streams.py | InsistentReaderBytesIO.read | def read(self, b=-1):
"""Keep reading from source stream until either the source stream is done
or the requested number of bytes have been obtained.
:param int b: number of bytes to read
:return: All bytes read from wrapped stream
:rtype: bytes
"""
remaining_bytes = b
data = io.BytesIO()
while True:
try:
chunk = to_bytes(self.__wrapped__.read(remaining_bytes))
except ValueError:
if self.__wrapped__.closed:
break
raise
if not chunk:
break
data.write(chunk)
remaining_bytes -= len(chunk)
if remaining_bytes <= 0:
break
return data.getvalue() | python | def read(self, b=-1):
"""Keep reading from source stream until either the source stream is done
or the requested number of bytes have been obtained.
:param int b: number of bytes to read
:return: All bytes read from wrapped stream
:rtype: bytes
"""
remaining_bytes = b
data = io.BytesIO()
while True:
try:
chunk = to_bytes(self.__wrapped__.read(remaining_bytes))
except ValueError:
if self.__wrapped__.closed:
break
raise
if not chunk:
break
data.write(chunk)
remaining_bytes -= len(chunk)
if remaining_bytes <= 0:
break
return data.getvalue() | [
"def",
"read",
"(",
"self",
",",
"b",
"=",
"-",
"1",
")",
":",
"remaining_bytes",
"=",
"b",
"data",
"=",
"io",
".",
"BytesIO",
"(",
")",
"while",
"True",
":",
"try",
":",
"chunk",
"=",
"to_bytes",
"(",
"self",
".",
"__wrapped__",
".",
"read",
"(",
"remaining_bytes",
")",
")",
"except",
"ValueError",
":",
"if",
"self",
".",
"__wrapped__",
".",
"closed",
":",
"break",
"raise",
"if",
"not",
"chunk",
":",
"break",
"data",
".",
"write",
"(",
"chunk",
")",
"remaining_bytes",
"-=",
"len",
"(",
"chunk",
")",
"if",
"remaining_bytes",
"<=",
"0",
":",
"break",
"return",
"data",
".",
"getvalue",
"(",
")"
] | Keep reading from source stream until either the source stream is done
or the requested number of bytes have been obtained.
:param int b: number of bytes to read
:return: All bytes read from wrapped stream
:rtype: bytes | [
"Keep",
"reading",
"from",
"source",
"stream",
"until",
"either",
"the",
"source",
"stream",
"is",
"done",
"or",
"the",
"requested",
"number",
"of",
"bytes",
"have",
"been",
"obtained",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/utils/streams.py#L73-L99 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/elliptic_curve.py | _ecc_static_length_signature | def _ecc_static_length_signature(key, algorithm, digest):
"""Calculates an elliptic curve signature with a static length using pre-calculated hash.
:param key: Elliptic curve private key
:type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
:param algorithm: Master algorithm to use
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes digest: Pre-calculated hash digest
:returns: Signature with required length
:rtype: bytes
"""
pre_hashed_algorithm = ec.ECDSA(Prehashed(algorithm.signing_hash_type()))
signature = b""
while len(signature) != algorithm.signature_len:
_LOGGER.debug(
"Signature length %d is not desired length %d. Recalculating.", len(signature), algorithm.signature_len
)
signature = key.sign(digest, pre_hashed_algorithm)
if len(signature) != algorithm.signature_len:
# Most of the time, a signature of the wrong length can be fixed
# by negating s in the signature relative to the group order.
_LOGGER.debug(
"Signature length %d is not desired length %d. Negating s.", len(signature), algorithm.signature_len
)
r, s = decode_dss_signature(signature)
s = _ECC_CURVE_PARAMETERS[algorithm.signing_algorithm_info.name].order - s
signature = encode_dss_signature(r, s)
return signature | python | def _ecc_static_length_signature(key, algorithm, digest):
"""Calculates an elliptic curve signature with a static length using pre-calculated hash.
:param key: Elliptic curve private key
:type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
:param algorithm: Master algorithm to use
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes digest: Pre-calculated hash digest
:returns: Signature with required length
:rtype: bytes
"""
pre_hashed_algorithm = ec.ECDSA(Prehashed(algorithm.signing_hash_type()))
signature = b""
while len(signature) != algorithm.signature_len:
_LOGGER.debug(
"Signature length %d is not desired length %d. Recalculating.", len(signature), algorithm.signature_len
)
signature = key.sign(digest, pre_hashed_algorithm)
if len(signature) != algorithm.signature_len:
# Most of the time, a signature of the wrong length can be fixed
# by negating s in the signature relative to the group order.
_LOGGER.debug(
"Signature length %d is not desired length %d. Negating s.", len(signature), algorithm.signature_len
)
r, s = decode_dss_signature(signature)
s = _ECC_CURVE_PARAMETERS[algorithm.signing_algorithm_info.name].order - s
signature = encode_dss_signature(r, s)
return signature | [
"def",
"_ecc_static_length_signature",
"(",
"key",
",",
"algorithm",
",",
"digest",
")",
":",
"pre_hashed_algorithm",
"=",
"ec",
".",
"ECDSA",
"(",
"Prehashed",
"(",
"algorithm",
".",
"signing_hash_type",
"(",
")",
")",
")",
"signature",
"=",
"b\"\"",
"while",
"len",
"(",
"signature",
")",
"!=",
"algorithm",
".",
"signature_len",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Signature length %d is not desired length %d. Recalculating.\"",
",",
"len",
"(",
"signature",
")",
",",
"algorithm",
".",
"signature_len",
")",
"signature",
"=",
"key",
".",
"sign",
"(",
"digest",
",",
"pre_hashed_algorithm",
")",
"if",
"len",
"(",
"signature",
")",
"!=",
"algorithm",
".",
"signature_len",
":",
"# Most of the time, a signature of the wrong length can be fixed",
"# by negating s in the signature relative to the group order.",
"_LOGGER",
".",
"debug",
"(",
"\"Signature length %d is not desired length %d. Negating s.\"",
",",
"len",
"(",
"signature",
")",
",",
"algorithm",
".",
"signature_len",
")",
"r",
",",
"s",
"=",
"decode_dss_signature",
"(",
"signature",
")",
"s",
"=",
"_ECC_CURVE_PARAMETERS",
"[",
"algorithm",
".",
"signing_algorithm_info",
".",
"name",
"]",
".",
"order",
"-",
"s",
"signature",
"=",
"encode_dss_signature",
"(",
"r",
",",
"s",
")",
"return",
"signature"
] | Calculates an elliptic curve signature with a static length using pre-calculated hash.
:param key: Elliptic curve private key
:type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
:param algorithm: Master algorithm to use
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes digest: Pre-calculated hash digest
:returns: Signature with required length
:rtype: bytes | [
"Calculates",
"an",
"elliptic",
"curve",
"signature",
"with",
"a",
"static",
"length",
"using",
"pre",
"-",
"calculated",
"hash",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/elliptic_curve.py#L55-L82 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/elliptic_curve.py | generate_ecc_signing_key | def generate_ecc_signing_key(algorithm):
"""Returns an ECC signing key.
:param algorithm: Algorithm object which determines what signature to generate
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:returns: Generated signing key
:raises NotSupportedError: if signing algorithm is not supported on this platform
"""
try:
verify_interface(ec.EllipticCurve, algorithm.signing_algorithm_info)
return ec.generate_private_key(curve=algorithm.signing_algorithm_info(), backend=default_backend())
except InterfaceNotImplemented:
raise NotSupportedError("Unsupported signing algorithm info") | python | def generate_ecc_signing_key(algorithm):
"""Returns an ECC signing key.
:param algorithm: Algorithm object which determines what signature to generate
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:returns: Generated signing key
:raises NotSupportedError: if signing algorithm is not supported on this platform
"""
try:
verify_interface(ec.EllipticCurve, algorithm.signing_algorithm_info)
return ec.generate_private_key(curve=algorithm.signing_algorithm_info(), backend=default_backend())
except InterfaceNotImplemented:
raise NotSupportedError("Unsupported signing algorithm info") | [
"def",
"generate_ecc_signing_key",
"(",
"algorithm",
")",
":",
"try",
":",
"verify_interface",
"(",
"ec",
".",
"EllipticCurve",
",",
"algorithm",
".",
"signing_algorithm_info",
")",
"return",
"ec",
".",
"generate_private_key",
"(",
"curve",
"=",
"algorithm",
".",
"signing_algorithm_info",
"(",
")",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"except",
"InterfaceNotImplemented",
":",
"raise",
"NotSupportedError",
"(",
"\"Unsupported signing algorithm info\"",
")"
] | Returns an ECC signing key.
:param algorithm: Algorithm object which determines what signature to generate
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:returns: Generated signing key
:raises NotSupportedError: if signing algorithm is not supported on this platform | [
"Returns",
"an",
"ECC",
"signing",
"key",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/elliptic_curve.py#L177-L189 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/crypto/data_keys.py | derive_data_encryption_key | def derive_data_encryption_key(source_key, algorithm, message_id):
"""Derives the data encryption key using the defined algorithm.
:param bytes source_key: Raw source key
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes message_id: Message ID
:returns: Derived data encryption key
:rtype: bytes
"""
key = source_key
if algorithm.kdf_type is not None:
key = algorithm.kdf_type(
algorithm=algorithm.kdf_hash_type(),
length=algorithm.data_key_len,
salt=None,
info=struct.pack(">H16s", algorithm.algorithm_id, message_id),
backend=default_backend(),
).derive(source_key)
return key | python | def derive_data_encryption_key(source_key, algorithm, message_id):
"""Derives the data encryption key using the defined algorithm.
:param bytes source_key: Raw source key
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes message_id: Message ID
:returns: Derived data encryption key
:rtype: bytes
"""
key = source_key
if algorithm.kdf_type is not None:
key = algorithm.kdf_type(
algorithm=algorithm.kdf_hash_type(),
length=algorithm.data_key_len,
salt=None,
info=struct.pack(">H16s", algorithm.algorithm_id, message_id),
backend=default_backend(),
).derive(source_key)
return key | [
"def",
"derive_data_encryption_key",
"(",
"source_key",
",",
"algorithm",
",",
"message_id",
")",
":",
"key",
"=",
"source_key",
"if",
"algorithm",
".",
"kdf_type",
"is",
"not",
"None",
":",
"key",
"=",
"algorithm",
".",
"kdf_type",
"(",
"algorithm",
"=",
"algorithm",
".",
"kdf_hash_type",
"(",
")",
",",
"length",
"=",
"algorithm",
".",
"data_key_len",
",",
"salt",
"=",
"None",
",",
"info",
"=",
"struct",
".",
"pack",
"(",
"\">H16s\"",
",",
"algorithm",
".",
"algorithm_id",
",",
"message_id",
")",
",",
"backend",
"=",
"default_backend",
"(",
")",
",",
")",
".",
"derive",
"(",
"source_key",
")",
"return",
"key"
] | Derives the data encryption key using the defined algorithm.
:param bytes source_key: Raw source key
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes message_id: Message ID
:returns: Derived data encryption key
:rtype: bytes | [
"Derives",
"the",
"data",
"encryption",
"key",
"using",
"the",
"defined",
"algorithm",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/data_keys.py#L22-L41 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/__init__.py | encrypt | def encrypt(**kwargs):
"""Encrypts and serializes provided plaintext.
.. note::
When using this function, the entire ciphertext message is encrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import aws_encryption_sdk
>>> kms_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(key_ids=[
... 'arn:aws:kms:us-east-1:2222222222222:key/22222222-2222-2222-2222-222222222222',
... 'arn:aws:kms:us-east-1:3333333333333:key/33333333-3333-3333-3333-333333333333'
... ])
>>> my_ciphertext, encryptor_header = aws_encryption_sdk.encrypt(
... source=my_plaintext,
... key_provider=kms_key_provider
... )
:param config: Client configuration object (config or individual parameters required)
:type config: aws_encryption_sdk.streaming_client.EncryptorConfig
:param source: Source data to encrypt or decrypt
:type source: str, bytes, io.IOBase, or file
:param materials_manager: `CryptoMaterialsManager` from which to obtain cryptographic materials
(either `materials_manager` or `key_provider` required)
:type materials_manager: aws_encryption_sdk.materials_managers.base.CryptoMaterialsManager
:param key_provider: `MasterKeyProvider` from which to obtain data keys for encryption
(either `materials_manager` or `key_provider` required)
:type key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
:param int source_length: Length of source data (optional)
.. note::
If source_length is not provided and unframed message is being written or read() is called,
will attempt to seek() to the end of the stream and tell() to find the length of source data.
.. note::
.. versionadded:: 1.3.0
If `source_length` and `materials_manager` are both provided, the total plaintext bytes
encrypted will not be allowed to exceed `source_length`. To maintain backwards compatibility,
this is not enforced if a `key_provider` is provided.
:param dict encryption_context: Dictionary defining encryption context
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int frame_length: Frame length in bytes
:returns: Tuple containing the encrypted ciphertext and the message header object
:rtype: tuple of bytes and :class:`aws_encryption_sdk.structures.MessageHeader`
"""
with StreamEncryptor(**kwargs) as encryptor:
ciphertext = encryptor.read()
return ciphertext, encryptor.header | python | def encrypt(**kwargs):
"""Encrypts and serializes provided plaintext.
.. note::
When using this function, the entire ciphertext message is encrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import aws_encryption_sdk
>>> kms_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(key_ids=[
... 'arn:aws:kms:us-east-1:2222222222222:key/22222222-2222-2222-2222-222222222222',
... 'arn:aws:kms:us-east-1:3333333333333:key/33333333-3333-3333-3333-333333333333'
... ])
>>> my_ciphertext, encryptor_header = aws_encryption_sdk.encrypt(
... source=my_plaintext,
... key_provider=kms_key_provider
... )
:param config: Client configuration object (config or individual parameters required)
:type config: aws_encryption_sdk.streaming_client.EncryptorConfig
:param source: Source data to encrypt or decrypt
:type source: str, bytes, io.IOBase, or file
:param materials_manager: `CryptoMaterialsManager` from which to obtain cryptographic materials
(either `materials_manager` or `key_provider` required)
:type materials_manager: aws_encryption_sdk.materials_managers.base.CryptoMaterialsManager
:param key_provider: `MasterKeyProvider` from which to obtain data keys for encryption
(either `materials_manager` or `key_provider` required)
:type key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
:param int source_length: Length of source data (optional)
.. note::
If source_length is not provided and unframed message is being written or read() is called,
will attempt to seek() to the end of the stream and tell() to find the length of source data.
.. note::
.. versionadded:: 1.3.0
If `source_length` and `materials_manager` are both provided, the total plaintext bytes
encrypted will not be allowed to exceed `source_length`. To maintain backwards compatibility,
this is not enforced if a `key_provider` is provided.
:param dict encryption_context: Dictionary defining encryption context
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int frame_length: Frame length in bytes
:returns: Tuple containing the encrypted ciphertext and the message header object
:rtype: tuple of bytes and :class:`aws_encryption_sdk.structures.MessageHeader`
"""
with StreamEncryptor(**kwargs) as encryptor:
ciphertext = encryptor.read()
return ciphertext, encryptor.header | [
"def",
"encrypt",
"(",
"*",
"*",
"kwargs",
")",
":",
"with",
"StreamEncryptor",
"(",
"*",
"*",
"kwargs",
")",
"as",
"encryptor",
":",
"ciphertext",
"=",
"encryptor",
".",
"read",
"(",
")",
"return",
"ciphertext",
",",
"encryptor",
".",
"header"
] | Encrypts and serializes provided plaintext.
.. note::
When using this function, the entire ciphertext message is encrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import aws_encryption_sdk
>>> kms_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(key_ids=[
... 'arn:aws:kms:us-east-1:2222222222222:key/22222222-2222-2222-2222-222222222222',
... 'arn:aws:kms:us-east-1:3333333333333:key/33333333-3333-3333-3333-333333333333'
... ])
>>> my_ciphertext, encryptor_header = aws_encryption_sdk.encrypt(
... source=my_plaintext,
... key_provider=kms_key_provider
... )
:param config: Client configuration object (config or individual parameters required)
:type config: aws_encryption_sdk.streaming_client.EncryptorConfig
:param source: Source data to encrypt or decrypt
:type source: str, bytes, io.IOBase, or file
:param materials_manager: `CryptoMaterialsManager` from which to obtain cryptographic materials
(either `materials_manager` or `key_provider` required)
:type materials_manager: aws_encryption_sdk.materials_managers.base.CryptoMaterialsManager
:param key_provider: `MasterKeyProvider` from which to obtain data keys for encryption
(either `materials_manager` or `key_provider` required)
:type key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
:param int source_length: Length of source data (optional)
.. note::
If source_length is not provided and unframed message is being written or read() is called,
will attempt to seek() to the end of the stream and tell() to find the length of source data.
.. note::
.. versionadded:: 1.3.0
If `source_length` and `materials_manager` are both provided, the total plaintext bytes
encrypted will not be allowed to exceed `source_length`. To maintain backwards compatibility,
this is not enforced if a `key_provider` is provided.
:param dict encryption_context: Dictionary defining encryption context
:param algorithm: Algorithm to use for encryption
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int frame_length: Frame length in bytes
:returns: Tuple containing the encrypted ciphertext and the message header object
:rtype: tuple of bytes and :class:`aws_encryption_sdk.structures.MessageHeader` | [
"Encrypts",
"and",
"serializes",
"provided",
"plaintext",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/__init__.py#L29-L80 | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/__init__.py | decrypt | def decrypt(**kwargs):
"""Deserializes and decrypts provided ciphertext.
.. note::
When using this function, the entire ciphertext message is decrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import aws_encryption_sdk
>>> kms_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(key_ids=[
... 'arn:aws:kms:us-east-1:2222222222222:key/22222222-2222-2222-2222-222222222222',
... 'arn:aws:kms:us-east-1:3333333333333:key/33333333-3333-3333-3333-333333333333'
... ])
>>> my_ciphertext, encryptor_header = aws_encryption_sdk.decrypt(
... source=my_ciphertext,
... key_provider=kms_key_provider
... )
:param config: Client configuration object (config or individual parameters required)
:type config: aws_encryption_sdk.streaming_client.DecryptorConfig
:param source: Source data to encrypt or decrypt
:type source: str, bytes, io.IOBase, or file
:param materials_manager: `CryptoMaterialsManager` from which to obtain cryptographic materials
(either `materials_manager` or `key_provider` required)
:type materials_manager: aws_encryption_sdk.materials_managers.base.CryptoMaterialsManager
:param key_provider: `MasterKeyProvider` from which to obtain data keys for decryption
(either `materials_manager` or `key_provider` required)
:type key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
:param int source_length: Length of source data (optional)
.. note::
If source_length is not provided and read() is called, will attempt to seek()
to the end of the stream and tell() to find the length of source data.
:param int max_body_length: Maximum frame size (or content length for non-framed messages)
in bytes to read from ciphertext message.
:returns: Tuple containing the decrypted plaintext and the message header object
:rtype: tuple of bytes and :class:`aws_encryption_sdk.structures.MessageHeader`
"""
with StreamDecryptor(**kwargs) as decryptor:
plaintext = decryptor.read()
return plaintext, decryptor.header | python | def decrypt(**kwargs):
"""Deserializes and decrypts provided ciphertext.
.. note::
When using this function, the entire ciphertext message is decrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import aws_encryption_sdk
>>> kms_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(key_ids=[
... 'arn:aws:kms:us-east-1:2222222222222:key/22222222-2222-2222-2222-222222222222',
... 'arn:aws:kms:us-east-1:3333333333333:key/33333333-3333-3333-3333-333333333333'
... ])
>>> my_ciphertext, encryptor_header = aws_encryption_sdk.decrypt(
... source=my_ciphertext,
... key_provider=kms_key_provider
... )
:param config: Client configuration object (config or individual parameters required)
:type config: aws_encryption_sdk.streaming_client.DecryptorConfig
:param source: Source data to encrypt or decrypt
:type source: str, bytes, io.IOBase, or file
:param materials_manager: `CryptoMaterialsManager` from which to obtain cryptographic materials
(either `materials_manager` or `key_provider` required)
:type materials_manager: aws_encryption_sdk.materials_managers.base.CryptoMaterialsManager
:param key_provider: `MasterKeyProvider` from which to obtain data keys for decryption
(either `materials_manager` or `key_provider` required)
:type key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
:param int source_length: Length of source data (optional)
.. note::
If source_length is not provided and read() is called, will attempt to seek()
to the end of the stream and tell() to find the length of source data.
:param int max_body_length: Maximum frame size (or content length for non-framed messages)
in bytes to read from ciphertext message.
:returns: Tuple containing the decrypted plaintext and the message header object
:rtype: tuple of bytes and :class:`aws_encryption_sdk.structures.MessageHeader`
"""
with StreamDecryptor(**kwargs) as decryptor:
plaintext = decryptor.read()
return plaintext, decryptor.header | [
"def",
"decrypt",
"(",
"*",
"*",
"kwargs",
")",
":",
"with",
"StreamDecryptor",
"(",
"*",
"*",
"kwargs",
")",
"as",
"decryptor",
":",
"plaintext",
"=",
"decryptor",
".",
"read",
"(",
")",
"return",
"plaintext",
",",
"decryptor",
".",
"header"
] | Deserializes and decrypts provided ciphertext.
.. note::
When using this function, the entire ciphertext message is decrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import aws_encryption_sdk
>>> kms_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(key_ids=[
... 'arn:aws:kms:us-east-1:2222222222222:key/22222222-2222-2222-2222-222222222222',
... 'arn:aws:kms:us-east-1:3333333333333:key/33333333-3333-3333-3333-333333333333'
... ])
>>> my_ciphertext, encryptor_header = aws_encryption_sdk.decrypt(
... source=my_ciphertext,
... key_provider=kms_key_provider
... )
:param config: Client configuration object (config or individual parameters required)
:type config: aws_encryption_sdk.streaming_client.DecryptorConfig
:param source: Source data to encrypt or decrypt
:type source: str, bytes, io.IOBase, or file
:param materials_manager: `CryptoMaterialsManager` from which to obtain cryptographic materials
(either `materials_manager` or `key_provider` required)
:type materials_manager: aws_encryption_sdk.materials_managers.base.CryptoMaterialsManager
:param key_provider: `MasterKeyProvider` from which to obtain data keys for decryption
(either `materials_manager` or `key_provider` required)
:type key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
:param int source_length: Length of source data (optional)
.. note::
If source_length is not provided and read() is called, will attempt to seek()
to the end of the stream and tell() to find the length of source data.
:param int max_body_length: Maximum frame size (or content length for non-framed messages)
in bytes to read from ciphertext message.
:returns: Tuple containing the decrypted plaintext and the message header object
:rtype: tuple of bytes and :class:`aws_encryption_sdk.structures.MessageHeader` | [
"Deserializes",
"and",
"decrypts",
"provided",
"ciphertext",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/__init__.py#L83-L125 | train |
aws/aws-encryption-sdk-python | examples/src/basic_file_encryption_with_multiple_providers.py | cycle_file | def cycle_file(key_arn, source_plaintext_filename, botocore_session=None):
"""Encrypts and then decrypts a file using a KMS master key provider and a custom static master
key provider. Both master key providers are used to encrypt the plaintext file, so either one alone
can decrypt it.
:param str key_arn: Amazon Resource Name (ARN) of the KMS Customer Master Key (CMK)
(http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html)
:param str source_plaintext_filename: Filename of file to encrypt
:param botocore_session: existing botocore session instance
:type botocore_session: botocore.session.Session
"""
# "Cycled" means encrypted and then decrypted
ciphertext_filename = source_plaintext_filename + ".encrypted"
cycled_kms_plaintext_filename = source_plaintext_filename + ".kms.decrypted"
cycled_static_plaintext_filename = source_plaintext_filename + ".static.decrypted"
# Create a KMS master key provider
kms_kwargs = dict(key_ids=[key_arn])
if botocore_session is not None:
kms_kwargs["botocore_session"] = botocore_session
kms_master_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(**kms_kwargs)
# Create a static master key provider and add a master key to it
static_key_id = os.urandom(8)
static_master_key_provider = StaticRandomMasterKeyProvider()
static_master_key_provider.add_master_key(static_key_id)
# Add the static master key provider to the KMS master key provider
# The resulting master key provider uses KMS master keys to generate (and encrypt)
# data keys and static master keys to create an additional encrypted copy of each data key.
kms_master_key_provider.add_master_key_provider(static_master_key_provider)
# Encrypt plaintext with both KMS and static master keys
with open(source_plaintext_filename, "rb") as plaintext, open(ciphertext_filename, "wb") as ciphertext:
with aws_encryption_sdk.stream(source=plaintext, mode="e", key_provider=kms_master_key_provider) as encryptor:
for chunk in encryptor:
ciphertext.write(chunk)
# Decrypt the ciphertext with only the KMS master key
with open(ciphertext_filename, "rb") as ciphertext, open(cycled_kms_plaintext_filename, "wb") as plaintext:
with aws_encryption_sdk.stream(
source=ciphertext, mode="d", key_provider=aws_encryption_sdk.KMSMasterKeyProvider(**kms_kwargs)
) as kms_decryptor:
for chunk in kms_decryptor:
plaintext.write(chunk)
# Decrypt the ciphertext with only the static master key
with open(ciphertext_filename, "rb") as ciphertext, open(cycled_static_plaintext_filename, "wb") as plaintext:
with aws_encryption_sdk.stream(
source=ciphertext, mode="d", key_provider=static_master_key_provider
) as static_decryptor:
for chunk in static_decryptor:
plaintext.write(chunk)
# Verify that the "cycled" (encrypted, then decrypted) plaintext is identical to the source plaintext
assert filecmp.cmp(source_plaintext_filename, cycled_kms_plaintext_filename)
assert filecmp.cmp(source_plaintext_filename, cycled_static_plaintext_filename)
# Verify that the encryption context in the decrypt operation includes all key pairs from the
# encrypt operation.
#
# In production, always use a meaningful encryption context. In this sample, we omit the
# encryption context (no key pairs).
assert all(
pair in kms_decryptor.header.encryption_context.items() for pair in encryptor.header.encryption_context.items()
)
assert all(
pair in static_decryptor.header.encryption_context.items()
for pair in encryptor.header.encryption_context.items()
)
return ciphertext_filename, cycled_kms_plaintext_filename, cycled_static_plaintext_filename | python | def cycle_file(key_arn, source_plaintext_filename, botocore_session=None):
"""Encrypts and then decrypts a file using a KMS master key provider and a custom static master
key provider. Both master key providers are used to encrypt the plaintext file, so either one alone
can decrypt it.
:param str key_arn: Amazon Resource Name (ARN) of the KMS Customer Master Key (CMK)
(http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html)
:param str source_plaintext_filename: Filename of file to encrypt
:param botocore_session: existing botocore session instance
:type botocore_session: botocore.session.Session
"""
# "Cycled" means encrypted and then decrypted
ciphertext_filename = source_plaintext_filename + ".encrypted"
cycled_kms_plaintext_filename = source_plaintext_filename + ".kms.decrypted"
cycled_static_plaintext_filename = source_plaintext_filename + ".static.decrypted"
# Create a KMS master key provider
kms_kwargs = dict(key_ids=[key_arn])
if botocore_session is not None:
kms_kwargs["botocore_session"] = botocore_session
kms_master_key_provider = aws_encryption_sdk.KMSMasterKeyProvider(**kms_kwargs)
# Create a static master key provider and add a master key to it
static_key_id = os.urandom(8)
static_master_key_provider = StaticRandomMasterKeyProvider()
static_master_key_provider.add_master_key(static_key_id)
# Add the static master key provider to the KMS master key provider
# The resulting master key provider uses KMS master keys to generate (and encrypt)
# data keys and static master keys to create an additional encrypted copy of each data key.
kms_master_key_provider.add_master_key_provider(static_master_key_provider)
# Encrypt plaintext with both KMS and static master keys
with open(source_plaintext_filename, "rb") as plaintext, open(ciphertext_filename, "wb") as ciphertext:
with aws_encryption_sdk.stream(source=plaintext, mode="e", key_provider=kms_master_key_provider) as encryptor:
for chunk in encryptor:
ciphertext.write(chunk)
# Decrypt the ciphertext with only the KMS master key
with open(ciphertext_filename, "rb") as ciphertext, open(cycled_kms_plaintext_filename, "wb") as plaintext:
with aws_encryption_sdk.stream(
source=ciphertext, mode="d", key_provider=aws_encryption_sdk.KMSMasterKeyProvider(**kms_kwargs)
) as kms_decryptor:
for chunk in kms_decryptor:
plaintext.write(chunk)
# Decrypt the ciphertext with only the static master key
with open(ciphertext_filename, "rb") as ciphertext, open(cycled_static_plaintext_filename, "wb") as plaintext:
with aws_encryption_sdk.stream(
source=ciphertext, mode="d", key_provider=static_master_key_provider
) as static_decryptor:
for chunk in static_decryptor:
plaintext.write(chunk)
# Verify that the "cycled" (encrypted, then decrypted) plaintext is identical to the source plaintext
assert filecmp.cmp(source_plaintext_filename, cycled_kms_plaintext_filename)
assert filecmp.cmp(source_plaintext_filename, cycled_static_plaintext_filename)
# Verify that the encryption context in the decrypt operation includes all key pairs from the
# encrypt operation.
#
# In production, always use a meaningful encryption context. In this sample, we omit the
# encryption context (no key pairs).
assert all(
pair in kms_decryptor.header.encryption_context.items() for pair in encryptor.header.encryption_context.items()
)
assert all(
pair in static_decryptor.header.encryption_context.items()
for pair in encryptor.header.encryption_context.items()
)
return ciphertext_filename, cycled_kms_plaintext_filename, cycled_static_plaintext_filename | [
"def",
"cycle_file",
"(",
"key_arn",
",",
"source_plaintext_filename",
",",
"botocore_session",
"=",
"None",
")",
":",
"# \"Cycled\" means encrypted and then decrypted",
"ciphertext_filename",
"=",
"source_plaintext_filename",
"+",
"\".encrypted\"",
"cycled_kms_plaintext_filename",
"=",
"source_plaintext_filename",
"+",
"\".kms.decrypted\"",
"cycled_static_plaintext_filename",
"=",
"source_plaintext_filename",
"+",
"\".static.decrypted\"",
"# Create a KMS master key provider",
"kms_kwargs",
"=",
"dict",
"(",
"key_ids",
"=",
"[",
"key_arn",
"]",
")",
"if",
"botocore_session",
"is",
"not",
"None",
":",
"kms_kwargs",
"[",
"\"botocore_session\"",
"]",
"=",
"botocore_session",
"kms_master_key_provider",
"=",
"aws_encryption_sdk",
".",
"KMSMasterKeyProvider",
"(",
"*",
"*",
"kms_kwargs",
")",
"# Create a static master key provider and add a master key to it",
"static_key_id",
"=",
"os",
".",
"urandom",
"(",
"8",
")",
"static_master_key_provider",
"=",
"StaticRandomMasterKeyProvider",
"(",
")",
"static_master_key_provider",
".",
"add_master_key",
"(",
"static_key_id",
")",
"# Add the static master key provider to the KMS master key provider",
"# The resulting master key provider uses KMS master keys to generate (and encrypt)",
"# data keys and static master keys to create an additional encrypted copy of each data key.",
"kms_master_key_provider",
".",
"add_master_key_provider",
"(",
"static_master_key_provider",
")",
"# Encrypt plaintext with both KMS and static master keys",
"with",
"open",
"(",
"source_plaintext_filename",
",",
"\"rb\"",
")",
"as",
"plaintext",
",",
"open",
"(",
"ciphertext_filename",
",",
"\"wb\"",
")",
"as",
"ciphertext",
":",
"with",
"aws_encryption_sdk",
".",
"stream",
"(",
"source",
"=",
"plaintext",
",",
"mode",
"=",
"\"e\"",
",",
"key_provider",
"=",
"kms_master_key_provider",
")",
"as",
"encryptor",
":",
"for",
"chunk",
"in",
"encryptor",
":",
"ciphertext",
".",
"write",
"(",
"chunk",
")",
"# Decrypt the ciphertext with only the KMS master key",
"with",
"open",
"(",
"ciphertext_filename",
",",
"\"rb\"",
")",
"as",
"ciphertext",
",",
"open",
"(",
"cycled_kms_plaintext_filename",
",",
"\"wb\"",
")",
"as",
"plaintext",
":",
"with",
"aws_encryption_sdk",
".",
"stream",
"(",
"source",
"=",
"ciphertext",
",",
"mode",
"=",
"\"d\"",
",",
"key_provider",
"=",
"aws_encryption_sdk",
".",
"KMSMasterKeyProvider",
"(",
"*",
"*",
"kms_kwargs",
")",
")",
"as",
"kms_decryptor",
":",
"for",
"chunk",
"in",
"kms_decryptor",
":",
"plaintext",
".",
"write",
"(",
"chunk",
")",
"# Decrypt the ciphertext with only the static master key",
"with",
"open",
"(",
"ciphertext_filename",
",",
"\"rb\"",
")",
"as",
"ciphertext",
",",
"open",
"(",
"cycled_static_plaintext_filename",
",",
"\"wb\"",
")",
"as",
"plaintext",
":",
"with",
"aws_encryption_sdk",
".",
"stream",
"(",
"source",
"=",
"ciphertext",
",",
"mode",
"=",
"\"d\"",
",",
"key_provider",
"=",
"static_master_key_provider",
")",
"as",
"static_decryptor",
":",
"for",
"chunk",
"in",
"static_decryptor",
":",
"plaintext",
".",
"write",
"(",
"chunk",
")",
"# Verify that the \"cycled\" (encrypted, then decrypted) plaintext is identical to the source plaintext",
"assert",
"filecmp",
".",
"cmp",
"(",
"source_plaintext_filename",
",",
"cycled_kms_plaintext_filename",
")",
"assert",
"filecmp",
".",
"cmp",
"(",
"source_plaintext_filename",
",",
"cycled_static_plaintext_filename",
")",
"# Verify that the encryption context in the decrypt operation includes all key pairs from the",
"# encrypt operation.",
"#",
"# In production, always use a meaningful encryption context. In this sample, we omit the",
"# encryption context (no key pairs).",
"assert",
"all",
"(",
"pair",
"in",
"kms_decryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
"for",
"pair",
"in",
"encryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
")",
"assert",
"all",
"(",
"pair",
"in",
"static_decryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
"for",
"pair",
"in",
"encryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
")",
"return",
"ciphertext_filename",
",",
"cycled_kms_plaintext_filename",
",",
"cycled_static_plaintext_filename"
] | Encrypts and then decrypts a file using a KMS master key provider and a custom static master
key provider. Both master key providers are used to encrypt the plaintext file, so either one alone
can decrypt it.
:param str key_arn: Amazon Resource Name (ARN) of the KMS Customer Master Key (CMK)
(http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html)
:param str source_plaintext_filename: Filename of file to encrypt
:param botocore_session: existing botocore session instance
:type botocore_session: botocore.session.Session | [
"Encrypts",
"and",
"then",
"decrypts",
"a",
"file",
"using",
"a",
"KMS",
"master",
"key",
"provider",
"and",
"a",
"custom",
"static",
"master",
"key",
"provider",
".",
"Both",
"master",
"key",
"providers",
"are",
"used",
"to",
"encrypt",
"the",
"plaintext",
"file",
"so",
"either",
"one",
"alone",
"can",
"decrypt",
"it",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/examples/src/basic_file_encryption_with_multiple_providers.py#L63-L133 | train |
aws/aws-encryption-sdk-python | examples/src/basic_file_encryption_with_multiple_providers.py | StaticRandomMasterKeyProvider._get_raw_key | def _get_raw_key(self, key_id):
"""Retrieves a static, randomly generated, RSA key for the specified key id.
:param str key_id: User-defined ID for the static key
:returns: Wrapping key that contains the specified static key
:rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`
"""
try:
static_key = self._static_keys[key_id]
except KeyError:
private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend())
static_key = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
self._static_keys[key_id] = static_key
return WrappingKey(
wrapping_algorithm=WrappingAlgorithm.RSA_OAEP_SHA1_MGF1,
wrapping_key=static_key,
wrapping_key_type=EncryptionKeyType.PRIVATE,
) | python | def _get_raw_key(self, key_id):
"""Retrieves a static, randomly generated, RSA key for the specified key id.
:param str key_id: User-defined ID for the static key
:returns: Wrapping key that contains the specified static key
:rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`
"""
try:
static_key = self._static_keys[key_id]
except KeyError:
private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend())
static_key = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
self._static_keys[key_id] = static_key
return WrappingKey(
wrapping_algorithm=WrappingAlgorithm.RSA_OAEP_SHA1_MGF1,
wrapping_key=static_key,
wrapping_key_type=EncryptionKeyType.PRIVATE,
) | [
"def",
"_get_raw_key",
"(",
"self",
",",
"key_id",
")",
":",
"try",
":",
"static_key",
"=",
"self",
".",
"_static_keys",
"[",
"key_id",
"]",
"except",
"KeyError",
":",
"private_key",
"=",
"rsa",
".",
"generate_private_key",
"(",
"public_exponent",
"=",
"65537",
",",
"key_size",
"=",
"4096",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"static_key",
"=",
"private_key",
".",
"private_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"PEM",
",",
"format",
"=",
"serialization",
".",
"PrivateFormat",
".",
"PKCS8",
",",
"encryption_algorithm",
"=",
"serialization",
".",
"NoEncryption",
"(",
")",
",",
")",
"self",
".",
"_static_keys",
"[",
"key_id",
"]",
"=",
"static_key",
"return",
"WrappingKey",
"(",
"wrapping_algorithm",
"=",
"WrappingAlgorithm",
".",
"RSA_OAEP_SHA1_MGF1",
",",
"wrapping_key",
"=",
"static_key",
",",
"wrapping_key_type",
"=",
"EncryptionKeyType",
".",
"PRIVATE",
",",
")"
] | Retrieves a static, randomly generated, RSA key for the specified key id.
:param str key_id: User-defined ID for the static key
:returns: Wrapping key that contains the specified static key
:rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey` | [
"Retrieves",
"a",
"static",
"randomly",
"generated",
"RSA",
"key",
"for",
"the",
"specified",
"key",
"id",
"."
] | d182155d5fb1ef176d9e7d0647679737d5146495 | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/examples/src/basic_file_encryption_with_multiple_providers.py#L39-L60 | train |
dakrauth/django-swingtime | swingtime/utils.py | month_boundaries | def month_boundaries(dt=None):
'''
Return a 2-tuple containing the datetime instances for the first and last
dates of the current month or using ``dt`` as a reference.
'''
dt = dt or date.today()
wkday, ndays = calendar.monthrange(dt.year, dt.month)
start = datetime(dt.year, dt.month, 1)
return (start, start + timedelta(ndays - 1)) | python | def month_boundaries(dt=None):
'''
Return a 2-tuple containing the datetime instances for the first and last
dates of the current month or using ``dt`` as a reference.
'''
dt = dt or date.today()
wkday, ndays = calendar.monthrange(dt.year, dt.month)
start = datetime(dt.year, dt.month, 1)
return (start, start + timedelta(ndays - 1)) | [
"def",
"month_boundaries",
"(",
"dt",
"=",
"None",
")",
":",
"dt",
"=",
"dt",
"or",
"date",
".",
"today",
"(",
")",
"wkday",
",",
"ndays",
"=",
"calendar",
".",
"monthrange",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
")",
"start",
"=",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"1",
")",
"return",
"(",
"start",
",",
"start",
"+",
"timedelta",
"(",
"ndays",
"-",
"1",
")",
")"
] | Return a 2-tuple containing the datetime instances for the first and last
dates of the current month or using ``dt`` as a reference. | [
"Return",
"a",
"2",
"-",
"tuple",
"containing",
"the",
"datetime",
"instances",
"for",
"the",
"first",
"and",
"last",
"dates",
"of",
"the",
"current",
"month",
"or",
"using",
"dt",
"as",
"a",
"reference",
"."
] | d1cdd449bd5c6895c3ff182fd890c4d3452943fe | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/utils.py#L27-L36 | train |
dakrauth/django-swingtime | swingtime/utils.py | css_class_cycler | def css_class_cycler():
'''
Return a dictionary keyed by ``EventType`` abbreviations, whose values are an
iterable or cycle of CSS class names.
'''
FMT = 'evt-{0}-{1}'.format
return defaultdict(default_css_class_cycler, (
(e.abbr, itertools.cycle((FMT(e.abbr, 'even'), FMT(e.abbr, 'odd'))))
for e in EventType.objects.all()
)) | python | def css_class_cycler():
'''
Return a dictionary keyed by ``EventType`` abbreviations, whose values are an
iterable or cycle of CSS class names.
'''
FMT = 'evt-{0}-{1}'.format
return defaultdict(default_css_class_cycler, (
(e.abbr, itertools.cycle((FMT(e.abbr, 'even'), FMT(e.abbr, 'odd'))))
for e in EventType.objects.all()
)) | [
"def",
"css_class_cycler",
"(",
")",
":",
"FMT",
"=",
"'evt-{0}-{1}'",
".",
"format",
"return",
"defaultdict",
"(",
"default_css_class_cycler",
",",
"(",
"(",
"e",
".",
"abbr",
",",
"itertools",
".",
"cycle",
"(",
"(",
"FMT",
"(",
"e",
".",
"abbr",
",",
"'even'",
")",
",",
"FMT",
"(",
"e",
".",
"abbr",
",",
"'odd'",
")",
")",
")",
")",
"for",
"e",
"in",
"EventType",
".",
"objects",
".",
"all",
"(",
")",
")",
")"
] | Return a dictionary keyed by ``EventType`` abbreviations, whose values are an
iterable or cycle of CSS class names. | [
"Return",
"a",
"dictionary",
"keyed",
"by",
"EventType",
"abbreviations",
"whose",
"values",
"are",
"an",
"iterable",
"or",
"cycle",
"of",
"CSS",
"class",
"names",
"."
] | d1cdd449bd5c6895c3ff182fd890c4d3452943fe | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/utils.py#L43-L53 | train |
dakrauth/django-swingtime | swingtime/models.py | create_event | def create_event(
title,
event_type,
description='',
start_time=None,
end_time=None,
note=None,
**rrule_params
):
'''
Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
rules match those for ``Event.add_occurrences``.
Returns the newly created ``Event`` instance.
Parameters
``event_type``
can be either an ``EventType`` object or 2-tuple of ``(abbreviation,label)``,
from which an ``EventType`` is either created or retrieved.
``start_time``
will default to the current hour if ``None``
``end_time``
will default to ``start_time`` plus swingtime_settings.DEFAULT_OCCURRENCE_DURATION
hour if ``None``
``freq``, ``count``, ``rrule_params``
follow the ``dateutils`` API (see http://labix.org/python-dateutil)
'''
if isinstance(event_type, tuple):
event_type, created = EventType.objects.get_or_create(
abbr=event_type[0],
label=event_type[1]
)
event = Event.objects.create(
title=title,
description=description,
event_type=event_type
)
if note is not None:
event.notes.create(note=note)
start_time = start_time or datetime.now().replace(
minute=0,
second=0,
microsecond=0
)
end_time = end_time or (start_time + swingtime_settings.DEFAULT_OCCURRENCE_DURATION)
event.add_occurrences(start_time, end_time, **rrule_params)
return event | python | def create_event(
title,
event_type,
description='',
start_time=None,
end_time=None,
note=None,
**rrule_params
):
'''
Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
rules match those for ``Event.add_occurrences``.
Returns the newly created ``Event`` instance.
Parameters
``event_type``
can be either an ``EventType`` object or 2-tuple of ``(abbreviation,label)``,
from which an ``EventType`` is either created or retrieved.
``start_time``
will default to the current hour if ``None``
``end_time``
will default to ``start_time`` plus swingtime_settings.DEFAULT_OCCURRENCE_DURATION
hour if ``None``
``freq``, ``count``, ``rrule_params``
follow the ``dateutils`` API (see http://labix.org/python-dateutil)
'''
if isinstance(event_type, tuple):
event_type, created = EventType.objects.get_or_create(
abbr=event_type[0],
label=event_type[1]
)
event = Event.objects.create(
title=title,
description=description,
event_type=event_type
)
if note is not None:
event.notes.create(note=note)
start_time = start_time or datetime.now().replace(
minute=0,
second=0,
microsecond=0
)
end_time = end_time or (start_time + swingtime_settings.DEFAULT_OCCURRENCE_DURATION)
event.add_occurrences(start_time, end_time, **rrule_params)
return event | [
"def",
"create_event",
"(",
"title",
",",
"event_type",
",",
"description",
"=",
"''",
",",
"start_time",
"=",
"None",
",",
"end_time",
"=",
"None",
",",
"note",
"=",
"None",
",",
"*",
"*",
"rrule_params",
")",
":",
"if",
"isinstance",
"(",
"event_type",
",",
"tuple",
")",
":",
"event_type",
",",
"created",
"=",
"EventType",
".",
"objects",
".",
"get_or_create",
"(",
"abbr",
"=",
"event_type",
"[",
"0",
"]",
",",
"label",
"=",
"event_type",
"[",
"1",
"]",
")",
"event",
"=",
"Event",
".",
"objects",
".",
"create",
"(",
"title",
"=",
"title",
",",
"description",
"=",
"description",
",",
"event_type",
"=",
"event_type",
")",
"if",
"note",
"is",
"not",
"None",
":",
"event",
".",
"notes",
".",
"create",
"(",
"note",
"=",
"note",
")",
"start_time",
"=",
"start_time",
"or",
"datetime",
".",
"now",
"(",
")",
".",
"replace",
"(",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"end_time",
"=",
"end_time",
"or",
"(",
"start_time",
"+",
"swingtime_settings",
".",
"DEFAULT_OCCURRENCE_DURATION",
")",
"event",
".",
"add_occurrences",
"(",
"start_time",
",",
"end_time",
",",
"*",
"*",
"rrule_params",
")",
"return",
"event"
] | Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
rules match those for ``Event.add_occurrences``.
Returns the newly created ``Event`` instance.
Parameters
``event_type``
can be either an ``EventType`` object or 2-tuple of ``(abbreviation,label)``,
from which an ``EventType`` is either created or retrieved.
``start_time``
will default to the current hour if ``None``
``end_time``
will default to ``start_time`` plus swingtime_settings.DEFAULT_OCCURRENCE_DURATION
hour if ``None``
``freq``, ``count``, ``rrule_params``
follow the ``dateutils`` API (see http://labix.org/python-dateutil) | [
"Convenience",
"function",
"to",
"create",
"an",
"Event",
"optionally",
"create",
"an",
"EventType",
"and",
"associated",
"Occurrence",
"s",
".",
"Occurrence",
"creation",
"rules",
"match",
"those",
"for",
"Event",
".",
"add_occurrences",
"."
] | d1cdd449bd5c6895c3ff182fd890c4d3452943fe | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L208-L265 | train |
dakrauth/django-swingtime | swingtime/models.py | Event.add_occurrences | def add_occurrences(self, start_time, end_time, **rrule_params):
'''
Add one or more occurences to the event using a comparable API to
``dateutil.rrule``.
If ``rrule_params`` does not contain a ``freq``, one will be defaulted
to ``rrule.DAILY``.
Because ``rrule.rrule`` returns an iterator that can essentially be
unbounded, we need to slightly alter the expected behavior here in order
to enforce a finite number of occurrence creation.
If both ``count`` and ``until`` entries are missing from ``rrule_params``,
only a single ``Occurrence`` instance will be created using the exact
``start_time`` and ``end_time`` values.
'''
count = rrule_params.get('count')
until = rrule_params.get('until')
if not (count or until):
self.occurrence_set.create(start_time=start_time, end_time=end_time)
else:
rrule_params.setdefault('freq', rrule.DAILY)
delta = end_time - start_time
occurrences = []
for ev in rrule.rrule(dtstart=start_time, **rrule_params):
occurrences.append(Occurrence(start_time=ev, end_time=ev + delta, event=self))
self.occurrence_set.bulk_create(occurrences) | python | def add_occurrences(self, start_time, end_time, **rrule_params):
'''
Add one or more occurences to the event using a comparable API to
``dateutil.rrule``.
If ``rrule_params`` does not contain a ``freq``, one will be defaulted
to ``rrule.DAILY``.
Because ``rrule.rrule`` returns an iterator that can essentially be
unbounded, we need to slightly alter the expected behavior here in order
to enforce a finite number of occurrence creation.
If both ``count`` and ``until`` entries are missing from ``rrule_params``,
only a single ``Occurrence`` instance will be created using the exact
``start_time`` and ``end_time`` values.
'''
count = rrule_params.get('count')
until = rrule_params.get('until')
if not (count or until):
self.occurrence_set.create(start_time=start_time, end_time=end_time)
else:
rrule_params.setdefault('freq', rrule.DAILY)
delta = end_time - start_time
occurrences = []
for ev in rrule.rrule(dtstart=start_time, **rrule_params):
occurrences.append(Occurrence(start_time=ev, end_time=ev + delta, event=self))
self.occurrence_set.bulk_create(occurrences) | [
"def",
"add_occurrences",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"*",
"*",
"rrule_params",
")",
":",
"count",
"=",
"rrule_params",
".",
"get",
"(",
"'count'",
")",
"until",
"=",
"rrule_params",
".",
"get",
"(",
"'until'",
")",
"if",
"not",
"(",
"count",
"or",
"until",
")",
":",
"self",
".",
"occurrence_set",
".",
"create",
"(",
"start_time",
"=",
"start_time",
",",
"end_time",
"=",
"end_time",
")",
"else",
":",
"rrule_params",
".",
"setdefault",
"(",
"'freq'",
",",
"rrule",
".",
"DAILY",
")",
"delta",
"=",
"end_time",
"-",
"start_time",
"occurrences",
"=",
"[",
"]",
"for",
"ev",
"in",
"rrule",
".",
"rrule",
"(",
"dtstart",
"=",
"start_time",
",",
"*",
"*",
"rrule_params",
")",
":",
"occurrences",
".",
"append",
"(",
"Occurrence",
"(",
"start_time",
"=",
"ev",
",",
"end_time",
"=",
"ev",
"+",
"delta",
",",
"event",
"=",
"self",
")",
")",
"self",
".",
"occurrence_set",
".",
"bulk_create",
"(",
"occurrences",
")"
] | Add one or more occurences to the event using a comparable API to
``dateutil.rrule``.
If ``rrule_params`` does not contain a ``freq``, one will be defaulted
to ``rrule.DAILY``.
Because ``rrule.rrule`` returns an iterator that can essentially be
unbounded, we need to slightly alter the expected behavior here in order
to enforce a finite number of occurrence creation.
If both ``count`` and ``until`` entries are missing from ``rrule_params``,
only a single ``Occurrence`` instance will be created using the exact
``start_time`` and ``end_time`` values. | [
"Add",
"one",
"or",
"more",
"occurences",
"to",
"the",
"event",
"using",
"a",
"comparable",
"API",
"to",
"dateutil",
".",
"rrule",
"."
] | d1cdd449bd5c6895c3ff182fd890c4d3452943fe | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L84-L110 | train |
dakrauth/django-swingtime | swingtime/models.py | Event.daily_occurrences | def daily_occurrences(self, dt=None):
'''
Convenience method wrapping ``Occurrence.objects.daily_occurrences``.
'''
return Occurrence.objects.daily_occurrences(dt=dt, event=self) | python | def daily_occurrences(self, dt=None):
'''
Convenience method wrapping ``Occurrence.objects.daily_occurrences``.
'''
return Occurrence.objects.daily_occurrences(dt=dt, event=self) | [
"def",
"daily_occurrences",
"(",
"self",
",",
"dt",
"=",
"None",
")",
":",
"return",
"Occurrence",
".",
"objects",
".",
"daily_occurrences",
"(",
"dt",
"=",
"dt",
",",
"event",
"=",
"self",
")"
] | Convenience method wrapping ``Occurrence.objects.daily_occurrences``. | [
"Convenience",
"method",
"wrapping",
"Occurrence",
".",
"objects",
".",
"daily_occurrences",
"."
] | d1cdd449bd5c6895c3ff182fd890c4d3452943fe | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L127-L131 | train |
dakrauth/django-swingtime | swingtime/models.py | OccurrenceManager.daily_occurrences | def daily_occurrences(self, dt=None, event=None):
'''
Returns a queryset of for instances that have any overlap with a
particular day.
* ``dt`` may be either a datetime.datetime, datetime.date object, or
``None``. If ``None``, default to the current day.
* ``event`` can be an ``Event`` instance for further filtering.
'''
dt = dt or datetime.now()
start = datetime(dt.year, dt.month, dt.day)
end = start.replace(hour=23, minute=59, second=59)
qs = self.filter(
models.Q(
start_time__gte=start,
start_time__lte=end,
) |
models.Q(
end_time__gte=start,
end_time__lte=end,
) |
models.Q(
start_time__lt=start,
end_time__gt=end
)
)
return qs.filter(event=event) if event else qs | python | def daily_occurrences(self, dt=None, event=None):
'''
Returns a queryset of for instances that have any overlap with a
particular day.
* ``dt`` may be either a datetime.datetime, datetime.date object, or
``None``. If ``None``, default to the current day.
* ``event`` can be an ``Event`` instance for further filtering.
'''
dt = dt or datetime.now()
start = datetime(dt.year, dt.month, dt.day)
end = start.replace(hour=23, minute=59, second=59)
qs = self.filter(
models.Q(
start_time__gte=start,
start_time__lte=end,
) |
models.Q(
end_time__gte=start,
end_time__lte=end,
) |
models.Q(
start_time__lt=start,
end_time__gt=end
)
)
return qs.filter(event=event) if event else qs | [
"def",
"daily_occurrences",
"(",
"self",
",",
"dt",
"=",
"None",
",",
"event",
"=",
"None",
")",
":",
"dt",
"=",
"dt",
"or",
"datetime",
".",
"now",
"(",
")",
"start",
"=",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
")",
"end",
"=",
"start",
".",
"replace",
"(",
"hour",
"=",
"23",
",",
"minute",
"=",
"59",
",",
"second",
"=",
"59",
")",
"qs",
"=",
"self",
".",
"filter",
"(",
"models",
".",
"Q",
"(",
"start_time__gte",
"=",
"start",
",",
"start_time__lte",
"=",
"end",
",",
")",
"|",
"models",
".",
"Q",
"(",
"end_time__gte",
"=",
"start",
",",
"end_time__lte",
"=",
"end",
",",
")",
"|",
"models",
".",
"Q",
"(",
"start_time__lt",
"=",
"start",
",",
"end_time__gt",
"=",
"end",
")",
")",
"return",
"qs",
".",
"filter",
"(",
"event",
"=",
"event",
")",
"if",
"event",
"else",
"qs"
] | Returns a queryset of for instances that have any overlap with a
particular day.
* ``dt`` may be either a datetime.datetime, datetime.date object, or
``None``. If ``None``, default to the current day.
* ``event`` can be an ``Event`` instance for further filtering. | [
"Returns",
"a",
"queryset",
"of",
"for",
"instances",
"that",
"have",
"any",
"overlap",
"with",
"a",
"particular",
"day",
"."
] | d1cdd449bd5c6895c3ff182fd890c4d3452943fe | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L136-L164 | train |
dakrauth/django-swingtime | swingtime/views.py | event_listing | def event_listing(
request,
template='swingtime/event_list.html',
events=None,
**extra_context
):
'''
View all ``events``.
If ``events`` is a queryset, clone it. If ``None`` default to all ``Event``s.
Context parameters:
``events``
an iterable of ``Event`` objects
... plus all values passed in via **extra_context
'''
events = events or Event.objects.all()
extra_context['events'] = events
return render(request, template, extra_context) | python | def event_listing(
request,
template='swingtime/event_list.html',
events=None,
**extra_context
):
'''
View all ``events``.
If ``events`` is a queryset, clone it. If ``None`` default to all ``Event``s.
Context parameters:
``events``
an iterable of ``Event`` objects
... plus all values passed in via **extra_context
'''
events = events or Event.objects.all()
extra_context['events'] = events
return render(request, template, extra_context) | [
"def",
"event_listing",
"(",
"request",
",",
"template",
"=",
"'swingtime/event_list.html'",
",",
"events",
"=",
"None",
",",
"*",
"*",
"extra_context",
")",
":",
"events",
"=",
"events",
"or",
"Event",
".",
"objects",
".",
"all",
"(",
")",
"extra_context",
"[",
"'events'",
"]",
"=",
"events",
"return",
"render",
"(",
"request",
",",
"template",
",",
"extra_context",
")"
] | View all ``events``.
If ``events`` is a queryset, clone it. If ``None`` default to all ``Event``s.
Context parameters:
``events``
an iterable of ``Event`` objects
... plus all values passed in via **extra_context | [
"View",
"all",
"events",
"."
] | d1cdd449bd5c6895c3ff182fd890c4d3452943fe | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L20-L40 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.