_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q270500
Boolean.write
test
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the encoding of the Boolean object to the output stream. Args: ostream (Stream): A buffer to contain the encoded bytes of a Boolean object. Usually a BytearrayStream object. Required. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ super(Boolean, self).write(ostream, kmip_version=kmip_version) self.write_value(ostream, kmip_version=kmip_version)
python
{ "resource": "" }
q270501
Boolean.validate
test
def validate(self): """ Verify that the value of the Boolean object is valid. Raises: TypeError: if the value is not of type bool. """ if self.value: if not isinstance(self.value, bool): raise TypeError("expected: {0}, observed: {1}".format( bool, type(self.value)))
python
{ "resource": "" }
q270502
Interval.read
test
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the encoding of the Interval from the input stream. Args: istream (stream): A buffer containing the encoded bytes of the value of an Interval. Usually a BytearrayStream object. Required. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: InvalidPrimitiveLength: if the Interval encoding read in has an invalid encoded length. InvalidPaddingBytes: if the Interval encoding read in does not use zeroes for its padding bytes. """ super(Interval, self).read(istream, kmip_version=kmip_version) # Check for a valid length before even trying to parse the value. if self.length != Interval.LENGTH: raise exceptions.InvalidPrimitiveLength( "interval length must be {0}".format(Interval.LENGTH)) # Decode the Interval value and the padding bytes. self.value = unpack('!I', istream.read(Interval.LENGTH))[0] pad = unpack('!I', istream.read(Interval.LENGTH))[0] # Verify that the padding bytes are zero bytes. if pad != 0: raise exceptions.InvalidPaddingBytes("padding bytes must be zero") self.validate()
python
{ "resource": "" }
q270503
Interval.validate
test
def validate(self): """ Verify that the value of the Interval is valid. Raises: TypeError: if the value is not of type int or long ValueError: if the value cannot be represented by an unsigned 32-bit integer """ if self.value is not None: if type(self.value) not in six.integer_types: raise TypeError('expected (one of): {0}, observed: {1}'.format( six.integer_types, type(self.value))) else: if self.value > Interval.MAX: raise ValueError( 'interval value greater than accepted max') elif self.value < Interval.MIN: raise ValueError('interval value less than accepted min')
python
{ "resource": "" }
q270504
Key.key_wrapping_data
test
def key_wrapping_data(self): """ Retrieve all of the relevant key wrapping data fields and return them as a dictionary. """ key_wrapping_data = {} encryption_key_info = { 'unique_identifier': self._kdw_eki_unique_identifier, 'cryptographic_parameters': { 'block_cipher_mode': self._kdw_eki_cp_block_cipher_mode, 'padding_method': self._kdw_eki_cp_padding_method, 'hashing_algorithm': self._kdw_eki_cp_hashing_algorithm, 'key_role_type': self._kdw_eki_cp_key_role_type, 'digital_signature_algorithm': self._kdw_eki_cp_digital_signature_algorithm, 'cryptographic_algorithm': self._kdw_eki_cp_cryptographic_algorithm, 'random_iv': self._kdw_eki_cp_random_iv, 'iv_length': self._kdw_eki_cp_iv_length, 'tag_length': self._kdw_eki_cp_tag_length, 'fixed_field_length': self._kdw_eki_cp_fixed_field_length, 'invocation_field_length': self._kdw_eki_cp_invocation_field_length, 'counter_length': self._kdw_eki_cp_counter_length, 'initial_counter_value': self._kdw_eki_cp_initial_counter_value } } if not any(encryption_key_info['cryptographic_parameters'].values()): encryption_key_info['cryptographic_parameters'] = {} if not any(encryption_key_info.values()): encryption_key_info = {} mac_sign_key_info = { 'unique_identifier': self._kdw_mski_unique_identifier, 'cryptographic_parameters': { 'block_cipher_mode': self._kdw_mski_cp_block_cipher_mode, 'padding_method': self._kdw_mski_cp_padding_method, 'hashing_algorithm': self._kdw_mski_cp_hashing_algorithm, 'key_role_type': self._kdw_mski_cp_key_role_type, 'digital_signature_algorithm': self._kdw_mski_cp_digital_signature_algorithm, 'cryptographic_algorithm': self._kdw_mski_cp_cryptographic_algorithm, 'random_iv': self._kdw_mski_cp_random_iv, 'iv_length': self._kdw_mski_cp_iv_length, 'tag_length': self._kdw_mski_cp_tag_length, 'fixed_field_length': self._kdw_mski_cp_fixed_field_length, 'invocation_field_length': self._kdw_mski_cp_invocation_field_length, 'counter_length': self._kdw_mski_cp_counter_length, 'initial_counter_value': self._kdw_mski_cp_initial_counter_value } } if not any(mac_sign_key_info['cryptographic_parameters'].values()): mac_sign_key_info['cryptographic_parameters'] = {} if not any(mac_sign_key_info.values()): mac_sign_key_info = {} key_wrapping_data['wrapping_method'] = self._kdw_wrapping_method key_wrapping_data['encryption_key_information'] = encryption_key_info key_wrapping_data['mac_signature_key_information'] = mac_sign_key_info key_wrapping_data['mac_signature'] = self._kdw_mac_signature key_wrapping_data['iv_counter_nonce'] = self._kdw_iv_counter_nonce key_wrapping_data['encoding_option'] = self._kdw_encoding_option if not any(key_wrapping_data.values()): key_wrapping_data = {} return key_wrapping_data
python
{ "resource": "" }
q270505
Key.key_wrapping_data
test
def key_wrapping_data(self, value): """ Set the key wrapping data attributes using a dictionary. """ if value is None: value = {} elif not isinstance(value, dict): raise TypeError("Key wrapping data must be a dictionary.") self._kdw_wrapping_method = value.get('wrapping_method') eki = value.get('encryption_key_information') if eki is None: eki = {} self._kdw_eki_unique_identifier = eki.get('unique_identifier') eki_cp = eki.get('cryptographic_parameters') if eki_cp is None: eki_cp = {} self._kdw_eki_cp_block_cipher_mode = eki_cp.get('block_cipher_mode') self._kdw_eki_cp_padding_method = eki_cp.get('padding_method') self._kdw_eki_cp_hashing_algorithm = eki_cp.get('hashing_algorithm') self._kdw_eki_cp_key_role_type = eki_cp.get('key_role_type') self._kdw_eki_cp_digital_signature_algorithm = \ eki_cp.get('digital_signature_algorithm') self._kdw_eki_cp_cryptographic_algorithm = \ eki_cp.get('cryptographic_algorithm') self._kdw_eki_cp_random_iv = eki_cp.get('random_iv') self._kdw_eki_cp_iv_length = eki_cp.get('iv_length') self._kdw_eki_cp_tag_length = eki_cp.get('tag_length') self._kdw_eki_cp_fixed_field_length = eki_cp.get('fixed_field_length') self._kdw_eki_cp_invocation_field_length = \ eki_cp.get('invocation_field_length') self._kdw_eki_cp_counter_length = eki_cp.get('counter_length') self._kdw_eki_cp_initial_counter_value = \ eki_cp.get('initial_counter_value') mski = value.get('mac_signature_key_information') if mski is None: mski = {} self._kdw_mski_unique_identifier = mski.get('unique_identifier') mski_cp = mski.get('cryptographic_parameters') if mski_cp is None: mski_cp = {} self._kdw_mski_cp_block_cipher_mode = mski_cp.get('block_cipher_mode') self._kdw_mski_cp_padding_method = mski_cp.get('padding_method') self._kdw_mski_cp_hashing_algorithm = mski_cp.get('hashing_algorithm') self._kdw_mski_cp_key_role_type = mski_cp.get('key_role_type') self._kdw_mski_cp_digital_signature_algorithm = \ mski_cp.get('digital_signature_algorithm') self._kdw_mski_cp_cryptographic_algorithm = \ mski_cp.get('cryptographic_algorithm') self._kdw_mski_cp_random_iv = mski_cp.get('random_iv') self._kdw_mski_cp_iv_length = mski_cp.get('iv_length') self._kdw_mski_cp_tag_length = mski_cp.get('tag_length') self._kdw_mski_cp_fixed_field_length = \ mski_cp.get('fixed_field_length') self._kdw_mski_cp_invocation_field_length = \ mski_cp.get('invocation_field_length') self._kdw_mski_cp_counter_length = mski_cp.get('counter_length') self._kdw_mski_cp_initial_counter_value = \ mski_cp.get('initial_counter_value') self._kdw_mac_signature = value.get('mac_signature') self._kdw_iv_counter_nonce = value.get('iv_counter_nonce') self._kdw_encoding_option = value.get('encoding_option')
python
{ "resource": "" }
q270506
PublicKey.validate
test
def validate(self): """ Verify that the contents of the PublicKey object are valid. Raises: TypeError: if the types of any PublicKey attributes are invalid. """ if not isinstance(self.value, bytes): raise TypeError("key value must be bytes") elif not isinstance(self.cryptographic_algorithm, enums.CryptographicAlgorithm): raise TypeError("key algorithm must be a CryptographicAlgorithm " "enumeration") elif not isinstance(self.cryptographic_length, six.integer_types): raise TypeError("key length must be an integer") elif not isinstance(self.key_format_type, enums.KeyFormatType): raise TypeError("key format type must be a KeyFormatType " "enumeration") elif self.key_format_type not in self._valid_formats: raise ValueError("key format type must be one of {0}".format( self._valid_formats)) # TODO (peter-hamilton) Verify that the key bytes match the key format mask_count = len(self.cryptographic_usage_masks) for i in range(mask_count): mask = self.cryptographic_usage_masks[i] if not isinstance(mask, enums.CryptographicUsageMask): position = "({0} in list)".format(i) raise TypeError( "key mask {0} must be a CryptographicUsageMask " "enumeration".format(position)) name_count = len(self.names) for i in range(name_count): name = self.names[i] if not isinstance(name, six.string_types): position = "({0} in list)".format(i) raise TypeError("key name {0} must be a string".format( position))
python
{ "resource": "" }
q270507
SecretData.validate
test
def validate(self): """ Verify that the contents of the SecretData object are valid. Raises: TypeError: if the types of any SecretData attributes are invalid. """ if not isinstance(self.value, bytes): raise TypeError("secret value must be bytes") elif not isinstance(self.data_type, enums.SecretDataType): raise TypeError("secret data type must be a SecretDataType " "enumeration") mask_count = len(self.cryptographic_usage_masks) for i in range(mask_count): mask = self.cryptographic_usage_masks[i] if not isinstance(mask, enums.CryptographicUsageMask): position = "({0} in list)".format(i) raise TypeError( "secret data mask {0} must be a CryptographicUsageMask " "enumeration".format(position)) name_count = len(self.names) for i in range(name_count): name = self.names[i] if not isinstance(name, six.string_types): position = "({0} in list)".format(i) raise TypeError("secret data name {0} must be a string".format( position))
python
{ "resource": "" }
q270508
OpaqueObject.validate
test
def validate(self): """ Verify that the contents of the OpaqueObject are valid. Raises: TypeError: if the types of any OpaqueObject attributes are invalid. """ if not isinstance(self.value, bytes): raise TypeError("opaque value must be bytes") elif not isinstance(self.opaque_type, enums.OpaqueDataType): raise TypeError("opaque data type must be an OpaqueDataType " "enumeration") name_count = len(self.names) for i in range(name_count): name = self.names[i] if not isinstance(name, six.string_types): position = "({0} in list)".format(i) raise TypeError("opaque data name {0} must be a string".format( position))
python
{ "resource": "" }
q270509
convert_attribute_name_to_tag
test
def convert_attribute_name_to_tag(value): """ A utility function that converts an attribute name string into the corresponding attribute tag. For example: 'State' -> enums.Tags.STATE Args: value (string): The string name of the attribute. Returns: enum: The Tags enumeration value that corresponds to the attribute name string. Raises: ValueError: if the attribute name string is not a string or if it is an unrecognized attribute name """ if not isinstance(value, six.string_types): raise ValueError("The attribute name must be a string.") for entry in attribute_name_tag_table: if value == entry[0]: return entry[1] raise ValueError("Unrecognized attribute name: '{}'".format(value))
python
{ "resource": "" }
q270510
convert_attribute_tag_to_name
test
def convert_attribute_tag_to_name(value): """ A utility function that converts an attribute tag into the corresponding attribute name string. For example: enums.Tags.STATE -> 'State' Args: value (enum): The Tags enumeration value of the attribute. Returns: string: The attribute name string that corresponds to the attribute tag. Raises: ValueError: if the attribute tag is not a Tags enumeration or if it is unrecognized attribute tag """ if not isinstance(value, Tags): raise ValueError("The attribute tag must be a Tags enumeration.") for entry in attribute_name_tag_table: if value == entry[1]: return entry[0] raise ValueError("Unrecognized attribute tag: {}".format(value))
python
{ "resource": "" }
q270511
get_bit_mask_from_enumerations
test
def get_bit_mask_from_enumerations(enumerations): """ A utility function that computes a bit mask from a collection of enumeration values. Args: enumerations (list): A list of enumeration values to be combined in a composite bit mask. Returns: int: The composite bit mask. """ return functools.reduce( lambda x, y: x | y, [z.value for z in enumerations] )
python
{ "resource": "" }
q270512
get_enumerations_from_bit_mask
test
def get_enumerations_from_bit_mask(enumeration, mask): """ A utility function that creates a list of enumeration values from a bit mask for a specific mask enumeration class. Args: enumeration (class): The enumeration class from which to draw enumeration values. mask (int): The bit mask from which to identify enumeration values. Returns: list: A list of enumeration values corresponding to the bit mask. """ return [x for x in enumeration if (x.value & mask) == x.value]
python
{ "resource": "" }
q270513
is_bit_mask
test
def is_bit_mask(enumeration, potential_mask): """ A utility function that checks if the provided value is a composite bit mask of enumeration values in the specified enumeration class. Args: enumeration (class): One of the mask enumeration classes found in this file. These include: * Cryptographic Usage Mask * Protection Storage Mask * Storage Status Mask potential_mask (int): A potential bit mask composed of enumeration values belonging to the enumeration class. Returns: True: if the potential mask is a valid bit mask of the mask enumeration False: otherwise """ if not isinstance(potential_mask, six.integer_types): return False mask_enumerations = ( CryptographicUsageMask, ProtectionStorageMask, StorageStatusMask ) if enumeration not in mask_enumerations: return False mask = 0 for value in [e.value for e in enumeration]: if (value & potential_mask) == value: mask |= value if mask != potential_mask: return False return True
python
{ "resource": "" }
q270514
CreateKeyPairRequestPayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the CreateKeyPair request payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(CreateKeyPairRequestPayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self.is_tag_next( enums.Tags.COMMON_TEMPLATE_ATTRIBUTE, local_buffer ): self._common_template_attribute = objects.TemplateAttribute( tag=enums.Tags.COMMON_TEMPLATE_ATTRIBUTE ) self._common_template_attribute.read( local_buffer, kmip_version=kmip_version ) else: if self.is_tag_next(enums.Tags.COMMON_ATTRIBUTES, local_buffer): attributes = objects.Attributes( tag=enums.Tags.COMMON_ATTRIBUTES ) attributes.read(local_buffer, kmip_version=kmip_version) self._common_template_attribute = \ objects.convert_attributes_to_template_attribute( attributes ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self.is_tag_next( enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE, local_buffer ): self._private_key_template_attribute = \ objects.TemplateAttribute( tag=enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE ) self._private_key_template_attribute.read( local_buffer, kmip_version=kmip_version ) else: if self.is_tag_next( enums.Tags.PRIVATE_KEY_ATTRIBUTES, local_buffer ): attributes = objects.Attributes( tag=enums.Tags.PRIVATE_KEY_ATTRIBUTES ) attributes.read(local_buffer, kmip_version=kmip_version) self._private_key_template_attribute = \ objects.convert_attributes_to_template_attribute( attributes ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self.is_tag_next( enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE, local_buffer ): self._public_key_template_attribute = \ objects.TemplateAttribute( tag=enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE ) self._public_key_template_attribute.read( local_buffer, kmip_version=kmip_version ) else: if self.is_tag_next( enums.Tags.PUBLIC_KEY_ATTRIBUTES, local_buffer ): attributes = objects.Attributes( tag=enums.Tags.PUBLIC_KEY_ATTRIBUTES ) attributes.read(local_buffer, kmip_version=kmip_version) self._public_key_template_attribute = \ objects.convert_attributes_to_template_attribute( attributes ) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270515
CreateKeyPairRequestPayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the CreateKeyPair request payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_buffer = utils.BytearrayStream() if kmip_version < enums.KMIPVersion.KMIP_2_0: if self._common_template_attribute is not None: self._common_template_attribute.write( local_buffer, kmip_version=kmip_version ) else: if self._common_template_attribute is not None: attributes = objects.convert_template_attribute_to_attributes( self._common_template_attribute ) attributes.write(local_buffer, kmip_version=kmip_version) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self._private_key_template_attribute is not None: self._private_key_template_attribute.write( local_buffer, kmip_version=kmip_version ) else: if self._private_key_template_attribute is not None: attributes = objects.convert_template_attribute_to_attributes( self._private_key_template_attribute ) attributes.write(local_buffer, kmip_version=kmip_version) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self._public_key_template_attribute is not None: self._public_key_template_attribute.write( local_buffer, kmip_version=kmip_version ) else: if self._public_key_template_attribute is not None: attributes = objects.convert_template_attribute_to_attributes( self._public_key_template_attribute ) attributes.write(local_buffer, kmip_version=kmip_version) self.length = local_buffer.length() super(CreateKeyPairRequestPayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270516
CreateKeyPairResponsePayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the CreateKeyPair response payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: InvalidKmipEncoding: Raised if the private key unique identifier or the public key unique identifier is missing from the encoded payload. """ super(CreateKeyPairResponsePayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next( enums.Tags.PRIVATE_KEY_UNIQUE_IDENTIFIER, local_buffer ): self._private_key_unique_identifier = primitives.TextString( tag=enums.Tags.PRIVATE_KEY_UNIQUE_IDENTIFIER ) self._private_key_unique_identifier.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The CreateKeyPair response payload encoding is missing the " "private key unique identifier." ) if self.is_tag_next( enums.Tags.PUBLIC_KEY_UNIQUE_IDENTIFIER, local_buffer ): self._public_key_unique_identifier = primitives.TextString( tag=enums.Tags.PUBLIC_KEY_UNIQUE_IDENTIFIER ) self._public_key_unique_identifier.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The CreateKeyPair response payload encoding is missing the " "public key unique identifier." ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self.is_tag_next( enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE, local_buffer ): self._private_key_template_attribute = \ objects.TemplateAttribute( tag=enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE ) self._private_key_template_attribute.read( local_buffer, kmip_version=kmip_version ) if self.is_tag_next( enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE, local_buffer ): self._public_key_template_attribute = \ objects.TemplateAttribute( tag=enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE ) self._public_key_template_attribute.read( local_buffer, kmip_version=kmip_version ) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270517
CreateKeyPairResponsePayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the CreateKeyPair response payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: InvalidField: Raised if the private key unique identifier or the public key unique identifier is not defined. """ local_buffer = utils.BytearrayStream() if self._private_key_unique_identifier: self._private_key_unique_identifier.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The CreateKeyPair response payload is missing the private " "key unique identifier field." ) if self._public_key_unique_identifier: self._public_key_unique_identifier.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The CreateKeyPair response payload is missing the public " "key unique identifier field." ) if self._private_key_template_attribute: self._private_key_template_attribute.write( local_buffer, kmip_version=kmip_version ) if self._public_key_template_attribute: self._public_key_template_attribute.write( local_buffer, kmip_version=kmip_version ) self.length = local_buffer.length() super(CreateKeyPairResponsePayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270518
GetAttributeListRequestPayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the GetAttributeList request payload and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(GetAttributeListRequestPayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_buffer, kmip_version=kmip_version ) else: self._unique_identifier = None self.is_oversized(local_buffer)
python
{ "resource": "" }
q270519
GetAttributeListRequestPayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the GetAttributeList request payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_buffer = utils.BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_buffer, kmip_version=kmip_version ) self.length = local_buffer.length() super(GetAttributeListRequestPayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270520
GetAttributeListResponsePayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the GetAttributeList response payload and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: InvalidKmipEncoding: Raised if the unique identifier or attribute names are missing from the encoded payload. """ super(GetAttributeListResponsePayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The GetAttributeList response payload encoding is missing " "the unique identifier." ) names = list() if kmip_version < enums.KMIPVersion.KMIP_2_0: while self.is_tag_next(enums.Tags.ATTRIBUTE_NAME, local_buffer): name = primitives.TextString(tag=enums.Tags.ATTRIBUTE_NAME) name.read(local_buffer, kmip_version=kmip_version) names.append(name) if len(names) == 0: raise exceptions.InvalidKmipEncoding( "The GetAttributeList response payload encoding is " "missing the attribute names." ) self._attribute_names = names else: while self.is_tag_next( enums.Tags.ATTRIBUTE_REFERENCE, local_buffer ): if self.is_type_next(enums.Types.STRUCTURE, local_buffer): reference = objects.AttributeReference() reference.read(local_buffer, kmip_version=kmip_version) names.append( primitives.TextString( value=reference.attribute_name, tag=enums.Tags.ATTRIBUTE_NAME ) ) elif self.is_type_next(enums.Types.ENUMERATION, local_buffer): reference = primitives.Enumeration( enums.Tags, tag=enums.Tags.ATTRIBUTE_REFERENCE ) reference.read(local_buffer, kmip_version=kmip_version) name = enums.convert_attribute_tag_to_name(reference.value) names.append( primitives.TextString( value=name, tag=enums.Tags.ATTRIBUTE_NAME ) ) else: raise exceptions.InvalidKmipEncoding( "The GetAttributeList response payload encoding " "contains an invalid AttributeReference type." ) self._attribute_names = names self.is_oversized(local_buffer)
python
{ "resource": "" }
q270521
GetAttributeListResponsePayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the GetAttributeList response payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: InvalidField: Raised if the unique identifier or attribute name are not defined. """ local_buffer = utils.BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The GetAttributeList response payload is missing the unique " "identifier field." ) if self._attribute_names: if kmip_version < enums.KMIPVersion.KMIP_2_0: for attribute_name in self._attribute_names: attribute_name.write( local_buffer, kmip_version=kmip_version ) else: # NOTE (ph) This approach simplifies backwards compatible # issues but limits easy support for Attribute # Reference structures going forward, specifically # limiting the use of VendorIdentification for # custom attributes. If custom attributes need to # be retrieved using the GetAttributeList operation # for KMIP 2.0 applications this code will need to # change. for attribute_name in self._attribute_names: t = enums.convert_attribute_name_to_tag( attribute_name.value ) e = primitives.Enumeration( enums.Tags, value=t, tag=enums.Tags.ATTRIBUTE_REFERENCE ) e.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The GetAttributeList response payload is missing the " "attribute names field." ) self.length = local_buffer.length() super(GetAttributeListResponsePayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270522
get_json_files
test
def get_json_files(p): """ Scan the provided policy directory for all JSON policy files. """ f = [os.path.join(p, x) for x in os.listdir(p) if x.endswith(".json")] return sorted(f)
python
{ "resource": "" }
q270523
PolicyDirectoryMonitor.scan_policies
test
def scan_policies(self): """ Scan the policy directory for policy data. """ policy_files = get_json_files(self.policy_directory) for f in set(policy_files) - set(self.policy_files): self.file_timestamps[f] = 0 for f in set(self.policy_files) - set(policy_files): self.logger.info("Removing policies for file: {}".format(f)) self.file_timestamps.pop(f, None) for p in self.policy_cache.keys(): self.disassociate_policy_and_file(p, f) for p in [k for k, v in self.policy_map.items() if v == f]: self.restore_or_delete_policy(p) self.policy_files = policy_files for f in sorted(self.file_timestamps.keys()): t = os.path.getmtime(f) if t > self.file_timestamps[f]: self.logger.info("Loading policies for file: {}".format(f)) self.file_timestamps[f] = t old_p = [k for k, v in self.policy_map.items() if v == f] try: new_p = operation_policy.read_policy_from_file(f) except ValueError: self.logger.error("Failure loading file: {}".format(f)) self.logger.debug("", exc_info=True) continue for p in new_p.keys(): self.logger.info("Loading policy: {}".format(p)) if p in self.reserved_policies: self.logger.warning( "Policy '{}' overwrites a reserved policy and " "will be thrown out.".format(p) ) continue if p in sorted(self.policy_store.keys()): self.logger.debug( "Policy '{}' overwrites an existing " "policy.".format(p) ) if f != self.policy_map.get(p): self.policy_cache.get(p).append( ( time.time(), self.policy_map.get(p), self.policy_store.get(p) ) ) else: self.policy_cache[p] = [] self.policy_store[p] = new_p.get(p) self.policy_map[p] = f for p in set(old_p) - set(new_p.keys()): self.disassociate_policy_and_file(p, f) self.restore_or_delete_policy(p)
python
{ "resource": "" }
q270524
PolicyDirectoryMonitor.run
test
def run(self): """ Start monitoring operation policy files. """ self.initialize_tracking_structures() if self.live_monitoring: self.logger.info("Starting up the operation policy file monitor.") while not self.halt_trigger.is_set(): time.sleep(1) self.scan_policies() self.logger.info("Stopping the operation policy file monitor.") else: self.scan_policies()
python
{ "resource": "" }
q270525
get_certificate_from_connection
test
def get_certificate_from_connection(connection): """ Extract an X.509 certificate from a socket connection. """ certificate = connection.getpeercert(binary_form=True) if certificate: return x509.load_der_x509_certificate( certificate, backends.default_backend() ) return None
python
{ "resource": "" }
q270526
get_extended_key_usage_from_certificate
test
def get_extended_key_usage_from_certificate(certificate): """ Given an X.509 certificate, extract and return the extendedKeyUsage extension. """ try: return certificate.extensions.get_extension_for_oid( x509.oid.ExtensionOID.EXTENDED_KEY_USAGE ).value except x509.ExtensionNotFound: return None
python
{ "resource": "" }
q270527
get_common_names_from_certificate
test
def get_common_names_from_certificate(certificate): """ Given an X.509 certificate, extract and return all common names. """ common_names = certificate.subject.get_attributes_for_oid( x509.oid.NameOID.COMMON_NAME ) return [common_name.value for common_name in common_names]
python
{ "resource": "" }
q270528
get_client_identity_from_certificate
test
def get_client_identity_from_certificate(certificate): """ Given an X.509 certificate, extract and return the client identity. """ client_ids = get_common_names_from_certificate(certificate) if len(client_ids) > 0: if len(client_ids) > 1: raise exceptions.PermissionDenied( "Multiple client identities found." ) return client_ids[0] else: raise exceptions.PermissionDenied( "The certificate does not define any subject common names. " "Client identity unavailable." )
python
{ "resource": "" }
q270529
CreateRequestPayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Create request payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: InvalidKmipEncoding: Raised if the object type or template attribute is missing from the encoded payload. """ super(CreateRequestPayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer): self._object_type = primitives.Enumeration( enums.ObjectType, tag=enums.Tags.OBJECT_TYPE ) self._object_type.read(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidKmipEncoding( "The Create request payload encoding is missing the object " "type." ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer): self._template_attribute = objects.TemplateAttribute() self._template_attribute.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The Create request payload encoding is missing the " "template attribute." ) else: # NOTE (ph) For now, leave attributes natively in TemplateAttribute # form and just convert to the KMIP 2.0 Attributes form as needed # for encoding/decoding purposes. Changing the payload to require # the new Attributes structure will trigger a bunch of second-order # effects across the client and server codebases that is beyond # the scope of updating the Create payloads to support KMIP 2.0. if self.is_tag_next(enums.Tags.ATTRIBUTES, local_buffer): attributes = objects.Attributes() attributes.read(local_buffer, kmip_version=kmip_version) value = objects.convert_attributes_to_template_attribute( attributes ) self._template_attribute = value else: raise exceptions.InvalidKmipEncoding( "The Create request payload encoding is missing the " "attributes structure." ) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270530
CreateRequestPayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Create request payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: InvalidField: Raised if the object type attribute or template attribute is not defined. """ local_buffer = utils.BytearrayStream() if self._object_type: self._object_type.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The Create request payload is missing the object type field." ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self._template_attribute: self._template_attribute.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The Create request payload is missing the template " "attribute field." ) else: # NOTE (ph) For now, leave attributes natively in TemplateAttribute # form and just convert to the KMIP 2.0 Attributes form as needed # for encoding/decoding purposes. Changing the payload to require # the new Attributes structure will trigger a bunch of second-order # effects across the client and server codebases that is beyond # the scope of updating the Create payloads to support KMIP 2.0. if self._template_attribute: attributes = objects.convert_template_attribute_to_attributes( self._template_attribute ) attributes.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The Create request payload is missing the template " "attribute field." ) self.length = local_buffer.length() super(CreateRequestPayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270531
CreateResponsePayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Create response payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: InvalidKmipEncoding: Raised if the object type or unique identifier is missing from the encoded payload. """ super(CreateResponsePayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer): self._object_type = primitives.Enumeration( enums.ObjectType, tag=enums.Tags.OBJECT_TYPE ) self._object_type.read(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidKmipEncoding( "The Create response payload encoding is missing the object " "type." ) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The Create response payload encoding is missing the unique " "identifier." ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer): self._template_attribute = objects.TemplateAttribute() self._template_attribute.read( local_buffer, kmip_version=kmip_version ) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270532
CreateResponsePayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Create response payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: InvalidField: Raised if the object type attribute or unique identifier is not defined. """ local_buffer = utils.BytearrayStream() if self._object_type: self._object_type.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The Create response payload is missing the object type field." ) if self._unique_identifier: self._unique_identifier.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The Create response payload is missing the unique identifier " "field." ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self._template_attribute: self._template_attribute.write( local_buffer, kmip_version=kmip_version ) self.length = local_buffer.length() super(CreateResponsePayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270533
ObjectFactory.convert
test
def convert(self, obj): """ Convert a Pie object into a core secret object and vice versa. Args: obj (various): A Pie or core secret object to convert into the opposite object space. Required. Raises: TypeError: if the object type is unrecognized or unsupported. """ if isinstance(obj, pobjects.SymmetricKey): return self._build_core_key(obj, secrets.SymmetricKey) elif isinstance(obj, secrets.SymmetricKey): return self._build_pie_key(obj, pobjects.SymmetricKey) elif isinstance(obj, pobjects.PublicKey): return self._build_core_key(obj, secrets.PublicKey) elif isinstance(obj, secrets.PublicKey): return self._build_pie_key(obj, pobjects.PublicKey) elif isinstance(obj, pobjects.PrivateKey): return self._build_core_key(obj, secrets.PrivateKey) elif isinstance(obj, secrets.PrivateKey): return self._build_pie_key(obj, pobjects.PrivateKey) elif isinstance(obj, pobjects.Certificate): return self._build_core_certificate(obj) elif isinstance(obj, secrets.Certificate): return self._build_pie_certificate(obj) elif isinstance(obj, pobjects.SecretData): return self._build_core_secret_data(obj) elif isinstance(obj, secrets.SecretData): return self._build_pie_secret_data(obj) elif isinstance(obj, pobjects.OpaqueObject): return self._build_core_opaque_object(obj) elif isinstance(obj, secrets.OpaqueObject): return self._build_pie_opaque_object(obj) else: raise TypeError("object type unsupported and cannot be converted")
python
{ "resource": "" }
q270534
EncryptResponsePayload.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Encrypt response payload and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the unique_identifier or data attributes are missing from the encoded payload. """ super(EncryptResponsePayload, self).read( input_stream, kmip_version=kmip_version ) local_stream = utils.BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_stream, kmip_version=kmip_version ) else: raise ValueError( "invalid payload missing the unique identifier attribute" ) if self.is_tag_next(enums.Tags.DATA, local_stream): self._data = primitives.ByteString(tag=enums.Tags.DATA) self._data.read( local_stream, kmip_version=kmip_version ) else: raise ValueError("invalid payload missing the data attribute") if self.is_tag_next(enums.Tags.IV_COUNTER_NONCE, local_stream): self._iv_counter_nonce = primitives.ByteString( tag=enums.Tags.IV_COUNTER_NONCE ) self._iv_counter_nonce.read( local_stream, kmip_version=kmip_version ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270535
DeriveKeyRequestPayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the DeriveKey request payload and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the data attribute is missing from the encoded payload. """ super(DeriveKeyRequestPayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer): self._object_type = primitives.Enumeration( enums.ObjectType, tag=enums.Tags.OBJECT_TYPE ) self._object_type.read(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidKmipEncoding( "The DeriveKey request payload encoding is missing the object " "type." ) unique_identifiers = [] while self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer): unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) unique_identifier.read(local_buffer, kmip_version=kmip_version) unique_identifiers.append(unique_identifier) if not unique_identifiers: raise exceptions.InvalidKmipEncoding( "The DeriveKey request payload encoding is missing the unique " "identifiers." ) else: self._unique_identifiers = unique_identifiers if self.is_tag_next(enums.Tags.DERIVATION_METHOD, local_buffer): self._derivation_method = primitives.Enumeration( enums.DerivationMethod, tag=enums.Tags.DERIVATION_METHOD ) self._derivation_method.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The DeriveKey request payload encoding is missing the " "derivation method." ) if self.is_tag_next(enums.Tags.DERIVATION_PARAMETERS, local_buffer): self._derivation_parameters = attributes.DerivationParameters() self._derivation_parameters.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The DeriveKey request payload encoding is missing the " "derivation parameters." ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer): self._template_attribute = objects.TemplateAttribute() self._template_attribute.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The DeriveKey request payload encoding is missing the " "template attribute." ) else: if self.is_tag_next(enums.Tags.ATTRIBUTES, local_buffer): attrs = objects.Attributes() attrs.read(local_buffer, kmip_version=kmip_version) value = objects.convert_attributes_to_template_attribute( attrs ) self._template_attribute = value else: raise exceptions.InvalidKmipEncoding( "The DeriveKey request payload encoding is missing the " "attributes structure." ) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270536
DeriveKeyRequestPayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the DeriveKey request payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the data attribute is not defined. """ local_buffer = utils.BytearrayStream() if self._object_type: self._object_type.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The DeriveKey request payload is missing the object type " "field." ) if self._unique_identifiers: for unique_identifier in self._unique_identifiers: unique_identifier.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The DeriveKey request payload is missing the unique " "identifiers field." ) if self._derivation_method: self._derivation_method.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The DeriveKey request payload is missing the derivation " "method field." ) if self._derivation_parameters: self._derivation_parameters.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The DeriveKey request payload is missing the derivation " "parameters field." ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self._template_attribute: self._template_attribute.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The DeriveKey request payload is missing the template " "attribute field." ) else: if self._template_attribute: attrs = objects.convert_template_attribute_to_attributes( self._template_attribute ) attrs.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The DeriveKey request payload is missing the template " "attribute field." ) self.length = local_buffer.length() super(DeriveKeyRequestPayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270537
AttributePolicy.is_attribute_supported
test
def is_attribute_supported(self, attribute): """ Check if the attribute is supported by the current KMIP version. Args: attribute (string): The name of the attribute (e.g., 'Cryptographic Algorithm'). Required. Returns: bool: True if the attribute is supported by the current KMIP version. False otherwise. """ if attribute not in self._attribute_rule_sets.keys(): return False rule_set = self._attribute_rule_sets.get(attribute) if self._version >= rule_set.version_added: return True else: return False
python
{ "resource": "" }
q270538
AttributePolicy.is_attribute_deprecated
test
def is_attribute_deprecated(self, attribute): """ Check if the attribute is deprecated by the current KMIP version. Args: attribute (string): The name of the attribute (e.g., 'Unique Identifier'). Required. """ rule_set = self._attribute_rule_sets.get(attribute) if rule_set.version_deprecated: if self._version >= rule_set.version_deprecated: return True else: return False else: return False
python
{ "resource": "" }
q270539
AttributePolicy.is_attribute_applicable_to_object_type
test
def is_attribute_applicable_to_object_type(self, attribute, object_type): """ Check if the attribute is supported by the given object type. Args: attribute (string): The name of the attribute (e.g., 'Name'). Required. object_type (ObjectType): An ObjectType enumeration (e.g., ObjectType.SYMMETRIC_KEY). Required. Returns: bool: True if the attribute is applicable to the object type. False otherwise. """ # TODO (peterhamilton) Handle applicability between certificate types rule_set = self._attribute_rule_sets.get(attribute) if object_type in rule_set.applies_to_object_types: return True else: return False
python
{ "resource": "" }
q270540
AttributePolicy.is_attribute_multivalued
test
def is_attribute_multivalued(self, attribute): """ Check if the attribute is allowed to have multiple instances. Args: attribute (string): The name of the attribute (e.g., 'State'). Required. """ # TODO (peterhamilton) Handle multivalue swap between certificate types rule_set = self._attribute_rule_sets.get(attribute) return rule_set.multiple_instances_permitted
python
{ "resource": "" }
q270541
ConfigHelper.get_valid_value
test
def get_valid_value(self, direct_value, config_section, config_option_name, default_value): """Returns a value that can be used as a parameter in client or server. If a direct_value is given, that value will be returned instead of the value from the config file. If the appropriate config file option is not found, the default_value is returned. :param direct_value: represents a direct value that should be used. supercedes values from config files :param config_section: which section of the config file to use :param config_option_name: name of config option value :param default_value: default value to be used if other options not found :returns: a value that can be used as a parameter """ ARG_MSG = "Using given value '{0}' for {1}" CONF_MSG = "Using value '{0}' from configuration file {1} for {2}" DEFAULT_MSG = "Using default value '{0}' for {1}" if direct_value: return_value = direct_value self.logger.debug(ARG_MSG.format(direct_value, config_option_name)) else: try: return_value = self.conf.get(config_section, config_option_name) self.logger.debug(CONF_MSG.format(return_value, CONFIG_FILE, config_option_name)) except Exception: return_value = default_value self.logger.debug(DEFAULT_MSG.format(default_value, config_option_name)) # TODO (peter-hamilton): Think about adding better value validation if return_value == self.NONE_VALUE: return None else: return return_value
python
{ "resource": "" }
q270542
CheckResponsePayload.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Check response payload and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the data attribute is missing from the encoded payload. """ super(CheckResponsePayload, self).read( input_stream, kmip_version=kmip_version ) local_stream = utils.BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.USAGE_LIMITS_COUNT, local_stream): self._usage_limits_count = primitives.LongInteger( tag=enums.Tags.USAGE_LIMITS_COUNT ) self._usage_limits_count.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.CRYPTOGRAPHIC_USAGE_MASK, local_stream): self._cryptographic_usage_mask = primitives.Integer( tag=enums.Tags.CRYPTOGRAPHIC_USAGE_MASK ) self._cryptographic_usage_mask.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.LEASE_TIME, local_stream): self._lease_time = primitives.Interval( tag=enums.Tags.LEASE_TIME ) self._lease_time.read( local_stream, kmip_version=kmip_version ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270543
CheckResponsePayload.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Check response payload to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the data attribute is not defined. """ local_stream = utils.BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_stream, kmip_version=kmip_version ) if self._usage_limits_count: self._usage_limits_count.write( local_stream, kmip_version=kmip_version ) if self._cryptographic_usage_mask: self._cryptographic_usage_mask.write( local_stream, kmip_version=kmip_version ) if self._lease_time: self._lease_time.write( local_stream, kmip_version=kmip_version ) self.length = local_stream.length() super(CheckResponsePayload, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270544
AttributeReference.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Read the data stream and decode the AttributeReference structure into its parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 2.0. Raises: InvalidKmipEncoding: Raised if the vendor identification or attribute name is missing from the encoding. VersionNotSupported: Raised when a KMIP version is provided that does not support the AttributeReference structure. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the AttributeReference " "object.".format( kmip_version.value ) ) super(AttributeReference, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.VENDOR_IDENTIFICATION, local_buffer): self._vendor_identification = primitives.TextString( tag=enums.Tags.VENDOR_IDENTIFICATION ) self._vendor_identification.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The AttributeReference encoding is missing the vendor " "identification string." ) if self.is_tag_next(enums.Tags.ATTRIBUTE_NAME, local_buffer): self._attribute_name = primitives.TextString( tag=enums.Tags.ATTRIBUTE_NAME ) self._attribute_name.read( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidKmipEncoding( "The AttributeReference encoding is missing the attribute " "name string." ) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270545
AttributeReference.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Write the AttributeReference structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode Attributes structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: InvalidField: Raised if the vendor identification or attribute name fields are not defined. VersionNotSupported: Raised when a KMIP version is provided that does not support the AttributeReference structure. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the AttributeReference " "object.".format( kmip_version.value ) ) local_buffer = BytearrayStream() if self._vendor_identification: self._vendor_identification.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The AttributeReference is missing the vendor identification " "field." ) if self._attribute_name: self._attribute_name.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The AttributeReference is missing the attribute name field." ) self.length = local_buffer.length() super(AttributeReference, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270546
Attributes.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Read the data stream and decode the Attributes structure into its parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 2.0. Raises: AttributeNotSupported: Raised if an unsupported attribute is encountered while decoding. VersionNotSupported: Raised when a KMIP version is provided that does not support the Attributes object. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the Attributes object.".format( kmip_version.value ) ) super(Attributes, self).read(input_stream, kmip_version=kmip_version) local_stream = BytearrayStream(input_stream.read(self.length)) while True: if len(local_stream) < 3: break tag = struct.unpack('!I', b'\x00' + local_stream.peek(3))[0] if enums.is_enum_value(enums.Tags, tag): tag = enums.Tags(tag) if not enums.is_attribute(tag, kmip_version=kmip_version): raise exceptions.AttributeNotSupported( "Attribute {} is not supported by KMIP {}.".format( tag.name, kmip_version.value ) ) value = self._factory.create_attribute_value_by_enum(tag, None) value.read(local_stream, kmip_version=kmip_version) self._attributes.append(value) else: break self.is_oversized(local_stream)
python
{ "resource": "" }
q270547
Attributes.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Write the Attributes structure encoding to the data stream. Args: output_stream (stream): A data stream in which to encode Attributes structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: AttributeNotSupported: Raised if an unsupported attribute is found in the attribute list while encoding. VersionNotSupported: Raised when a KMIP version is provided that does not support the Attributes object. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the Attributes object.".format( kmip_version.value ) ) local_stream = BytearrayStream() for attribute in self._attributes: tag = attribute.tag if not enums.is_attribute(tag, kmip_version=kmip_version): raise exceptions.AttributeNotSupported( "Attribute {} is not supported by KMIP {}.".format( tag.name, kmip_version.value ) ) attribute.write(local_stream, kmip_version=kmip_version) self.length = local_stream.length() super(Attributes, self).write(output_stream, kmip_version=kmip_version) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270548
Nonce.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Nonce struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the nonce ID or nonce value is missing from the encoding. """ super(Nonce, self).read(input_stream, kmip_version=kmip_version) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.NONCE_ID, local_stream): self._nonce_id = primitives.ByteString( tag=enums.Tags.NONCE_ID ) self._nonce_id.read(local_stream, kmip_version=kmip_version) else: raise ValueError( "Nonce encoding missing the nonce ID." ) if self.is_tag_next(enums.Tags.NONCE_VALUE, local_stream): self._nonce_value = primitives.ByteString( tag=enums.Tags.NONCE_VALUE ) self._nonce_value.read(local_stream, kmip_version=kmip_version) else: raise ValueError( "Nonce encoding missing the nonce value." ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270549
Nonce.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Nonce struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the nonce ID or nonce value is not defined. """ local_stream = BytearrayStream() if self._nonce_id: self._nonce_id.write(local_stream, kmip_version=kmip_version) else: raise ValueError("Nonce struct is missing the nonce ID.") if self._nonce_value: self._nonce_value.write(local_stream, kmip_version=kmip_version) else: raise ValueError("Nonce struct is missing the nonce value.") self.length = local_stream.length() super(Nonce, self).write(output_stream, kmip_version=kmip_version) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270550
UsernamePasswordCredential.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the UsernamePasswordCredential struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the username is missing from the encoding. """ super(UsernamePasswordCredential, self).read( input_stream, kmip_version=kmip_version ) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.USERNAME, local_stream): self._username = primitives.TextString( tag=enums.Tags.USERNAME ) self._username.read(local_stream, kmip_version=kmip_version) else: raise ValueError( "Username/password credential encoding missing the username." ) if self.is_tag_next(enums.Tags.PASSWORD, local_stream): self._password = primitives.TextString( tag=enums.Tags.PASSWORD ) self._password.read(local_stream, kmip_version=kmip_version) self.is_oversized(local_stream)
python
{ "resource": "" }
q270551
UsernamePasswordCredential.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the UsernamePasswordCredential struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the username is not defined. """ local_stream = BytearrayStream() if self._username: self._username.write(local_stream, kmip_version=kmip_version) else: raise ValueError( "Username/password credential struct missing the username." ) if self._password: self._password.write(local_stream, kmip_version=kmip_version) self.length = local_stream.length() super(UsernamePasswordCredential, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270552
DeviceCredential.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the DeviceCredential struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(DeviceCredential, self).read( input_stream, kmip_version=kmip_version ) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.DEVICE_SERIAL_NUMBER, local_stream): self._device_serial_number = primitives.TextString( tag=enums.Tags.DEVICE_SERIAL_NUMBER ) self._device_serial_number.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.PASSWORD, local_stream): self._password = primitives.TextString( tag=enums.Tags.PASSWORD ) self._password.read(local_stream, kmip_version=kmip_version) if self.is_tag_next(enums.Tags.DEVICE_IDENTIFIER, local_stream): self._device_identifier = primitives.TextString( tag=enums.Tags.DEVICE_IDENTIFIER ) self._device_identifier.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.NETWORK_IDENTIFIER, local_stream): self._network_identifier = primitives.TextString( tag=enums.Tags.NETWORK_IDENTIFIER ) self._network_identifier.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.MACHINE_IDENTIFIER, local_stream): self._machine_identifier = primitives.TextString( tag=enums.Tags.MACHINE_IDENTIFIER ) self._machine_identifier.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.MEDIA_IDENTIFIER, local_stream): self._media_identifier = primitives.TextString( tag=enums.Tags.MEDIA_IDENTIFIER ) self._media_identifier.read( local_stream, kmip_version=kmip_version ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270553
DeviceCredential.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the DeviceCredential struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_stream = BytearrayStream() if self._device_serial_number is not None: self._device_serial_number.write( local_stream, kmip_version=kmip_version ) if self._password is not None: self._password.write( local_stream, kmip_version=kmip_version ) if self._device_identifier is not None: self._device_identifier.write( local_stream, kmip_version=kmip_version ) if self._network_identifier is not None: self._network_identifier.write( local_stream, kmip_version=kmip_version) if self._machine_identifier is not None: self._machine_identifier.write( local_stream, kmip_version=kmip_version ) if self._media_identifier is not None: self._media_identifier.write( local_stream, kmip_version=kmip_version ) self.length = local_stream.length() super(DeviceCredential, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270554
Credential.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Credential struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if either the credential type or value are missing from the encoding. """ super(Credential, self).read(input_stream, kmip_version=kmip_version) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.CREDENTIAL_TYPE, local_stream): self._credential_type = primitives.Enumeration( enum=enums.CredentialType, tag=enums.Tags.CREDENTIAL_TYPE ) self._credential_type.read(local_stream, kmip_version=kmip_version) else: raise ValueError( "Credential encoding missing the credential type." ) if self.is_tag_next(enums.Tags.CREDENTIAL_VALUE, local_stream): if self.credential_type == \ enums.CredentialType.USERNAME_AND_PASSWORD: self._credential_value = UsernamePasswordCredential() elif self.credential_type == enums.CredentialType.DEVICE: self._credential_value = DeviceCredential() elif self.credential_type == enums.CredentialType.ATTESTATION: self._credential_value = AttestationCredential() else: raise ValueError( "Credential encoding includes unrecognized credential " "type." ) self._credential_value.read( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Credential encoding missing the credential value." ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270555
Credential.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Credential struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if either the credential type or value are not defined. """ local_stream = BytearrayStream() if self._credential_type: self._credential_type.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Credential struct missing the credential type." ) if self._credential_value: self._credential_value.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Credential struct missing the credential value." ) self.length = local_stream.length() super(Credential, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270556
MACSignatureKeyInformation.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the MACSignatureKeyInformation struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(MACSignatureKeyInformation, self).read( input_stream, kmip_version=kmip_version ) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Invalid struct missing the unique identifier attribute." ) if self.is_tag_next( enums.Tags.CRYPTOGRAPHIC_PARAMETERS, local_stream ): self._cryptographic_parameters = CryptographicParameters() self._cryptographic_parameters.read( local_stream, kmip_version=kmip_version ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270557
MACSignatureKeyInformation.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the MACSignatureKeyInformation struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_stream = BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Invalid struct missing the unique identifier attribute." ) if self._cryptographic_parameters: self._cryptographic_parameters.write( local_stream, kmip_version=kmip_version ) self.length = local_stream.length() super(MACSignatureKeyInformation, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270558
KeyWrappingData.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the KeyWrappingData struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(KeyWrappingData, self).read( input_stream, kmip_version=kmip_version ) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.WRAPPING_METHOD, local_stream): self._wrapping_method = primitives.Enumeration( enum=enums.WrappingMethod, tag=enums.Tags.WRAPPING_METHOD ) self._wrapping_method.read( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Invalid struct missing the wrapping method attribute." ) if self.is_tag_next( enums.Tags.ENCRYPTION_KEY_INFORMATION, local_stream ): self._encryption_key_information = EncryptionKeyInformation() self._encryption_key_information.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next( enums.Tags.MAC_SIGNATURE_KEY_INFORMATION, local_stream ): self._mac_signature_key_information = MACSignatureKeyInformation() self._mac_signature_key_information.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.MAC_SIGNATURE, local_stream): self._mac_signature = primitives.ByteString( tag=enums.Tags.MAC_SIGNATURE ) self._mac_signature.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.IV_COUNTER_NONCE, local_stream): self._iv_counter_nonce = primitives.ByteString( tag=enums.Tags.IV_COUNTER_NONCE ) self._iv_counter_nonce.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.ENCODING_OPTION, local_stream): self._encoding_option = primitives.Enumeration( enum=enums.EncodingOption, tag=enums.Tags.ENCODING_OPTION ) self._encoding_option.read( local_stream, kmip_version=kmip_version ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270559
KeyWrappingData.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the KeyWrappingData struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_stream = BytearrayStream() if self._wrapping_method: self._wrapping_method.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Invalid struct missing the wrapping method attribute." ) if self._encryption_key_information: self._encryption_key_information.write( local_stream, kmip_version=kmip_version ) if self._mac_signature_key_information: self._mac_signature_key_information.write( local_stream, kmip_version=kmip_version ) if self._mac_signature: self._mac_signature.write( local_stream, kmip_version=kmip_version ) if self._iv_counter_nonce: self._iv_counter_nonce.write( local_stream, kmip_version=kmip_version ) if self._encoding_option: self._encoding_option.write( local_stream, kmip_version=kmip_version ) self.length = local_stream.length() super(KeyWrappingData, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270560
KeyWrappingSpecification.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the KeyWrappingSpecification struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(KeyWrappingSpecification, self).read( input_stream, kmip_version=kmip_version ) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.WRAPPING_METHOD, local_stream): self._wrapping_method = primitives.Enumeration( enum=enums.WrappingMethod, tag=enums.Tags.WRAPPING_METHOD ) self._wrapping_method.read( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Invalid struct missing the wrapping method attribute." ) if self.is_tag_next( enums.Tags.ENCRYPTION_KEY_INFORMATION, local_stream ): self._encryption_key_information = EncryptionKeyInformation() self._encryption_key_information.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next( enums.Tags.MAC_SIGNATURE_KEY_INFORMATION, local_stream ): self._mac_signature_key_information = MACSignatureKeyInformation() self._mac_signature_key_information.read( local_stream, kmip_version=kmip_version ) attribute_names = [] while self.is_tag_next(enums.Tags.ATTRIBUTE_NAME, local_stream): attribute_name = primitives.TextString( tag=enums.Tags.ATTRIBUTE_NAME ) attribute_name.read(local_stream, kmip_version=kmip_version) attribute_names.append(attribute_name) self._attribute_names = attribute_names if self.is_tag_next(enums.Tags.ENCODING_OPTION, local_stream): self._encoding_option = primitives.Enumeration( enum=enums.EncodingOption, tag=enums.Tags.ENCODING_OPTION ) self._encoding_option.read( local_stream, kmip_version=kmip_version ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270561
KeyWrappingSpecification.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the KeyWrappingSpecification struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_stream = BytearrayStream() if self._wrapping_method: self._wrapping_method.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Invalid struct missing the wrapping method attribute." ) if self._encryption_key_information: self._encryption_key_information.write( local_stream, kmip_version=kmip_version ) if self._mac_signature_key_information: self._mac_signature_key_information.write( local_stream, kmip_version=kmip_version ) if self._attribute_names: for unique_identifier in self._attribute_names: unique_identifier.write( local_stream, kmip_version=kmip_version ) if self._encoding_option: self._encoding_option.write( local_stream, kmip_version=kmip_version ) self.length = local_stream.length() super(KeyWrappingSpecification, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270562
ExtensionInformation.read
test
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the ExtensionInformation object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(ExtensionInformation, self).read( istream, kmip_version=kmip_version ) tstream = BytearrayStream(istream.read(self.length)) self.extension_name.read(tstream, kmip_version=kmip_version) if self.is_tag_next(Tags.EXTENSION_TAG, tstream): self.extension_tag = ExtensionTag() self.extension_tag.read(tstream, kmip_version=kmip_version) if self.is_tag_next(Tags.EXTENSION_TYPE, tstream): self.extension_type = ExtensionType() self.extension_type.read(tstream, kmip_version=kmip_version) self.is_oversized(tstream) self.validate()
python
{ "resource": "" }
q270563
ExtensionInformation.write
test
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the ExtensionInformation object to a stream. Args: ostream (Stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ tstream = BytearrayStream() self.extension_name.write(tstream, kmip_version=kmip_version) if self.extension_tag is not None: self.extension_tag.write(tstream, kmip_version=kmip_version) if self.extension_type is not None: self.extension_type.write(tstream, kmip_version=kmip_version) self.length = tstream.length() super(ExtensionInformation, self).write( ostream, kmip_version=kmip_version ) ostream.write(tstream.buffer)
python
{ "resource": "" }
q270564
ExtensionInformation.create
test
def create(cls, extension_name=None, extension_tag=None, extension_type=None): """ Construct an ExtensionInformation object from provided extension values. Args: extension_name (str): The name of the extension. Optional, defaults to None. extension_tag (int): The tag number of the extension. Optional, defaults to None. extension_type (int): The type index of the extension. Optional, defaults to None. Returns: ExtensionInformation: The newly created set of extension information. Example: >>> x = ExtensionInformation.create('extension', 1, 1) >>> x.extension_name.value ExtensionName(value='extension') >>> x.extension_tag.value ExtensionTag(value=1) >>> x.extension_type.value ExtensionType(value=1) """ extension_name = ExtensionName(extension_name) extension_tag = ExtensionTag(extension_tag) extension_type = ExtensionType(extension_type) return ExtensionInformation( extension_name=extension_name, extension_tag=extension_tag, extension_type=extension_type)
python
{ "resource": "" }
q270565
RevocationReason.read
test
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the RevocationReason object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(RevocationReason, self).read(istream, kmip_version=kmip_version) tstream = BytearrayStream(istream.read(self.length)) self.revocation_code = RevocationReasonCode() self.revocation_code.read(tstream, kmip_version=kmip_version) if self.is_tag_next(Tags.REVOCATION_MESSAGE, tstream): self.revocation_message = TextString() self.revocation_message.read(tstream, kmip_version=kmip_version) self.is_oversized(tstream) self.validate()
python
{ "resource": "" }
q270566
RevocationReason.write
test
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the RevocationReason object to a stream. Args: ostream (Stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ tstream = BytearrayStream() self.revocation_code.write(tstream, kmip_version=kmip_version) if self.revocation_message is not None: self.revocation_message.write(tstream, kmip_version=kmip_version) # Write the length and value self.length = tstream.length() super(RevocationReason, self).write(ostream, kmip_version=kmip_version) ostream.write(tstream.buffer)
python
{ "resource": "" }
q270567
RevocationReason.validate
test
def validate(self): """ validate the RevocationReason object """ if not isinstance(self.revocation_code, RevocationReasonCode): msg = "RevocationReaonCode expected" raise TypeError(msg) if self.revocation_message is not None: if not isinstance(self.revocation_message, TextString): msg = "TextString expect" raise TypeError(msg)
python
{ "resource": "" }
q270568
ObjectDefaults.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Read the data encoding the ObjectDefaults structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 2.0. Raises: InvalidKmipEncoding: Raised if the object type or attributes are missing from the encoding. VersionNotSupported: Raised when a KMIP version is provided that does not support the ObjectDefaults structure. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the ObjectDefaults object.".format( kmip_version.value ) ) super(ObjectDefaults, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer): self._object_type = primitives.Enumeration( enums.ObjectType, tag=enums.Tags.OBJECT_TYPE ) self._object_type.read(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidKmipEncoding( "The ObjectDefaults encoding is missing the object type " "enumeration." ) if self.is_tag_next(enums.Tags.ATTRIBUTES, local_buffer): self._attributes = Attributes() self._attributes.read(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidKmipEncoding( "The ObjectDefaults encoding is missing the attributes " "structure." ) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270569
ObjectDefaults.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Write the ObjectDefaults structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode Attributes structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: InvalidField: Raised if the object type or attributes fields are not defined. VersionNotSupported: Raised when a KMIP version is provided that does not support the ObjectDefaults structure. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the ObjectDefaults object.".format( kmip_version.value ) ) local_buffer = BytearrayStream() if self._object_type: self._object_type.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The ObjectDefaults structure is missing the object type " "field." ) if self._attributes: self._attributes.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The ObjectDefaults structure is missing the attributes field." ) self.length = local_buffer.length() super(ObjectDefaults, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270570
DefaultsInformation.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Read the data encoding the DefaultsInformation structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 2.0. Raises: InvalidKmipEncoding: Raised if the object defaults are missing from the encoding. VersionNotSupported: Raised when a KMIP version is provided that does not support the DefaultsInformation structure. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the DefaultsInformation " "object.".format( kmip_version.value ) ) super(DefaultsInformation, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) object_defaults = [] while self.is_tag_next(enums.Tags.OBJECT_DEFAULTS, local_buffer): object_default = ObjectDefaults() object_default.read(local_buffer, kmip_version=kmip_version) object_defaults.append(object_default) if len(object_defaults) == 0: raise exceptions.InvalidKmipEncoding( "The DefaultsInformation encoding is missing the object " "defaults structure." ) else: self._object_defaults = object_defaults self.is_oversized(local_buffer)
python
{ "resource": "" }
q270571
DefaultsInformation.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Write the DefaultsInformation structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode Attributes structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: InvalidField: Raised if the object defaults field is not defined. VersionNotSupported: Raised when a KMIP version is provided that does not support the DefaultsInformation structure. """ if kmip_version < enums.KMIPVersion.KMIP_2_0: raise exceptions.VersionNotSupported( "KMIP {} does not support the DefaultsInformation " "object.".format( kmip_version.value ) ) local_buffer = BytearrayStream() if self._object_defaults: for object_default in self._object_defaults: object_default.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The DefaultsInformation structure is missing the object " "defaults field." ) self.length = local_buffer.length() super(DefaultsInformation, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270572
RNGParameters.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Read the data encoding the RNGParameters structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 2.0. Raises: InvalidKmipEncoding: Raised if the RNG algorithm is missing from the encoding. VersionNotSupported: Raised when a KMIP version is provided that does not support the RNGParameters structure. """ if kmip_version < enums.KMIPVersion.KMIP_1_3: raise exceptions.VersionNotSupported( "KMIP {} does not support the RNGParameters object.".format( kmip_version.value ) ) super(RNGParameters, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.RNG_ALGORITHM, local_buffer): rng_algorithm = primitives.Enumeration( enums.RNGAlgorithm, tag=enums.Tags.RNG_ALGORITHM ) rng_algorithm.read(local_buffer, kmip_version=kmip_version) self._rng_algorithm = rng_algorithm else: raise exceptions.InvalidKmipEncoding( "The RNGParameters encoding is missing the RNG algorithm." ) if self.is_tag_next(enums.Tags.CRYPTOGRAPHIC_ALGORITHM, local_buffer): cryptographic_algorithm = primitives.Enumeration( enums.CryptographicAlgorithm, tag=enums.Tags.CRYPTOGRAPHIC_ALGORITHM ) cryptographic_algorithm.read( local_buffer, kmip_version=kmip_version ) self._cryptographic_algorithm = cryptographic_algorithm if self.is_tag_next(enums.Tags.CRYPTOGRAPHIC_LENGTH, local_buffer): cryptographic_length = primitives.Integer( tag=enums.Tags.CRYPTOGRAPHIC_LENGTH ) cryptographic_length.read(local_buffer, kmip_version=kmip_version) self._cryptographic_length = cryptographic_length if self.is_tag_next(enums.Tags.HASHING_ALGORITHM, local_buffer): hashing_algorithm = primitives.Enumeration( enums.HashingAlgorithm, tag=enums.Tags.HASHING_ALGORITHM ) hashing_algorithm.read(local_buffer, kmip_version=kmip_version) self._hashing_algorithm = hashing_algorithm if self.is_tag_next(enums.Tags.DRBG_ALGORITHM, local_buffer): drbg_algorithm = primitives.Enumeration( enums.DRBGAlgorithm, tag=enums.Tags.DRBG_ALGORITHM ) drbg_algorithm.read(local_buffer, kmip_version=kmip_version) self._drbg_algorithm = drbg_algorithm if self.is_tag_next(enums.Tags.RECOMMENDED_CURVE, local_buffer): recommended_curve = primitives.Enumeration( enums.RecommendedCurve, tag=enums.Tags.RECOMMENDED_CURVE ) recommended_curve.read(local_buffer, kmip_version=kmip_version) self._recommended_curve = recommended_curve if self.is_tag_next(enums.Tags.FIPS186_VARIATION, local_buffer): fips186_variation = primitives.Enumeration( enums.FIPS186Variation, tag=enums.Tags.FIPS186_VARIATION ) fips186_variation.read(local_buffer, kmip_version=kmip_version) self._fips186_variation = fips186_variation if self.is_tag_next(enums.Tags.PREDICTION_RESISTANCE, local_buffer): prediction_resistance = primitives.Boolean( tag=enums.Tags.PREDICTION_RESISTANCE ) prediction_resistance.read( local_buffer, kmip_version=kmip_version ) self._prediction_resistance = prediction_resistance self.is_oversized(local_buffer)
python
{ "resource": "" }
q270573
RNGParameters.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Write the RNGParameters structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode Attributes structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: InvalidField: Raised if the RNG algorithm field is not defined. VersionNotSupported: Raised when a KMIP version is provided that does not support the RNGParameters structure. """ if kmip_version < enums.KMIPVersion.KMIP_1_3: raise exceptions.VersionNotSupported( "KMIP {} does not support the RNGParameters object.".format( kmip_version.value ) ) local_buffer = BytearrayStream() if self._rng_algorithm: self._rng_algorithm.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The RNGParameters structure is missing the RNG algorithm " "field." ) if self._cryptographic_algorithm: self._cryptographic_algorithm.write( local_buffer, kmip_version=kmip_version ) if self._cryptographic_length: self._cryptographic_length.write( local_buffer, kmip_version=kmip_version ) if self._hashing_algorithm: self._hashing_algorithm.write( local_buffer, kmip_version=kmip_version ) if self._drbg_algorithm: self._drbg_algorithm.write( local_buffer, kmip_version=kmip_version ) if self._recommended_curve: self._recommended_curve.write( local_buffer, kmip_version=kmip_version ) if self._fips186_variation: self._fips186_variation.write( local_buffer, kmip_version=kmip_version ) if self._prediction_resistance: self._prediction_resistance.write( local_buffer, kmip_version=kmip_version ) self.length = local_buffer.length() super(RNGParameters, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270574
ProfileInformation.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Read the data encoding the ProfileInformation structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 2.0. Raises: InvalidKmipEncoding: Raised if the profile name is missing from the encoding. VersionNotSupported: Raised when a KMIP version is provided that does not support the ProfileInformation structure. """ if kmip_version < enums.KMIPVersion.KMIP_1_3: raise exceptions.VersionNotSupported( "KMIP {} does not support the ProfileInformation " "object.".format( kmip_version.value ) ) super(ProfileInformation, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.PROFILE_NAME, local_buffer): profile_name = primitives.Enumeration( enums.ProfileName, tag=enums.Tags.PROFILE_NAME ) profile_name.read(local_buffer, kmip_version=kmip_version) self._profile_name = profile_name else: raise exceptions.InvalidKmipEncoding( "The ProfileInformation encoding is missing the profile name." ) if self.is_tag_next(enums.Tags.SERVER_URI, local_buffer): server_uri = primitives.TextString(tag=enums.Tags.SERVER_URI) server_uri.read(local_buffer, kmip_version=kmip_version) self._server_uri = server_uri if self.is_tag_next(enums.Tags.SERVER_PORT, local_buffer): server_port = primitives.Integer(tag=enums.Tags.SERVER_PORT) server_port.read(local_buffer, kmip_version=kmip_version) self._server_port = server_port self.is_oversized(local_buffer)
python
{ "resource": "" }
q270575
ProfileInformation.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Write the ProfileInformation structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode ProfileInformation structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: InvalidField: Raised if the profile name field is not defined. VersionNotSupported: Raised when a KMIP version is provided that does not support the ProfileInformation structure. """ if kmip_version < enums.KMIPVersion.KMIP_1_3: raise exceptions.VersionNotSupported( "KMIP {} does not support the ProfileInformation " "object.".format( kmip_version.value ) ) local_buffer = BytearrayStream() if self._profile_name: self._profile_name.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The ProfileInformation structure is missing the profile " "name field." ) if self._server_uri: self._server_uri.write(local_buffer, kmip_version=kmip_version) if self._server_port: self._server_port.write(local_buffer, kmip_version=kmip_version) self.length = local_buffer.length() super(ProfileInformation, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270576
ValidationInformation.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Write the ValidationInformation structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode ValidationInformation structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: InvalidField: Raised if the validation authority type, validation version major, validation type, and/or validation level fields are not defined. VersionNotSupported: Raised when a KMIP version is provided that does not support the ValidationInformation structure. """ if kmip_version < enums.KMIPVersion.KMIP_1_3: raise exceptions.VersionNotSupported( "KMIP {} does not support the ValidationInformation " "object.".format( kmip_version.value ) ) local_buffer = BytearrayStream() if self._validation_authority_type: self._validation_authority_type.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The ValidationInformation structure is missing the " "validation authority type field." ) if self._validation_authority_country: self._validation_authority_country.write( local_buffer, kmip_version=kmip_version ) if self._validation_authority_uri: self._validation_authority_uri.write( local_buffer, kmip_version=kmip_version ) if self._validation_version_major: self._validation_version_major.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The ValidationInformation structure is missing the " "validation version major field." ) if self._validation_version_minor: self._validation_version_minor.write( local_buffer, kmip_version=kmip_version ) if self._validation_type: self._validation_type.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The ValidationInformation structure is missing the " "validation type field." ) if self._validation_level: self._validation_level.write( local_buffer, kmip_version=kmip_version ) else: raise exceptions.InvalidField( "The ValidationInformation structure is missing the " "validation level field." ) if self._validation_certificate_identifier: self._validation_certificate_identifier.write( local_buffer, kmip_version=kmip_version ) if self._validation_certificate_uri: self._validation_certificate_uri.write( local_buffer, kmip_version=kmip_version ) if self._validation_vendor_uri: self._validation_vendor_uri.write( local_buffer, kmip_version=kmip_version ) if self._validation_profiles: for validation_profile in self._validation_profiles: validation_profile.write( local_buffer, kmip_version=kmip_version ) self.length = local_buffer.length() super(ValidationInformation, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270577
CapabilityInformation.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Read the data encoding the CapabilityInformation structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 2.0. Raises: VersionNotSupported: Raised when a KMIP version is provided that does not support the CapabilityInformation structure. """ if kmip_version < enums.KMIPVersion.KMIP_1_3: raise exceptions.VersionNotSupported( "KMIP {} does not support the CapabilityInformation " "object.".format( kmip_version.value ) ) super(CapabilityInformation, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.STREAMING_CAPABILITY, local_buffer): streaming_capability = primitives.Boolean( tag=enums.Tags.STREAMING_CAPABILITY ) streaming_capability.read(local_buffer, kmip_version=kmip_version) self._streaming_capability = streaming_capability if self.is_tag_next(enums.Tags.ASYNCHRONOUS_CAPABILITY, local_buffer): asynchronous_capability = primitives.Boolean( tag=enums.Tags.ASYNCHRONOUS_CAPABILITY ) asynchronous_capability.read( local_buffer, kmip_version=kmip_version ) self._asynchronous_capability = asynchronous_capability if self.is_tag_next(enums.Tags.ATTESTATION_CAPABILITY, local_buffer): attestation_capability = primitives.Boolean( tag=enums.Tags.ATTESTATION_CAPABILITY ) attestation_capability.read( local_buffer, kmip_version=kmip_version ) self._attestation_capability = attestation_capability if kmip_version >= enums.KMIPVersion.KMIP_1_4: if self.is_tag_next( enums.Tags.BATCH_UNDO_CAPABILITY, local_buffer ): batch_undo_capability = primitives.Boolean( tag=enums.Tags.BATCH_UNDO_CAPABILITY ) batch_undo_capability.read( local_buffer, kmip_version=kmip_version ) self._batch_continue_capability = batch_undo_capability if self.is_tag_next( enums.Tags.BATCH_CONTINUE_CAPABILITY, local_buffer ): batch_continue_capability = primitives.Boolean( tag=enums.Tags.BATCH_CONTINUE_CAPABILITY ) batch_continue_capability.read( local_buffer, kmip_version=kmip_version ) self._batch_continue_capability = batch_continue_capability if self.is_tag_next(enums.Tags.UNWRAP_MODE, local_buffer): unwrap_mode = primitives.Enumeration( enums.UnwrapMode, tag=enums.Tags.UNWRAP_MODE ) unwrap_mode.read(local_buffer, kmip_version=kmip_version) self._unwrap_mode = unwrap_mode if self.is_tag_next(enums.Tags.DESTROY_ACTION, local_buffer): destroy_action = primitives.Enumeration( enums.DestroyAction, tag=enums.Tags.DESTROY_ACTION ) destroy_action.read(local_buffer, kmip_version=kmip_version) self._destroy_action = destroy_action if self.is_tag_next(enums.Tags.SHREDDING_ALGORITHM, local_buffer): shredding_algorithm = primitives.Enumeration( enums.ShreddingAlgorithm, tag=enums.Tags.SHREDDING_ALGORITHM ) shredding_algorithm.read(local_buffer, kmip_version=kmip_version) self._shredding_algorithm = shredding_algorithm if self.is_tag_next(enums.Tags.RNG_MODE, local_buffer): rng_mode = primitives.Enumeration( enums.RNGMode, tag=enums.Tags.RNG_MODE ) rng_mode.read(local_buffer, kmip_version=kmip_version) self._rng_mode = rng_mode self.is_oversized(local_buffer)
python
{ "resource": "" }
q270578
CapabilityInformation.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Write the CapabilityInformation structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode CapabilityInformation structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 2.0. Raises: VersionNotSupported: Raised when a KMIP version is provided that does not support the CapabilityInformation structure. """ if kmip_version < enums.KMIPVersion.KMIP_1_3: raise exceptions.VersionNotSupported( "KMIP {} does not support the CapabilityInformation " "object.".format( kmip_version.value ) ) local_buffer = BytearrayStream() if self._streaming_capability: self._streaming_capability.write( local_buffer, kmip_version=kmip_version ) if self._asynchronous_capability: self._asynchronous_capability.write( local_buffer, kmip_version=kmip_version ) if self._attestation_capability: self._attestation_capability.write( local_buffer, kmip_version=kmip_version ) if kmip_version >= enums.KMIPVersion.KMIP_1_4: if self._batch_undo_capability: self._batch_undo_capability.write( local_buffer, kmip_version=kmip_version ) if self._batch_continue_capability: self._batch_continue_capability.write( local_buffer, kmip_version=kmip_version ) if self._unwrap_mode: self._unwrap_mode.write( local_buffer, kmip_version=kmip_version ) if self._destroy_action: self._destroy_action.write( local_buffer, kmip_version=kmip_version ) if self._shredding_algorithm: self._shredding_algorithm.write( local_buffer, kmip_version=kmip_version ) if self._rng_mode: self._rng_mode.write( local_buffer, kmip_version=kmip_version ) self.length = local_buffer.length() super(CapabilityInformation, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270579
KmipServer.stop
test
def stop(self): """ Stop the server. Halt server client connections and clean up any existing connection threads. Raises: NetworkingError: Raised if a failure occurs while sutting down or closing the TLS server socket. """ self._logger.info("Cleaning up remaining connection threads.") for thread in threading.enumerate(): if thread is not threading.current_thread(): try: thread.join(10.0) except Exception as e: self._logger.info( "Error occurred while attempting to cleanup thread: " "{0}".format(thread.name) ) self._logger.exception(e) else: if thread.is_alive(): self._logger.warning( "Cleanup failed for thread: {0}. Thread is " "still alive".format(thread.name) ) else: self._logger.info( "Cleanup succeeded for thread: {0}".format( thread.name ) ) self._logger.info("Shutting down server socket handler.") try: self._socket.shutdown(socket.SHUT_RDWR) self._socket.close() except Exception as e: self._logger.exception(e) raise exceptions.NetworkingError( "Server failed to shutdown socket handler." ) if hasattr(self, "policy_monitor"): try: self.policy_monitor.stop() self.policy_monitor.join() except Exception as e: self._logger.exception(e) raise exceptions.ShutdownError( "Server failed to clean up the policy monitor." )
python
{ "resource": "" }
q270580
KmipServer.serve
test
def serve(self): """ Serve client connections. Begin listening for client connections, spinning off new KmipSessions as connections are handled. Set up signal handling to shutdown connection service as needed. """ self._socket.listen(5) def _signal_handler(signal_number, stack_frame): self._is_serving = False # Python3.5+ silently ignores SIGINT and retries system calls if # the signal handler does not raise an exception. Explicitly # detect SIGINT and raise a KeyboardInterrupt exception to regain # old functionality. if signal_number == signal.SIGINT: raise KeyboardInterrupt("SIGINT received") signal.signal(signal.SIGINT, _signal_handler) signal.signal(signal.SIGTERM, _signal_handler) self._logger.info("Starting connection service...") while self._is_serving: try: connection, address = self._socket.accept() except socket.timeout: # Setting the default socket timeout to break hung connections # will cause accept to periodically raise socket.timeout. This # is expected behavior, so ignore it and retry accept. pass except socket.error as e: self._logger.warning( "Error detected while establishing new connection." ) self._logger.exception(e) except KeyboardInterrupt: self._logger.warning("Interrupting connection service.") self._is_serving = False break except Exception as e: self._logger.warning( "Error detected while establishing new connection." ) self._logger.exception(e) else: self._setup_connection_handler(connection, address) self._logger.info("Stopping connection service.")
python
{ "resource": "" }
q270581
LocateRequestPayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Locate request payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: InvalidKmipEncoding: Raised if the attributes structure is missing from the encoded payload for KMIP 2.0+ encodings. """ super(LocateRequestPayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.MAXIMUM_ITEMS, local_buffer): self._maximum_items = primitives.Integer( tag=enums.Tags.MAXIMUM_ITEMS ) self._maximum_items.read( local_buffer, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.OFFSET_ITEMS, local_buffer): self._offset_items = primitives.Integer( tag=enums.Tags.OFFSET_ITEMS ) self._offset_items.read( local_buffer, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.STORAGE_STATUS_MASK, local_buffer): self._storage_status_mask = primitives.Integer( tag=enums.Tags.STORAGE_STATUS_MASK ) self._storage_status_mask.read( local_buffer, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.OBJECT_GROUP_MEMBER, local_buffer): self._object_group_member = primitives.Enumeration( enums.ObjectGroupMember, tag=enums.Tags.OBJECT_GROUP_MEMBER ) self._object_group_member.read( local_buffer, kmip_version=kmip_version ) if kmip_version < enums.KMIPVersion.KMIP_2_0: while self.is_tag_next(enums.Tags.ATTRIBUTE, local_buffer): attribute = objects.Attribute() attribute.read(local_buffer, kmip_version=kmip_version) self._attributes.append(attribute) else: if self.is_tag_next(enums.Tags.ATTRIBUTES, local_buffer): attributes = objects.Attributes() attributes.read(local_buffer, kmip_version=kmip_version) # TODO (ph) Add a new utility to avoid using TemplateAttributes temp_attr = objects.convert_attributes_to_template_attribute( attributes ) self._attributes = temp_attr.attributes else: raise exceptions.InvalidKmipEncoding( "The Locate request payload encoding is missing the " "attributes structure." )
python
{ "resource": "" }
q270582
LocateRequestPayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Locate request payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_buffer = utils.BytearrayStream() if self._maximum_items: self._maximum_items.write(local_buffer, kmip_version=kmip_version) if self._offset_items: self._offset_items.write(local_buffer, kmip_version=kmip_version) if self._storage_status_mask: self._storage_status_mask.write( local_buffer, kmip_version=kmip_version ) if self._object_group_member: self._object_group_member.write( local_buffer, kmip_version=kmip_version ) if kmip_version < enums.KMIPVersion.KMIP_2_0: if self._attributes: for attribute in self.attributes: attribute.write( local_buffer, kmip_version=kmip_version ) else: if self._attributes: # TODO (ph) Add a new utility to avoid using TemplateAttributes template_attribute = objects.TemplateAttribute( attributes=self.attributes ) attributes = objects.convert_template_attribute_to_attributes( template_attribute ) attributes.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The Locate request payload is missing the attributes " "list." ) self.length = local_buffer.length() super(LocateRequestPayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270583
LocateResponsePayload.read
test
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Locate response payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. """ super(LocateResponsePayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.LOCATED_ITEMS, local_buffer): self._located_items = primitives.Integer( tag=enums.Tags.LOCATED_ITEMS ) self._located_items.read( local_buffer, kmip_version=kmip_version ) self._unique_identifiers = [] while self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer): unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) unique_identifier.read(local_buffer, kmip_version=kmip_version) self._unique_identifiers.append(unique_identifier) self.is_oversized(local_buffer)
python
{ "resource": "" }
q270584
LocateResponsePayload.write
test
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Locate response payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0. """ local_buffer = utils.BytearrayStream() if self._located_items: self._located_items.write(local_buffer, kmip_version=kmip_version) if self._unique_identifiers: for unique_identifier in self._unique_identifiers: unique_identifier.write( local_buffer, kmip_version=kmip_version ) self.length = local_buffer.length() super(LocateResponsePayload, self).write( output_buffer, kmip_version=kmip_version ) output_buffer.write(local_buffer.buffer)
python
{ "resource": "" }
q270585
CryptographyEngine.create_symmetric_key
test
def create_symmetric_key(self, algorithm, length): """ Create a symmetric key. Args: algorithm(CryptographicAlgorithm): An enumeration specifying the algorithm for which the created key will be compliant. length(int): The length of the key to be created. This value must be compliant with the constraints of the provided algorithm. Returns: dict: A dictionary containing the key data, with the following key/value fields: * value - the bytes of the key * format - a KeyFormatType enumeration for the bytes format Raises: InvalidField: Raised when the algorithm is unsupported or the length is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. Example: >>> engine = CryptographyEngine() >>> key = engine.create_symmetric_key( ... CryptographicAlgorithm.AES, 256) """ if algorithm not in self._symmetric_key_algorithms.keys(): raise exceptions.InvalidField( "The cryptographic algorithm {0} is not a supported symmetric " "key algorithm.".format(algorithm) ) cryptography_algorithm = self._symmetric_key_algorithms.get(algorithm) if length not in cryptography_algorithm.key_sizes: raise exceptions.InvalidField( "The cryptographic length ({0}) is not valid for " "the cryptographic algorithm ({1}).".format( length, algorithm.name ) ) self.logger.info( "Generating a {0} symmetric key with length: {1}".format( algorithm.name, length ) ) key_bytes = os.urandom(length // 8) try: cryptography_algorithm(key_bytes) except Exception as e: self.logger.exception(e) raise exceptions.CryptographicFailure( "Invalid bytes for the provided cryptographic algorithm.") return {'value': key_bytes, 'format': enums.KeyFormatType.RAW}
python
{ "resource": "" }
q270586
CryptographyEngine.create_asymmetric_key_pair
test
def create_asymmetric_key_pair(self, algorithm, length): """ Create an asymmetric key pair. Args: algorithm(CryptographicAlgorithm): An enumeration specifying the algorithm for which the created keys will be compliant. length(int): The length of the keys to be created. This value must be compliant with the constraints of the provided algorithm. Returns: dict: A dictionary containing the public key data, with at least the following key/value fields: * value - the bytes of the key * format - a KeyFormatType enumeration for the bytes format dict: A dictionary containing the private key data, identical in structure to the one above. Raises: InvalidField: Raised when the algorithm is unsupported or the length is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. Example: >>> engine = CryptographyEngine() >>> key = engine.create_asymmetric_key( ... CryptographicAlgorithm.RSA, 2048) """ if algorithm not in self._asymmetric_key_algorithms.keys(): raise exceptions.InvalidField( "The cryptographic algorithm ({0}) is not a supported " "asymmetric key algorithm.".format(algorithm) ) engine_method = self._asymmetric_key_algorithms.get(algorithm) return engine_method(length)
python
{ "resource": "" }
q270587
CryptographyEngine.mac
test
def mac(self, algorithm, key, data): """ Generate message authentication code. Args: algorithm(CryptographicAlgorithm): An enumeration specifying the algorithm for which the MAC operation will use. key(bytes): secret key used in the MAC operation data(bytes): The data to be MACed. Returns: bytes: The MACed data Raises: InvalidField: Raised when the algorithm is unsupported or the length is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. Example: >>> engine = CryptographyEngine() >>> mac_data = engine.mac( ... CryptographicAlgorithm.HMAC-SHA256, b'\x01\x02\x03\x04', ... b'\x05\x06\x07\x08') """ mac_data = None if algorithm in self._hash_algorithms.keys(): self.logger.info( "Generating a hash-based message authentication code using " "{0}".format(algorithm.name) ) hash_algorithm = self._hash_algorithms.get(algorithm) try: h = hmac.HMAC(key, hash_algorithm(), backend=default_backend()) h.update(data) mac_data = h.finalize() except Exception as e: self.logger.exception(e) raise exceptions.CryptographicFailure( "An error occurred while computing an HMAC. " "See the server log for more information." ) elif algorithm in self._symmetric_key_algorithms.keys(): self.logger.info( "Generating a cipher-based message authentication code using " "{0}".format(algorithm.name) ) cipher_algorithm = self._symmetric_key_algorithms.get(algorithm) try: # ARC4 and IDEA algorithms will raise exception as CMAC # requires block ciphers c = cmac.CMAC(cipher_algorithm(key), backend=default_backend()) c.update(data) mac_data = c.finalize() except Exception as e: raise exceptions.CryptographicFailure( "An error occurred while computing a CMAC. " "See the server log for more information." ) else: raise exceptions.InvalidField( "The cryptographic algorithm ({0}) is not a supported " "for a MAC operation.".format(algorithm) ) return mac_data
python
{ "resource": "" }
q270588
CryptographyEngine.encrypt
test
def encrypt(self, encryption_algorithm, encryption_key, plain_text, cipher_mode=None, padding_method=None, iv_nonce=None, hashing_algorithm=None): """ Encrypt data using symmetric or asymmetric encryption. Args: encryption_algorithm (CryptographicAlgorithm): An enumeration specifying the encryption algorithm to use for encryption. encryption_key (bytes): The bytes of the encryption key to use for encryption. plain_text (bytes): The bytes to be encrypted. cipher_mode (BlockCipherMode): An enumeration specifying the block cipher mode to use with the encryption algorithm. Required in the general case. Optional if the encryption algorithm is RC4 (aka ARC4). If optional, defaults to None. padding_method (PaddingMethod): An enumeration specifying the padding method to use on the data before encryption. Required if the cipher mode is for block ciphers (e.g., CBC, ECB). Optional otherwise, defaults to None. iv_nonce (bytes): The IV/nonce value to use to initialize the mode of the encryption algorithm. Optional, defaults to None. If required and not provided, it will be autogenerated and returned with the cipher text. hashing_algorithm (HashingAlgorithm): An enumeration specifying the hashing algorithm to use with the encryption algorithm, if needed. Required for OAEP-based asymmetric encryption. Optional, defaults to None. Returns: dict: A dictionary containing the encrypted data, with at least the following key/value fields: * cipher_text - the bytes of the encrypted data * iv_nonce - the bytes of the IV/counter/nonce used if it was needed by the encryption scheme and if it was automatically generated for the encryption Raises: InvalidField: Raised when the algorithm is unsupported or the length is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. Example: >>> engine = CryptographyEngine() >>> result = engine.encrypt( ... encryption_algorithm=CryptographicAlgorithm.AES, ... encryption_key=( ... b'\xF3\x96\xE7\x1C\xCF\xCD\xEC\x1F' ... b'\xFC\xE2\x8E\xA6\xF8\x74\x28\xB0' ... ), ... plain_text=( ... b'\x00\x01\x02\x03\x04\x05\x06\x07' ... b'\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' ... ), ... cipher_mode=BlockCipherMode.CBC, ... padding_method=PaddingMethod.ANSI_X923, ... ) >>> result.get('cipher_text') b'\x18[\xb9y\x1bL\xd1\x8f\x9a\xa0e\x02b\xa3=c' >>> result.iv_counter_nonce b'8qA\x05\xc4\x86\x03\xd9=\xef\xdf\xb8ke\x9a\xa2' """ if encryption_algorithm is None: raise exceptions.InvalidField("Encryption algorithm is required.") if encryption_algorithm == enums.CryptographicAlgorithm.RSA: return self._encrypt_asymmetric( encryption_algorithm, encryption_key, plain_text, padding_method, hashing_algorithm=hashing_algorithm ) else: return self._encrypt_symmetric( encryption_algorithm, encryption_key, plain_text, cipher_mode=cipher_mode, padding_method=padding_method, iv_nonce=iv_nonce )
python
{ "resource": "" }
q270589
CryptographyEngine._encrypt_symmetric
test
def _encrypt_symmetric( self, encryption_algorithm, encryption_key, plain_text, cipher_mode=None, padding_method=None, iv_nonce=None): """ Encrypt data using symmetric encryption. Args: encryption_algorithm (CryptographicAlgorithm): An enumeration specifying the symmetric encryption algorithm to use for encryption. encryption_key (bytes): The bytes of the symmetric key to use for encryption. plain_text (bytes): The bytes to be encrypted. cipher_mode (BlockCipherMode): An enumeration specifying the block cipher mode to use with the encryption algorithm. Required in the general case. Optional if the encryption algorithm is RC4 (aka ARC4). If optional, defaults to None. padding_method (PaddingMethod): An enumeration specifying the padding method to use on the data before encryption. Required if the cipher mode is for block ciphers (e.g., CBC, ECB). Optional otherwise, defaults to None. iv_nonce (bytes): The IV/nonce value to use to initialize the mode of the encryption algorithm. Optional, defaults to None. If required and not provided, it will be autogenerated and returned with the cipher text. Returns: dict: A dictionary containing the encrypted data, with at least the following key/value fields: * cipher_text - the bytes of the encrypted data * iv_nonce - the bytes of the IV/counter/nonce used if it was needed by the encryption scheme and if it was automatically generated for the encryption Raises: InvalidField: Raised when the algorithm is unsupported or the encryption key is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. """ # Set up the algorithm algorithm = self._symmetric_key_algorithms.get( encryption_algorithm, None ) if algorithm is None: raise exceptions.InvalidField( "Encryption algorithm '{0}' is not a supported symmetric " "encryption algorithm.".format(encryption_algorithm) ) try: algorithm = algorithm(encryption_key) except Exception as e: self.logger.exception(e) raise exceptions.CryptographicFailure( "Invalid key bytes for the specified encryption algorithm." ) # Set up the cipher mode if needed return_iv_nonce = False if encryption_algorithm == enums.CryptographicAlgorithm.RC4: mode = None else: if cipher_mode is None: raise exceptions.InvalidField("Cipher mode is required.") mode = self._modes.get(cipher_mode, None) if mode is None: raise exceptions.InvalidField( "Cipher mode '{0}' is not a supported mode.".format( cipher_mode ) ) if hasattr(mode, 'initialization_vector') or \ hasattr(mode, 'nonce'): if iv_nonce is None: iv_nonce = os.urandom(algorithm.block_size // 8) return_iv_nonce = True mode = mode(iv_nonce) else: mode = mode() # Pad the plain text if needed (separate methods for testing purposes) if cipher_mode in [ enums.BlockCipherMode.CBC, enums.BlockCipherMode.ECB ]: plain_text = self._handle_symmetric_padding( self._symmetric_key_algorithms.get(encryption_algorithm), plain_text, padding_method ) # Encrypt the plain text cipher = ciphers.Cipher(algorithm, mode, backend=default_backend()) encryptor = cipher.encryptor() cipher_text = encryptor.update(plain_text) + encryptor.finalize() if return_iv_nonce: return { 'cipher_text': cipher_text, 'iv_nonce': iv_nonce } else: return {'cipher_text': cipher_text}
python
{ "resource": "" }
q270590
CryptographyEngine._encrypt_asymmetric
test
def _encrypt_asymmetric(self, encryption_algorithm, encryption_key, plain_text, padding_method, hashing_algorithm=None): """ Encrypt data using asymmetric encryption. Args: encryption_algorithm (CryptographicAlgorithm): An enumeration specifying the asymmetric encryption algorithm to use for encryption. Required. encryption_key (bytes): The bytes of the public key to use for encryption. Required. plain_text (bytes): The bytes to be encrypted. Required. padding_method (PaddingMethod): An enumeration specifying the padding method to use with the asymmetric encryption algorithm. Required. hashing_algorithm (HashingAlgorithm): An enumeration specifying the hashing algorithm to use with the encryption padding method. Required, if the padding method is OAEP. Optional otherwise, defaults to None. Returns: dict: A dictionary containing the encrypted data, with at least the following key/value field: * cipher_text - the bytes of the encrypted data Raises: InvalidField: Raised when the algorithm is unsupported or the length is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. """ if encryption_algorithm == enums.CryptographicAlgorithm.RSA: if padding_method == enums.PaddingMethod.OAEP: hash_algorithm = self._encryption_hash_algorithms.get( hashing_algorithm ) if hash_algorithm is None: raise exceptions.InvalidField( "The hashing algorithm '{0}' is not supported for " "asymmetric encryption.".format(hashing_algorithm) ) padding_method = asymmetric_padding.OAEP( mgf=asymmetric_padding.MGF1( algorithm=hash_algorithm() ), algorithm=hash_algorithm(), label=None ) elif padding_method == enums.PaddingMethod.PKCS1v15: padding_method = asymmetric_padding.PKCS1v15() else: raise exceptions.InvalidField( "The padding method '{0}' is not supported for asymmetric " "encryption.".format(padding_method) ) backend = default_backend() try: public_key = backend.load_der_public_key(encryption_key) except Exception: try: public_key = backend.load_pem_public_key(encryption_key) except Exception: raise exceptions.CryptographicFailure( "The public key bytes could not be loaded." ) cipher_text = public_key.encrypt( plain_text, padding_method ) return {'cipher_text': cipher_text} else: raise exceptions.InvalidField( "The cryptographic algorithm '{0}' is not supported for " "asymmetric encryption.".format(encryption_algorithm) )
python
{ "resource": "" }
q270591
CryptographyEngine._decrypt_asymmetric
test
def _decrypt_asymmetric( self, decryption_algorithm, decryption_key, cipher_text, padding_method, hashing_algorithm=None): """ Encrypt data using asymmetric decryption. Args: decryption_algorithm (CryptographicAlgorithm): An enumeration specifying the asymmetric decryption algorithm to use for decryption. Required. decryption_key (bytes): The bytes of the private key to use for decryption. Required. cipher_text (bytes): The bytes to be decrypted. Required. padding_method (PaddingMethod): An enumeration specifying the padding method to use with the asymmetric decryption algorithm. Required. hashing_algorithm (HashingAlgorithm): An enumeration specifying the hashing algorithm to use with the decryption padding method. Required, if the padding method is OAEP. Optional otherwise, defaults to None. Returns: dict: A dictionary containing the decrypted data, with at least the following key/value field: * plain_text - the bytes of the decrypted data Raises: InvalidField: Raised when the algorithm is unsupported or the length is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. """ if decryption_algorithm == enums.CryptographicAlgorithm.RSA: if padding_method == enums.PaddingMethod.OAEP: hash_algorithm = self._encryption_hash_algorithms.get( hashing_algorithm ) if hash_algorithm is None: raise exceptions.InvalidField( "The hashing algorithm '{0}' is not supported for " "asymmetric decryption.".format(hashing_algorithm) ) padding_method = asymmetric_padding.OAEP( mgf=asymmetric_padding.MGF1( algorithm=hash_algorithm() ), algorithm=hash_algorithm(), label=None ) elif padding_method == enums.PaddingMethod.PKCS1v15: padding_method = asymmetric_padding.PKCS1v15() else: raise exceptions.InvalidField( "The padding method '{0}' is not supported for asymmetric " "decryption.".format(padding_method) ) backend = default_backend() try: private_key = backend.load_der_private_key( decryption_key, None ) except Exception: try: private_key = backend.load_pem_private_key( decryption_key, None ) except Exception: raise exceptions.CryptographicFailure( "The private key bytes could not be loaded." ) plain_text = private_key.decrypt( cipher_text, padding_method ) return plain_text else: raise exceptions.InvalidField( "The cryptographic algorithm '{0}' is not supported for " "asymmetric decryption.".format(decryption_algorithm) )
python
{ "resource": "" }
q270592
CryptographyEngine._create_rsa_key_pair
test
def _create_rsa_key_pair(self, length, public_exponent=65537): """ Create an RSA key pair. Args: length(int): The length of the keys to be created. This value must be compliant with the constraints of the provided algorithm. public_exponent(int): The value of the public exponent needed to generate the keys. Usually a small Fermat prime number. Optional, defaults to 65537. Returns: dict: A dictionary containing the public key data, with the following key/value fields: * value - the bytes of the key * format - a KeyFormatType enumeration for the bytes format * public_exponent - the public exponent integer dict: A dictionary containing the private key data, identical in structure to the one above. Raises: CryptographicFailure: Raised when the key generation process fails. """ self.logger.info( "Generating an RSA key pair with length: {0}, and " "public_exponent: {1}".format( length, public_exponent ) ) try: private_key = rsa.generate_private_key( public_exponent=public_exponent, key_size=length, backend=default_backend()) public_key = private_key.public_key() private_bytes = private_key.private_bytes( serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) public_bytes = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1) except Exception as e: self.logger.exception(e) raise exceptions.CryptographicFailure( "An error occurred while generating the RSA key pair. " "See the server log for more information." ) public_key = { 'value': public_bytes, 'format': enums.KeyFormatType.PKCS_1, 'public_exponent': public_exponent } private_key = { 'value': private_bytes, 'format': enums.KeyFormatType.PKCS_8, 'public_exponent': public_exponent } return public_key, private_key
python
{ "resource": "" }
q270593
CryptographyEngine.derive_key
test
def derive_key(self, derivation_method, derivation_length, derivation_data=None, key_material=None, hash_algorithm=None, salt=None, iteration_count=None, encryption_algorithm=None, cipher_mode=None, padding_method=None, iv_nonce=None): """ Derive key data using a variety of key derivation functions. Args: derivation_method (DerivationMethod): An enumeration specifying the key derivation method to use. Required. derivation_length (int): An integer specifying the size of the derived key data in bytes. Required. derivation_data (bytes): The non-cryptographic bytes to be used in the key derivation process (e.g., the data to be encrypted, hashed, HMACed). Required in the general case. Optional if the derivation method is Hash and the key material is provided. Optional, defaults to None. key_material (bytes): The bytes of the key material to use for key derivation. Required in the general case. Optional if the derivation_method is HASH and derivation_data is provided. Optional, defaults to None. hash_algorithm (HashingAlgorithm): An enumeration specifying the hashing algorithm to use with the key derivation method. Required in the general case, optional if the derivation method specifies encryption. Optional, defaults to None. salt (bytes): Bytes representing a randomly generated salt. Required if the derivation method is PBKDF2. Optional, defaults to None. iteration_count (int): An integer representing the number of iterations to use when deriving key material. Required if the derivation method is PBKDF2. Optional, defaults to None. encryption_algorithm (CryptographicAlgorithm): An enumeration specifying the symmetric encryption algorithm to use for encryption-based key derivation. Required if the derivation method specifies encryption. Optional, defaults to None. cipher_mode (BlockCipherMode): An enumeration specifying the block cipher mode to use with the encryption algorithm. Required in in the general case if the derivation method specifies encryption and the encryption algorithm is specified. Optional if the encryption algorithm is RC4 (aka ARC4). Optional, defaults to None. padding_method (PaddingMethod): An enumeration specifying the padding method to use on the data before encryption. Required in in the general case if the derivation method specifies encryption and the encryption algorithm is specified. Required if the cipher mode is for block ciphers (e.g., CBC, ECB). Optional otherwise, defaults to None. iv_nonce (bytes): The IV/nonce value to use to initialize the mode of the encryption algorithm. Required in the general case if the derivation method specifies encryption and the encryption algorithm is specified. Optional, defaults to None. If required and not provided, it will be autogenerated. Returns: bytes: the bytes of the derived data Raises: InvalidField: Raised when cryptographic data and/or settings are unsupported or incompatible with the derivation method. Example: >>> engine = CryptographyEngine() >>> result = engine.derive_key( ... derivation_method=enums.DerivationMethod.HASH, ... derivation_length=16, ... derivation_data=b'abc', ... hash_algorithm=enums.HashingAlgorithm.MD5 ... ) >>> result b'\x90\x01P\x98<\xd2O\xb0\xd6\x96?}(\xe1\x7fr' """ if derivation_method == enums.DerivationMethod.ENCRYPT: result = self.encrypt( encryption_algorithm=encryption_algorithm, encryption_key=key_material, plain_text=derivation_data, cipher_mode=cipher_mode, padding_method=padding_method, iv_nonce=iv_nonce ) return result.get('cipher_text') else: # Handle key derivation functions that use hash algorithms # Set up the hashing algorithm if hash_algorithm is None: raise exceptions.InvalidField("Hash algorithm is required.") hashing_algorithm = self._encryption_hash_algorithms.get( hash_algorithm, None ) if hashing_algorithm is None: raise exceptions.InvalidField( "Hash algorithm '{0}' is not a supported hashing " "algorithm.".format(hash_algorithm) ) if derivation_method == enums.DerivationMethod.HMAC: df = hkdf.HKDF( algorithm=hashing_algorithm(), length=derivation_length, salt=salt, info=derivation_data, backend=default_backend() ) derived_data = df.derive(key_material) return derived_data elif derivation_method == enums.DerivationMethod.HASH: if None not in [derivation_data, key_material]: raise exceptions.InvalidField( "For hash-based key derivation, specify only " "derivation data or key material, not both." ) elif derivation_data is not None: hashing_data = derivation_data elif key_material is not None: hashing_data = key_material else: raise exceptions.InvalidField( "For hash-based key derivation, derivation data or " "key material must be specified." ) df = hashes.Hash( algorithm=hashing_algorithm(), backend=default_backend() ) df.update(hashing_data) derived_data = df.finalize() return derived_data elif derivation_method == enums.DerivationMethod.PBKDF2: if salt is None: raise exceptions.InvalidField( "For PBKDF2 key derivation, salt must be specified." ) if iteration_count is None: raise exceptions.InvalidField( "For PBKDF2 key derivation, iteration count must be " "specified." ) df = pbkdf2.PBKDF2HMAC( algorithm=hashing_algorithm(), length=derivation_length, salt=salt, iterations=iteration_count, backend=default_backend() ) derived_data = df.derive(key_material) return derived_data elif derivation_method == enums.DerivationMethod.NIST800_108_C: df = kbkdf.KBKDFHMAC( algorithm=hashing_algorithm(), mode=kbkdf.Mode.CounterMode, length=derivation_length, rlen=4, llen=None, location=kbkdf.CounterLocation.BeforeFixed, label=None, context=None, fixed=derivation_data, backend=default_backend() ) derived_data = df.derive(key_material) return derived_data else: raise exceptions.InvalidField( "Derivation method '{0}' is not a supported key " "derivation method.".format(derivation_method) )
python
{ "resource": "" }
q270594
CryptographyEngine._create_RSA_private_key
test
def _create_RSA_private_key(self, bytes): """ Instantiates an RSA key from bytes. Args: bytes (byte string): Bytes of RSA private key. Returns: private_key (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey): RSA private key created from key bytes. """ try: private_key = serialization.load_pem_private_key( bytes, password=None, backend=default_backend() ) return private_key except Exception: private_key = serialization.load_der_private_key( bytes, password=None, backend=default_backend() ) return private_key
python
{ "resource": "" }
q270595
CryptographyEngine.verify_signature
test
def verify_signature(self, signing_key, message, signature, padding_method, signing_algorithm=None, hashing_algorithm=None, digital_signature_algorithm=None): """ Verify a message signature. Args: signing_key (bytes): The bytes of the signing key to use for signature verification. Required. message (bytes): The bytes of the message that corresponds with the signature. Required. signature (bytes): The bytes of the signature to be verified. Required. padding_method (PaddingMethod): An enumeration specifying the padding method to use during signature verification. Required. signing_algorithm (CryptographicAlgorithm): An enumeration specifying the cryptographic algorithm to use for signature verification. Only RSA is supported. Optional, must match the algorithm specified by the digital signature algorithm if both are provided. Defaults to None. hashing_algorithm (HashingAlgorithm): An enumeration specifying the hashing algorithm to use with the cryptographic algortihm, if needed. Optional, must match the algorithm specified by the digital signature algorithm if both are provided. Defaults to None. digital_signature_algorithm (DigitalSignatureAlgorithm): An enumeration specifying both the cryptographic and hashing algorithms to use for signature verification. Optional, must match the cryptographic and hashing algorithms if both are provided. Defaults to None. Returns: boolean: the result of signature verification, True for valid signatures, False for invalid signatures Raises: InvalidField: Raised when various settings or values are invalid. CryptographicFailure: Raised when the signing key bytes cannot be loaded, or when the signature verification process fails unexpectedly. """ backend = default_backend() hash_algorithm = None dsa_hash_algorithm = None dsa_signing_algorithm = None if hashing_algorithm: hash_algorithm = self._encryption_hash_algorithms.get( hashing_algorithm ) if digital_signature_algorithm: algorithm_pair = self._digital_signature_algorithms.get( digital_signature_algorithm ) if algorithm_pair: dsa_hash_algorithm = algorithm_pair[0] dsa_signing_algorithm = algorithm_pair[1] if dsa_hash_algorithm and dsa_signing_algorithm: if hash_algorithm and (hash_algorithm != dsa_hash_algorithm): raise exceptions.InvalidField( "The hashing algorithm does not match the digital " "signature algorithm." ) if (signing_algorithm and (signing_algorithm != dsa_signing_algorithm)): raise exceptions.InvalidField( "The signing algorithm does not match the digital " "signature algorithm." ) signing_algorithm = dsa_signing_algorithm hash_algorithm = dsa_hash_algorithm if signing_algorithm == enums.CryptographicAlgorithm.RSA: if padding_method == enums.PaddingMethod.PSS: if hash_algorithm: padding = asymmetric_padding.PSS( mgf=asymmetric_padding.MGF1(hash_algorithm()), salt_length=asymmetric_padding.PSS.MAX_LENGTH ) else: raise exceptions.InvalidField( "A hashing algorithm must be specified for PSS " "padding." ) elif padding_method == enums.PaddingMethod.PKCS1v15: padding = asymmetric_padding.PKCS1v15() else: raise exceptions.InvalidField( "The padding method '{0}' is not supported for signature " "verification.".format(padding_method) ) try: public_key = backend.load_der_public_key(signing_key) except Exception: try: public_key = backend.load_pem_public_key(signing_key) except Exception: raise exceptions.CryptographicFailure( "The signing key bytes could not be loaded." ) try: public_key.verify( signature, message, padding, hash_algorithm() ) return True except errors.InvalidSignature: return False except Exception: raise exceptions.CryptographicFailure( "The signature verification process failed." ) else: raise exceptions.InvalidField( "The signing algorithm '{0}' is not supported for " "signature verification.".format(signing_algorithm) )
python
{ "resource": "" }
q270596
SignResponsePayload.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Sign response payload and decode it. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the unique_identifier or signature attributes are missing from the encoded payload. """ super(SignResponsePayload, self).read( input_stream, kmip_version=kmip_version ) local_stream = utils.BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_stream, kmip_version=kmip_version ) else: raise ValueError( "invalid payload missing the unique identifier attribute" ) if self.is_tag_next(enums.Tags.SIGNATURE_DATA, local_stream): self._signature_data = primitives.ByteString( tag=enums.Tags.SIGNATURE_DATA ) self._signature_data.read(local_stream, kmip_version=kmip_version) else: raise ValueError( "invalid payload missing the signature data attribute" )
python
{ "resource": "" }
q270597
SignResponsePayload.write
test
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Sign response to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. Raises: ValueError: Raised if the unique_identifier or signature attributes are not defined. """ local_stream = utils.BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "invalid payload missing the unique identifier attribute" ) if self._signature_data: self._signature_data.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "invalid payload missing the signature attribute" ) self.length = local_stream.length() super(SignResponsePayload, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
python
{ "resource": "" }
q270598
GetUsageAllocationRequestPayload.read
test
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the GetUsageAllocation request payload and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the data attribute is missing from the encoded payload. """ super(GetUsageAllocationRequestPayload, self).read( input_stream, kmip_version=kmip_version ) local_stream = utils.BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_stream, kmip_version=kmip_version ) if self.is_tag_next(enums.Tags.USAGE_LIMITS_COUNT, local_stream): self._usage_limits_count = primitives.LongInteger( tag=enums.Tags.USAGE_LIMITS_COUNT ) self._usage_limits_count.read( local_stream, kmip_version=kmip_version ) self.is_oversized(local_stream)
python
{ "resource": "" }
q270599
protocol_version_to_kmip_version
test
def protocol_version_to_kmip_version(value): """ Convert a ProtocolVersion struct to its KMIPVersion enumeration equivalent. Args: value (ProtocolVersion): A ProtocolVersion struct to be converted into a KMIPVersion enumeration. Returns: KMIPVersion: The enumeration equivalent of the struct. If the struct cannot be converted to a valid enumeration, None is returned. """ if not isinstance(value, ProtocolVersion): return None if value.major == 1: if value.minor == 0: return enums.KMIPVersion.KMIP_1_0 elif value.minor == 1: return enums.KMIPVersion.KMIP_1_1 elif value.minor == 2: return enums.KMIPVersion.KMIP_1_2 elif value.minor == 3: return enums.KMIPVersion.KMIP_1_3 elif value.minor == 4: return enums.KMIPVersion.KMIP_1_4 else: return None else: return None
python
{ "resource": "" }