Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def cycle_string(key_arn, source_plaintext, botocore_session=None): # 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 master_key_provider = a...
[ "Encrypts and then decrypts a string under a KMS customer master key (CMK).\n\n :param str key_arn: Amazon Resource Name (ARN) of the KMS CMK\n :param bytes source_plaintext: Data to encrypt\n :param botocore_session: existing botocore session instance\n :type botocore_session: botocore.session.Session\...
Please provide a description of the function: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_fi...
[ "Encrypts and then decrypts a file under a custom static master key provider.\n\n :param str source_plaintext_filename: Filename of file to encrypt\n " ]
Please provide a description of the function: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_algor...
[ "Returns a static, randomly-generated symmetric key for the specified key ID.\n\n :param str key_id: Key ID\n :returns: Wrapping key that contains the specified static key\n :rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`\n " ]
Please provide a description of the function: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() ...
[ "Returns the length of the source stream, determining it if not already known." ]
Please provide a description of the function: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) ...
[ "Returns either the requested number of bytes or the entire stream.\n\n :param int b: Number of bytes to read\n :returns: Processed (encrypted or decrypted) bytes from source stream\n :rtype: bytes\n " ]
Please provide a description of the function: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" ]
Please provide a description of the function: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") ...
[ "Provides hook for Python2 iterator functionality." ]
Please provide a description of the function: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.\n\n :rtype: int\n " ]
Please provide a description of the function:def _prep_message(self): message_id = aws_encryption_sdk.internal.utils.message_id() try: plaintext_length = self.stream_length except NotSupportedError: plaintext_length = None encryption_materials_request = ...
[ "Performs initial message setup.\n\n :raises MasterKeyProviderError: if primary master key is not a member of supplied MasterKeyProvider\n :raises MasterKeyProviderError: if no Master Keys are returned from key_provider\n " ]
Please provide a description of the function: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, ...
[ "Builds the message header and writes it to the output stream." ]
Please provide a description of the function:def _prep_non_framed(self): try: plaintext_length = self.stream_length self.__unframed_plaintext_cache = self.source_stream except NotSupportedError: # We need to know the plaintext length before we can start proce...
[ "Prepare the opening data for a non-framed message." ]
Please provide a description of the function: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: ...
[ "Reads the requested number of bytes from source to a streaming non-framed message body.\n\n :param int b: Number of bytes to read\n :returns: Encrypted bytes from source stream\n :rtype: bytes\n " ]
Please provide a description of the function: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) ...
[ "Reads the requested number of bytes from source to a streaming framed message body.\n\n :param int b: Number of bytes to read\n :returns: Bytes read from source stream, encrypted, and serialized\n :rtype: bytes\n " ]
Please provide a description of the function:def _read_bytes(self, b): _LOGGER.debug("%d bytes requested from stream with content type: %s", b, self.content_type) if 0 <= b <= len(self.output_buffer) or self.__message_complete: _LOGGER.debug("No need to read from source stream or so...
[ "Reads the requested number of bytes from a streaming message body.\n\n :param int b: Number of bytes to read\n :raises NotSupportedError: if content type is not supported\n " ]
Please provide a description of the function:def _prep_message(self): self._header, self.header_auth = self._read_header() if self._header.content_type == ContentType.NO_FRAMING: self._prep_non_framed() self._message_prepped = True
[ "Performs initial message setup." ]
Please provide a description of the function: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.FRA...
[ "Reads the message header from the input stream.\n\n :returns: tuple containing deserialized header and header_auth objects\n :rtype: tuple of aws_encryption_sdk.structures.MessageHeader\n and aws_encryption_sdk.internal.structures.MessageHeaderAuthentication\n :raises CustomMaximumV...
Please provide a description of the function:def _prep_non_framed(self): self._unframed_body_iv, self.body_length = deserialize_non_framed_values( stream=self.source_stream, header=self._header, verifier=self.verifier ) if self.config.max_body_length is not None and self.bo...
[ "Prepare the opening data for a non-framed message." ]
Please provide a description of the function: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...
[ "Reads the requested number of bytes from a streaming non-framed message body.\n\n :param int b: Number of bytes to read\n :returns: Decrypted bytes from source stream\n :rtype: bytes\n " ]
Please provide a description of the function: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, fi...
[ "Reads the requested number of bytes from a streaming framed message body.\n\n :param int b: Number of bytes to read\n :returns: Bytes read from source stream and decrypted\n :rtype: bytes\n " ]
Please provide a description of the function:def _read_bytes(self, b): if hasattr(self, "footer"): _LOGGER.debug("Source stream processing complete") return buffer_length = len(self.output_buffer) if 0 <= b <= buffer_length: _LOGGER.debug("%d bytes r...
[ "Reads the requested number of bytes from a streaming message body.\n\n :param int b: Number of bytes to read\n :raises NotSupportedError: if content type is not supported\n " ]
Please provide a description of the function: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." ]
Please provide a description of the function: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 determinab...
[ "Determine the target region from a key ID, falling back to a default region if provided.\n\n :param str key_id: AWS KMS key ID\n :param str default_region: Region to use if no region found in key_id\n :returns: region name\n :rtype: str\n :raises UnknownRegionError: if no region found in key_id and ...
Please provide a description of the function: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_re...
[ "Traverses the config and adds master keys and regional clients as needed." ]
Please provide a description of the function: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( 'Re...
[ "Proxies all calls to a kms clients methods and removes misbehaving clients\n\n :param str region_name: AWS Region ID (ex: us-east-1)\n :param callable method: a method on the KMS client to proxy\n :param tuple args: list of arguments to pass to the provided ``method``\n :param dict kwar...
Please provide a description of the function: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...
[ "Uses functools.partial to wrap all methods on a client with the self._wrap_client method\n\n :param botocore.client.BaseClient client: the client to proxy\n :param str region_name: AWS Region ID (ex: us-east-1)\n " ]
Please provide a description of the function: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=se...
[ "Adds a regional client for the specified region if it does not already exist.\n\n :param str region_name: AWS Region ID (ex: us-east-1)\n " ]
Please provide a description of the function: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.\n\n :param str key_id: KMS CMK ID\n " ]
Please provide a description of the function: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.\n\n :param bytes key_id: KMS CMK ID\n :returns: KMS Master Key based on key_id\n :rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey\n :raises InvalidKeyIdError: if key_id is not a valid KMS CMK ID to which this key provider has acc...
Please provide a description of the function: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 ...
[ "Generates data key and returns plaintext and ciphertext of key.\n\n :param algorithm: Algorithm on which to base data key\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param dict encryption_context: Encryption context to pass to KMS\n :returns: Generated data key\n ...
Please provide a description of the function: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.co...
[ "Encrypts a data key and returns the ciphertext.\n\n :param data_key: Unencrypted data key\n :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`\n or :class:`aws_encryption_sdk.structures.DataKey`\n :param algorithm: Placeholder to maintain API compatibility with parent...
Please provide a description of the function:def _decrypt_data_key(self, encrypted_data_key, algorithm, encryption_context=None): kms_params = {"CiphertextBlob": encrypted_data_key.encrypted_data_key} if encryption_context: kms_params["EncryptionContext"] = encryption_context ...
[ "Decrypts an encrypted data key and returns the plaintext.\n\n :param data_key: Encrypted data key\n :type data_key: aws_encryption_sdk.structures.EncryptedDataKey\n :type algorithm: `aws_encryption_sdk.identifiers.Algorithm` (not used for KMS)\n :param dict encryption_context: Encryptio...
Please provide a description of the function: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 i...
[ "Serializes an encrypted data key.\n\n .. versionadded:: 1.3.0\n\n :param encrypted_data_key: Encrypted data key to serialize\n :type encrypted_data_key: aws_encryption_sdk.structures.EncryptedDataKey\n :returns: Serialized encrypted data key\n :rtype: bytes\n " ]
Please provide a description of the function: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 ...
[ "Serializes a header object.\n\n :param header: Header to serialize\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param signer: Cryptographic signer object (optional)\n :type signer: aws_encryption_sdk.internal.crypto.Signer\n :returns: Serialized header\n :rtype: bytes\n " ]
Please provide a description of the function: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), ) ...
[ "Creates serialized header authentication data.\n\n :param algorithm: Algorithm to use for encryption\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes header: Serialized message header\n :param bytes data_encryption_key: Data key with which to encrypt message\n :param signer...
Please provide a description of the function: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 ...
[ "Serializes the opening block for a non-framed message body.\n\n :param algorithm: Algorithm to use for encryption\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes iv: IV value used to encrypt body\n :param int plaintext_length: Length of plaintext (and thus ciphertext) in body...
Please provide a description of the function: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.\n\n :param bytes tag: Auth tag value from body encryptor\n :param signer: Cryptographic signer object (optional)\n :type signer: aws_encryption_sdk.internal.crypto.Signer\n :returns: Serialized body close block\n :rtype: bytes\n " ]
Please provide a description of the function: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_num...
[ "Receives a message plaintext, breaks off a frame, encrypts and serializes\n the frame, and returns the encrypted frame and the remaining plaintext.\n\n :param algorithm: Algorithm to use for encryption\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes plaintext: Source plaintex...
Please provide a description of the function: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\n the signature, then serializes that signature.\n\n :param signer: Cryptographic signer object\n :type signer: aws_encryption_sdk.internal.crypto.Signer\n :returns: Serialized footer\n :rtype: bytes\n " ]
Please provide a description of the function: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_...
[ "Produces the prefix that a RawMasterKey will always use for the\n key_info value of keys which require additional information.\n\n :param raw_master_key: RawMasterKey for which to produce a prefix\n :type raw_master_key: aws_encryption_sdk.key_providers.raw.RawMasterKey\n :returns: Serialized key_info ...
Please provide a description of the function: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...
[ "Serializes EncryptedData into a Wrapped EncryptedDataKey.\n\n :param key_provider: Info for Wrapping MasterKey\n :type key_provider: aws_encryption_sdk.structures.MasterKeyInfo\n :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key\n :type wrapping_algorithm: aws_encrypti...
Please provide a description of the function: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_con...
[ "Assembles the Body AAD string for a message body structure.\n\n :param message_id: Message ID\n :type message_id: str\n :param aad_content_string: ContentAADString object for frame type\n :type aad_content_string: aws_encryption_sdk.identifiers.ContentAADString\n :param seq_num: Sequence number of f...
Please provide a description of the function: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: ...
[ "Serializes the contents of a dictionary into a byte string.\n\n :param dict encryption_context: Dictionary of encrytion context keys/values.\n :returns: Serialized encryption context\n :rtype: bytes\n " ]
Please provide a description of the function: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.\n\n :param bytes source: Source byte string\n :param int offset: Point in byte string to start reading\n :returns: Read number and offset at point after read data\n :rtype: tuple of ints\n :raises: SerializationError if unable to unpack\n " ]
Please provide a description of the function: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.\n\n :param bytes source: Source byte string\n :param int offset: Point in byte string to start reading\n :param int length: Length of string to read\n :returns: Read string and offset at point after read data\n :rtype: tuple of str and int\n :raises Serializatio...
Please provide a description of the function: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_con...
[ "Deserializes the contents of a byte string into a dictionary.\n\n :param bytes serialized_encryption_context: Source byte string containing serialized dictionary\n :returns: Deserialized encryption context\n :rtype: dict\n :raises SerializationError: if serialized encryption context is too large\n :...
Please provide a description of the function: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.\n\n :param data_key: Data key to evaluate\n :type data_key: :class:`aws_encryption_sdk.structures.DataKey`,\n :class:`aws_encryption_sdk.structures.RawDataKey`,\n or :class:`aws_encryption_sdk.structures...
Please provide a description of the function:def _generate_data_key(self, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]) -> DataKey: return DataKey( key_provider=self.key_provider, data_key=self._null_plaintext_data_key(algorithm), encrypted_data_key=b"" )
[ ":class:`NullMasterKey` does not support generate_data_key\n\n :param algorithm: Algorithm on which to base data key\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param dict encryption_context: Encryption context to use in encryption\n :raises NotImplementedError: when c...
Please provide a description of the function:def _decrypt_data_key( self, encrypted_data_key: EncryptedDataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text] ) -> DataKey: return DataKey( key_provider=self.key_provider, data_key=self._null_plaintext...
[ "Decrypt an encrypted data key and return the plaintext.\n\n :param data_key: Encrypted data key\n :type data_key: aws_encryption_sdk.structures.EncryptedDataKey\n :param algorithm: Algorithm object which directs how this Master Key will encrypt the data key\n :type algorithm: aws_encryp...
Please provide a description of the function: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_num...
[ "Builds the deterministic IV for a body frame.\n\n :param algorithm: Algorithm for which to build IV\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param int sequence_number: Frame sequence number\n :returns: Generated IV\n :rtype: bytes\n :raises ActionNotAllowedError: if sequence...
Please provide a description of the function: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...
[ "Determine whether a KDFSuite can be used with this EncryptionSuite.\n\n :param kdf: KDFSuite to evaluate\n :type kdf: aws_encryption_sdk.identifiers.KDFSuite\n :rtype: bool\n " ]
Please provide a description of the function: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.algorith...
[ "Calculates the ciphertext message header length, given a complete header.\n\n :param header: Complete message header object\n :type header: aws_encryption_sdk.structures.MessageHeader\n :rtype: int\n " ]
Please provide a description of the function: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 # Authenticatio...
[ "Calculates the length of a non-framed message body, given a complete header.\n\n :param header: Complete message header object\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param int plaintext_length: Length of plaintext in bytes\n :rtype: int\n " ]
Please provide a description of the function: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 fram...
[ "Calculates the length of a standard ciphertext frame, given a complete header.\n\n :param header: Complete message header object\n :type header: aws_encryption_sdk.structures.MessageHeader\n :rtype: int\n " ]
Please provide a description of the function: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...
[ "Calculates the length of a final ciphertext frame, given a complete header\n and the number of bytes of ciphertext in the final frame.\n\n :param header: Complete message header object\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param int final_frame_bytes: Bytes of ciphertext in the...
Please provide a description of the function: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...
[ "Calculates the ciphertext message body length, given a complete header.\n\n :param header: Complete message header object\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param int plaintext_length: Length of plaintext in bytes\n :rtype: int\n " ]
Please provide a description of the function: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.\n\n :param header: Complete message header object\n :type header: aws_encryption_sdk.structures.MessageHeader\n :rtype: int\n " ]
Please provide a description of the function: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.\n\n :param header: Complete message header object\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param int plaintext_length: Length of plaintext in bytes\n :rtype: int\n " ]
Please provide a description of the function: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 ): ...
[ "Determines if data_key object is owned by this RawMasterKey.\n\n :param data_key: Data key to evaluate\n :type data_key: :class:`aws_encryption_sdk.structures.DataKey`,\n :class:`aws_encryption_sdk.structures.RawDataKey`,\n or :class:`aws_encryption_sdk.structures.EncryptedDataK...
Please provide a description of the function:def _generate_data_key(self, algorithm, encryption_context): plaintext_data_key = os.urandom(algorithm.kdf_input_len) encrypted_data_key = self._encrypt_data_key( data_key=RawDataKey(key_provider=self.key_provider, data_key=plaintext_data...
[ "Generates data key and returns :class:`aws_encryption_sdk.structures.DataKey`.\n\n :param algorithm: Algorithm on which to base data key\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param dict encryption_context: Encryption context to use in encryption\n :returns: Gene...
Please provide a description of the function: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 ...
[ "Performs the provider-specific key encryption actions.\n\n :param data_key: Unencrypted data key\n :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`\n or :class:`aws_encryption_sdk.structures.DataKey`\n :param algorithm: Algorithm object which directs how this Master...
Please provide a description of the function:def _decrypt_data_key(self, encrypted_data_key, algorithm, encryption_context): # Wrapped EncryptedDataKey to deserialized EncryptedData encrypted_wrapped_key = aws_encryption_sdk.internal.formatting.deserialize.deserialize_wrapped_key( w...
[ "Decrypts an encrypted data key and returns the plaintext.\n\n :param data_key: Encrypted data key\n :type data_key: aws_encryption_sdk.structures.EncryptedDataKey\n :param algorithm: Algorithm object which directs how this Master Key will encrypt the data key\n :type algorithm: aws_encr...
Please provide a description of the function:def encrypt_with_caching(kms_cmk_arn, max_age_in_cache, cache_capacity): # Data to be encrypted my_data = "My plaintext data" # Security thresholds # Max messages (or max bytes per) data key are optional MAX_ENTRY_MESSAGES = 100 # Create an e...
[ "Encrypts a string using an AWS KMS customer master key (CMK) and data key caching.\n\n :param str kms_cmk_arn: Amazon Resource Name (ARN) of the KMS customer master key\n :param float max_age_in_cache: Maximum time in seconds that a cached entry can be used\n :param int cache_capacity: Maximum number of e...
Please provide a description of the function: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.\n\n :param bytes cache_key: Identifier for entries in cache\n :param encryption_materials: Encryption materials to add to cache\n :type encryption_materials: aws_encryption_sdk.materials_managers.Encry...
Please provide a description of the function:def get_version(): release = get_release() split_version = release.split(".") if len(split_version) == 3: return ".".join(split_version[:2]) return release
[ "Reads the version (MAJOR.MINOR) from this module." ]
Please provide a description of the function:def _set_signature_type(self): try: verify_interface(ec.EllipticCurve, self.algorithm.signing_algorithm_info) return ec.EllipticCurve except InterfaceNotImplemented: raise NotSupportedError("Unsupported signing alg...
[ "Ensures that the algorithm signature type is a known type and sets a reference value." ]
Please provide a description of the function: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.\n\n :param algorithm: Algorithm on which to base signer\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes key_bytes: Raw signing key\n :rtype: aws_encryption_sdk.internal.crypto.Signer\n " ]
Please provide a description of the function: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.\n\n :rtype: bytes\n " ]
Please provide a description of the function: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.\n\n :returns: Calculated signer signature\n :rtype: bytes\n " ]
Please provide a description of the function: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...
[ "Creates a Verifier object based on the supplied algorithm and encoded compressed ECC curve point.\n\n :param algorithm: Algorithm on which to base verifier\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes encoded_point: ECC public point compressed and encoded with _ec...
Please provide a description of the function: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.\n\n :param algorithm: Algorithm on which to base verifier\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes encoded_point: Raw verification key\n :returns: Instance of Verifier...
Please provide a description of the function:def key_bytes(self): return self.key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo )
[ "Returns the raw verification key.\n\n :rtype: bytes\n " ]
Please provide a description of the function: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.\n\n :param bytes signature: The signature to verify\n " ]
Please provide a description of the function: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_...
[ "Encrypts a data key using a direct wrapping key.\n\n :param bytes plaintext_data_key: Data key to encrypt\n :param dict encryption_context: Encryption context to use in encryption\n :returns: Deserialized object containing encrypted key\n :rtype: aws_encryption_sdk.internal.structures.E...
Please provide a description of the function: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: ...
[ "Decrypts a wrapped, encrypted, data key.\n\n :param encrypted_wrapped_data_key: Encrypted, wrapped, data key\n :type encrypted_wrapped_data_key: aws_encryption_sdk.internal.structures.EncryptedData\n :param dict encryption_context: Encryption context to use in decryption\n :returns: Pla...
Please provide a description of the function: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_...
[ "Perform the provider-specific data key generation task.\n\n :param algorithm: Algorithm on which to base data key\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param dict encryption_context: Encryption context to use in encryption\n :returns: Generated data key\n ...
Please provide a description of the function: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.\n\n :param data_key: Unencrypted data key\n :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`\n or :class:`aws_encryption_sdk.structures.DataKey`\n :param algorithm: Algorithm object which directs how this Master Key will...
Please provide a description of the function:def _decrypt_data_key( self, encrypted_data_key: EncryptedDataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text] ) -> DataKey: if encrypted_data_key.encrypted_data_key != self._encrypted_data_key: raise DecryptKeyErr...
[ "Decrypt an encrypted data key and return the plaintext.\n\n :param data_key: Encrypted data key\n :type data_key: aws_encryption_sdk.structures.EncryptedDataKey\n :param algorithm: Algorithm object which directs how this Master Key will encrypt the data key\n :type algorithm: aws_encryp...
Please provide a description of the function: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"", head...
[ "Validates the header using the header authentication data.\n\n :param header: Deserialized header\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param header_auth: Deserialized header auth\n :type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication\n :type...
Please provide a description of the function:def _verified_version_from_id(version_id): # type: (int) -> SerializationVersion try: return SerializationVersion(version_id) except ValueError as error: raise NotSupportedError("Unsupported version {}".format(version_id), error)
[ "Load a message :class:`SerializationVersion` for the specified version ID.\n\n :param int version_id: Message format version ID\n :return: Message format version\n :rtype: SerializationVersion\n :raises NotSupportedError: if unsupported version ID is received\n " ]
Please provide a description of the function:def _verified_message_type_from_id(message_type_id): # type: (int) -> ObjectType try: return ObjectType(message_type_id) except ValueError as error: raise NotSupportedError("Unsupported type {} discovered in data stream".format(message_type_i...
[ "Load a message :class:`ObjectType` for the specified message type ID.\n\n :param int message_type_id: Message type ID\n :return: Message type\n :rtype: ObjectType\n :raises NotSupportedError: if unsupported message type ID is received\n " ]
Please provide a description of the function:def _verified_algorithm_from_id(algorithm_id): # type: (int) -> AlgorithmSuite try: algorithm_suite = AlgorithmSuite.get_by_id(algorithm_id) except KeyError as error: raise UnknownIdentityError("Unknown algorithm {}".format(algorithm_id), err...
[ "Load a message :class:`AlgorithmSuite` for the specified algorithm suite ID.\n\n :param int algorithm_id: Algorithm suite ID\n :return: Algorithm suite\n :rtype: AlgorithmSuite\n :raises UnknownIdentityError: if unknown algorithm ID is received\n :raises NotSupportedError: if unsupported algorithm I...
Please provide a description of the function: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_...
[ "Deserialize some encrypted data keys from a stream.\n\n :param stream: Stream from which to read encrypted data keys\n :return: Loaded encrypted data keys\n :rtype: set of :class:`EncryptedDataKey`\n " ]
Please provide a description of the function:def _verified_content_type_from_id(content_type_id): # type: (int) -> ContentType try: return ContentType(content_type_id) except ValueError as error: raise UnknownIdentityError("Unknown content type {}".format(content_type_id), error)
[ "Load a message :class:`ContentType` for the specified content type ID.\n\n :param int content_type_id: Content type ID\n :return: Message content type\n :rtype: ContentType\n :raises UnknownIdentityError: if unknown content type ID is received\n " ]
Please provide a description of the function: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})".form...
[ "Verify an IV length for an algorithm suite.\n\n :param int iv_length: IV length to verify\n :param AlgorithmSuite algorithm_suite: Algorithm suite to verify against\n :return: IV length\n :rtype: int\n :raises SerializationError: if IV length does not match algorithm suite\n " ]
Please provide a description of the function: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 maxi...
[ "Verify a frame length value for a message content type.\n\n :param int frame_length: Frame length to verify\n :param ContentType content_type: Message content type to verify against\n :return: frame length\n :rtype: int\n :raises SerializationError: if frame length is too large\n :raises Serializ...
Please provide a description of the function: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() ...
[ "Deserializes the header from a source stream\n\n :param stream: Source data stream\n :type stream: io.BytesIO\n :returns: Deserialized MessageHeader object\n :rtype: :class:`aws_encryption_sdk.structures.MessageHeader` and bytes\n :raises NotSupportedError: if unsupported data types are found\n :...
Please provide a description of the function: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_...
[ "Deserializes a MessageHeaderAuthentication object from a source stream.\n\n :param stream: Source data stream\n :type stream: io.BytesIO\n :param algorithm: The AlgorithmSuite object type contained in the header\n :type algorith: aws_encryption_sdk.identifiers.AlgorithmSuite\n :param verifier: Signa...
Please provide a description of the function: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.\n\n :param stream: Source data stream\n :type stream: io.BytesIO\n :param header: Deserialized header\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param verifier: Signature verifier object (optional)\n :type verifier:...
Please provide a description of the function: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.\n\n :param stream: Source data stream\n :type stream: io.BytesIO\n :param header: Deserialized header\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param verifier: Signature verifier object (optional)\n :type verifier: aws_encry...
Please provide a description of the function: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_NUM...
[ "Deserializes a frame from a body.\n\n :param stream: Source data stream\n :type stream: io.BytesIO\n :param header: Deserialized header\n :type header: aws_encryption_sdk.structures.MessageHeader\n :param verifier: Signature verifier object (optional)\n :type verifier: aws_encryption_sdk.internal...
Please provide a description of the function: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) (signatur...
[ "Deserializes a footer.\n\n :param stream: Source data stream\n :type stream: io.BytesIO\n :param verifier: Signature verifier object (optional)\n :type verifier: aws_encryption_sdk.internal.crypto.Verifier\n :returns: Deserialized footer\n :rtype: aws_encryption_sdk.internal.structures.MessageFoo...
Please provide a description of the function:def unpack_values(format_string, stream, verifier=None): try: message_bytes = stream.read(struct.calcsize(format_string)) if verifier: verifier.update(message_bytes) values = struct.unpack(format_string, message_bytes) except ...
[ "Helper function to unpack struct data from a stream and update the signature verifier.\n\n :param str format_string: Struct format string\n :param stream: Source data stream\n :type stream: io.BytesIO\n :param verifier: Signature verifier object\n :type verifier: aws_encryption_sdk.internal.crypto.V...
Please provide a description of the function: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, ta...
[ "Extracts and deserializes EncryptedData from a Wrapped EncryptedDataKey.\n\n :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key\n :type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm\n :param bytes wrapping_key_id: Key ID of wrapping MasterKey\n :p...
Please provide a description of the function: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 algori...
[ "Validates that frame length is within the defined limits and is compatible with the selected algorithm.\n\n :param int frame_length: Frame size in bytes\n :param algorithm: Algorithm to use for encryption\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :raises SerializationError: if frame...
Please provide a description of the function: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_conte...
[ "Prepares the appropriate Body AAD Value for a message body.\n\n :param content_type: Defines the type of content for which to prepare AAD String\n :type content_type: aws_encryption_sdk.identifiers.ContentType\n :param bool is_final_frame: Boolean stating whether this is the final frame in a body\n :re...
Please provide a description of the function: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.debu...
[ "Prepares a DataKey to be used for encrypting message and list\n of EncryptedDataKey objects to be serialized into header.\n\n :param primary_master_key: Master key with which to generate the encryption data key\n :type primary_master_key: aws_encryption_sdk.key_providers.base.MasterKey\n :param master_...
Please provide a description of the function: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.\n\n :param data: Input data\n :returns: Prepared stream\n :rtype: InsistentReaderBytesIO\n " ]
Please provide a description of the function: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( ...
[ "Validates that the supplied source_data_key's data_key is the\n correct length for the supplied algorithm's kdf_input_len value.\n\n :param source_data_key: Source data key object received from MasterKey decrypt or generate data_key methods\n :type source_data_key: :class:`aws_encryption_sdk.structures.Ra...
Please provide a description of the function: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.\n\n :param algorithm: Algorithm used to encrypt this body\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes key: Encryption key\n :param bytes plaintext: Body plaintext\n :param bytes associated_data: Body AAD Data\n :param bytes iv: IV to use when ...
Please provide a description of the function: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.\n\n :param algorithm: Algorithm used to encrypt this body\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes key: Plaintext data key\n :param encrypted_data: EncryptedData containing body data\n :type encrypted_data: :class:`aws_encryption_sdk.internal....