idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
248,300
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_ke...
Generates the expected hash for the provided encrypted data keys .
248,301
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...
Generates a cache key for a decrypt request .
248,302
def cycle_file ( source_plaintext_filename ) : 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" with open...
Encrypts and then decrypts a file under a custom static master key provider .
248,303
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...
Returns a static randomly - generated symmetric key for the specified key ID .
248,304
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 : raise NotSupportedError ...
Returns the length of the source stream determining it if not already known .
248,305
def read ( self , b = - 1 ) : 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 ) ...
Returns either the requested number of bytes or the entire stream .
248,306
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
248,307
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 .
248,308
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 .
248,309
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...
Builds the message header and writes it to the output stream .
248,310
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"...
Reads the requested number of bytes from source to a streaming non - framed message body .
248,311
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 ...
Reads the requested number of bytes from source to a streaming framed message body .
248,312
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 C...
Reads the message header from the input stream .
248,313
def _read_bytes_from_non_framed_body ( self , b ) : _LOGGER . debug ( "starting non-framed body read" ) 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 ( cip...
Reads the requested number of bytes from a streaming non - framed message body .
248,314
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 ,...
Reads the requested number of bytes from a streaming framed message body .
248,315
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 .
248,316
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 regi...
Determine the target region from a key ID falling back to a default region if provided .
248,317
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_...
Traverses the config and adds master keys and regional clients as needed .
248,318
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 , me...
Proxies all calls to a kms clients methods and removes misbehaving clients
248,319
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
248,320
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_clien...
Adds a regional client for the specified region if it does not already exist .
248,321
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 .
248,322
def _new_master_key ( self , key_id ) : _key_id = to_str ( key_id ) return KMSMasterKey ( config = KMSMasterKeyConfig ( key_id = key_id , client = self . _client ( _key_id ) ) )
Returns a KMSMasterKey for the specified key_id .
248,323
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" ] = s...
Generates data key and returns plaintext and ciphertext of key .
248,324
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...
Encrypts a data key and returns the ciphertext .
248,325
def serialize_encrypted_data_key ( encrypted_data_key ) : encrypted_data_key_format = ( ">" "H" "{provider_id_len}s" "H" "{provider_info_len}s" "H" "{enc_data_key_len}s" ) return struct . pack ( encrypted_data_key_format . format ( provider_id_len = len ( encrypted_data_key . key_provider . provider_id ) , provider_inf...
Serializes an encrypted data key .
248,326
def serialize_header ( header , signer = None ) : ec_serialized = aws_encryption_sdk . internal . formatting . encryption_context . serialize_encryption_context ( header . encryption_context ) header_start_format = ( ">" "B" "B" "H" "16s" "H" "{}s" ) . format ( len ( ec_serialized ) ) header_bytes = bytearray ( ) heade...
Serializes a header object .
248,327
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 = algo...
Creates serialized header authentication data .
248,328
def serialize_non_framed_open ( algorithm , iv , plaintext_length , signer = None ) : body_start_format = ( ">" "{iv_length}s" "Q" ) . format ( iv_length = algorithm . iv_len ) 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 .
248,329
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 .
248,330
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_FR...
Receives a message plaintext breaks off a frame encrypts and serializes the frame and returns the encrypted frame and the remaining plaintext .
248,331
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 .
248,332
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 ...
Produces the prefix that a RawMasterKey will always use for the key_info value of keys which require additional information .
248,333
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 ( w...
Serializes EncryptedData into a Wrapped EncryptedDataKey .
248,334
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 . p...
Assembles the Body AAD string for a message body structure .
248,335
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...
Serializes the contents of a dictionary into a byte string .
248,336
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 .
248,337
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 .
248,338
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 con...
Deserializes the contents of a byte string into a dictionary .
248,339
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 .
248,340
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...
Builds the deterministic IV for a body frame .
248,341
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 .
248,342
def header_length ( header ) : header_length = len ( serialize_header ( header ) ) header_length += header . algorithm . iv_len header_length += header . algorithm . auth_len return header_length
Calculates the ciphertext message header length given a complete header .
248,343
def _non_framed_body_length ( header , plaintext_length ) : body_length = header . algorithm . iv_len body_length += 8 body_length += plaintext_length body_length += header . algorithm . auth_len return body_length
Calculates the length of a non - framed message body given a complete header .
248,344
def _standard_frame_length ( header ) : frame_length = 4 frame_length += header . algorithm . iv_len frame_length += header . frame_length frame_length += header . algorithm . auth_len return frame_length
Calculates the length of a standard ciphertext frame given a complete header .
248,345
def _final_frame_length ( header , final_frame_bytes ) : final_frame_length = 4 final_frame_length += 4 final_frame_length += header . algorithm . iv_len final_frame_length += 4 final_frame_length += final_frame_bytes final_frame_length += header . algorithm . auth_len 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 .
248,346
def body_length ( header , plaintext_length ) : body_length = 0 if header . frame_length == 0 : body_length += _non_framed_body_length ( header , plaintext_length ) else : frames , final_frame_bytes = divmod ( plaintext_length , header . frame_length ) body_length += frames * _standard_frame_length ( header ) body_leng...
Calculates the ciphertext message body length given a complete header .
248,347
def footer_length ( header ) : footer_length = 0 if header . algorithm . signing_algorithm_info is not None : footer_length += 2 footer_length += header . algorithm . signature_len return footer_length
Calculates the ciphertext message footer length given a complete header .
248,348
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 .
248,349
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 Encry...
Determines if data_key object is owned by this RawMasterKey .
248,350
def _encrypt_data_key ( self , data_key , algorithm , encryption_context ) : encrypted_wrapped_key = self . config . wrapping_key . encrypt ( plaintext_data_key = data_key . data_key , encryption_context = encryption_context ) return aws_encryption_sdk . internal . formatting . serialize . serialize_wrapped_key ( key_p...
Performs the provider - specific key encryption actions .
248,351
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 .
248,352
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 .
248,353
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 .
248,354
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 .
248,355
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 .
248,356
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 .
248,357
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 .
248,358
def key_bytes ( self ) : return self . key . public_bytes ( encoding = serialization . Encoding . DER , format = serialization . PublicFormat . SubjectPublicKeyInfo )
Returns the raw verification key .
248,359
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 .
248,360
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 ...
Encrypts a data key using a direct wrapping key .
248,361
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_w...
Decrypts a wrapped encrypted data key .
248,362
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_dat...
Perform the provider - specific data key generation task .
248,363
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 .
248,364
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 : r...
Validates the header using the header authentication data .
248,365
def _deserialize_encrypted_data_keys ( stream ) : ( 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 (...
Deserialize some encrypted data keys from a stream .
248,366
def _verified_iv_length ( iv_length , algorithm_suite ) : if iv_length != algorithm_suite . iv_len : raise SerializationError ( "Specified IV length ({length}) does not match algorithm IV length ({algorithm})" . format ( length = iv_length , algorithm = algorithm_suite ) ) return iv_length
Verify an IV length for an algorithm suite .
248,367
def _verified_frame_length ( frame_length , content_type ) : if content_type == ContentType . FRAMED_DATA and frame_length > MAX_FRAME_SIZE : raise SerializationError ( "Specified frame length larger than allowed maximum: {found} > {max}" . format ( found = frame_length , max = MAX_FRAME_SIZE ) ) if content_type == Con...
Verify a frame length value for a message content type .
248,368
def deserialize_header ( stream ) : _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" ]...
Deserializes the header from a source stream
248,369
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 ...
Deserializes a MessageHeaderAuthentication object from a source stream .
248,370
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 .
248,371
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 .
248,372
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 ( "Deseriali...
Deserializes a frame from a body .
248,373
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_...
Deserializes a footer .
248,374
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_encrypte...
Extracts and deserializes EncryptedData from a Wrapped EncryptedDataKey .
248,375
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 . encrypti...
Validates that frame length is within the defined limits and is compatible with the selected algorithm .
248,376
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_...
Prepares the appropriate Body AAD Value for a message body .
248,377
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: %...
Prepares a DataKey to be used for encrypting message and list of EncryptedDataKey objects to be serialized into header .
248,378
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 .
248,379
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 ....
Validates that the supplied source_data_key s data_key is the correct length for the supplied algorithm s kdf_input_len value .
248,380
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 .
248,381
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 .
248,382
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 .
248,383
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_encrypt...
Basic decrypt handler for decrypt oracle v0 .
248,384
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 .
248,385
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...
Keep reading from source stream until either the source stream is done or the requested number of bytes have been obtained .
248,386
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...
Calculates an elliptic curve signature with a static length using pre - calculated hash .
248,387
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 sign...
Returns an ECC signing key .
248,388
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_i...
Derives the data encryption key using the defined algorithm .
248,389
def encrypt ( ** kwargs ) : with StreamEncryptor ( ** kwargs ) as encryptor : ciphertext = encryptor . read ( ) return ciphertext , encryptor . header
Encrypts and serializes provided plaintext .
248,390
def decrypt ( ** kwargs ) : with StreamDecryptor ( ** kwargs ) as decryptor : plaintext = decryptor . read ( ) return plaintext , decryptor . header
Deserializes and decrypts provided ciphertext .
248,391
def cycle_file ( key_arn , source_plaintext_filename , botocore_session = None ) : ciphertext_filename = source_plaintext_filename + ".encrypted" cycled_kms_plaintext_filename = source_plaintext_filename + ".kms.decrypted" cycled_static_plaintext_filename = source_plaintext_filename + ".static.decrypted" kms_kwargs = d...
Encrypts and then decrypts a file using a KMS master key provider and a custom static master key provider . Both master key providers are used to encrypt the plaintext file so either one alone can decrypt it .
248,392
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 = ...
Retrieves a static randomly generated RSA key for the specified key id .
248,393
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 .
248,394
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 .
248,395
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 ( t...
Convenience function to create an Event optionally create an EventType and associated Occurrence s . Occurrence creation rules match those for Event . add_occurrences .
248,396
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 ) ...
Add one or more occurences to the event using a comparable API to dateutil . rrule .
248,397
def daily_occurrences ( self , dt = None ) : return Occurrence . objects . daily_occurrences ( dt = dt , event = self )
Convenience method wrapping Occurrence . objects . daily_occurrences .
248,398
def daily_occurrences ( self , dt = None , event = None ) : dt = dt or datetime . now ( ) start = datetime ( dt . year , dt . month , dt . day ) end = start . replace ( hour = 23 , minute = 59 , second = 59 ) qs = self . filter ( models . Q ( start_time__gte = start , start_time__lte = end , ) | models . Q ( end_time__...
Returns a queryset of for instances that have any overlap with a particular day .
248,399
def event_listing ( request , template = 'swingtime/event_list.html' , events = None , ** extra_context ) : events = events or Event . objects . all ( ) extra_context [ 'events' ] = events return render ( request , template , extra_context )
View all events .