idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
247,300
def remove_unused_resources ( issues , app_dir , ignore_layouts ) : for issue in issues : filepath = os . path . join ( app_dir , issue . filepath ) if issue . remove_file : remove_resource_file ( issue , filepath , ignore_layouts ) else : remove_resource_value ( issue , filepath )
Remove the file or the value inside the file depending if the whole file is unused or not .
79
19
247,301
def _encryption_context_hash ( hasher , encryption_context ) : serialized_encryption_context = serialize_encryption_context ( encryption_context ) hasher . update ( serialized_encryption_context ) return hasher . finalize ( )
Generates the expected hash for the provided encryption context .
58
11
247,302
def build_encryption_materials_cache_key ( partition , request ) : if request . algorithm is None : _algorithm_info = b"\x00" else : _algorithm_info = b"\x01" + request . algorithm . id_as_bytes ( ) hasher = _new_cache_key_hasher ( ) _partition_hash = _partition_name_hash ( hasher = hasher . copy ( ) , partition_name = partition ) _ec_hash = _encryption_context_hash ( hasher = hasher . copy ( ) , encryption_context = request . encryption_context ) hasher . update ( _partition_hash ) hasher . update ( _algorithm_info ) hasher . update ( _ec_hash ) return hasher . finalize ( )
Generates a cache key for an encrypt request .
180
10
247,303
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 .
107
12
247,304
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 .
215
10
247,305
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 .
422
17
247,306
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 .
121
15
247,307
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 .
108
14
247,308
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 .
221
12
247,309
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
56
6
247,310
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 .
73
9
247,311
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 .
45
12
247,312
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 .
94
13
247,313
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 .
284
18
247,314
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 .
542
16
247,315
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 .
420
10
247,316
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 .
408
16
247,317
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 .
412
14
247,318
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 .
56
6
247,319
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 .
92
19
247,320
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 .
173
15
247,321
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
104
17
247,322
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
74
23
247,323
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 .
116
15
247,324
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 .
61
13
247,325
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 .
73
13
247,326
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 .
291
14
247,327
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 .
270
12
247,328
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 .
290
7
247,329
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 .
397
6
247,330
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 .
142
8
247,331
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 .
106
13
247,332
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 .
66
13
247,333
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 .
557
29
247,334
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 .
73
24
247,335
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 .
169
25
247,336
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 .
261
14
247,337
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 .
122
14
247,338
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 .
418
12
247,339
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 .
68
9
247,340
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 .
71
9
247,341
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 .
376
13
247,342
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 .
42
16
247,343
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 .
115
11
247,344
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 .
75
19
247,345
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 .
85
14
247,346
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 .
72
17
247,347
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 .
63
16
247,348
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 .
102
28
247,349
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 .
124
14
247,350
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 .
58
15
247,351
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 .
58
14
247,352
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 .
306
16
247,353
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 .
161
10
247,354
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 .
54
19
247,355
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 .
65
18
247,356
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 .
57
15
247,357
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 .
55
6
247,358
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 .
57
10
247,359
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 .
88
19
247,360
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 .
54
16
247,361
def key_bytes ( self ) : return self . key . public_bytes ( encoding = serialization . Encoding . DER , format = serialization . PublicFormat . SubjectPublicKeyInfo )
Returns the raw verification key .
41
6
247,362
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 .
74
12
247,363
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 .
252
12
247,364
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 .
180
9
247,365
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 .
116
11
247,366
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 .
63
11
247,367
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 .
96
10
247,368
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 .
306
11
247,369
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 .
90
10
247,370
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 .
138
12
247,371
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
473
9
247,372
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 .
98
14
247,373
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 .
90
15
247,374
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 .
72
13
247,375
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 .
421
9
247,376
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 .
143
7
247,377
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 .
405
19
247,378
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 .
161
18
247,379
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 .
143
13
247,380
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 .
295
27
247,381
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 .
60
12
247,382
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 .
95
31
247,383
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 .
71
7
247,384
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 .
64
7
247,385
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 .
83
8
247,386
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 .
254
10
247,387
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 .
35
12
247,388
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 .
100
22
247,389
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 .
252
18
247,390
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 .
88
7
247,391
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 .
116
11
247,392
def encrypt ( * * kwargs ) : with StreamEncryptor ( * * kwargs ) as encryptor : ciphertext = encryptor . read ( ) return ciphertext , encryptor . header
Encrypts and serializes provided plaintext .
43
10
247,393
def decrypt ( * * kwargs ) : with StreamDecryptor ( * * kwargs ) as decryptor : plaintext = decryptor . read ( ) return plaintext , decryptor . header
Deserializes and decrypts provided ciphertext .
43
10
247,394
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 .
188
15
247,395
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 .
77
28
247,396
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 .
96
23
247,397
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 .
211
34
247,398
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 .
180
21
247,399
def daily_occurrences ( self , dt = None ) : return Occurrence . objects . daily_occurrences ( dt = dt , event = self )
Convenience method wrapping Occurrence . objects . daily_occurrences .
37
16