def process_request(self, request, credential=None):
        """
        Process a KMIP request message.

        This routine is the main driver of the KmipEngine. It breaks apart and
        processes the request header, handles any message errors that may
        result, and then passes the set of request batch items on for
        processing. This routine is thread-safe, allowing multiple client
        connections to use the same KmipEngine.

        Args:
            request (RequestMessage): The request message containing the batch
                items to be processed.
            credential (string): Identifying information about the client
                obtained from the client certificate. Optional, defaults to
                None.

        Returns:
            ResponseMessage: The response containing all of the results from
                the request batch items.
        """
        self._client_identity = [None, None]
        header = request.request_header

        # Process the protocol version
        self._set_protocol_version(header.protocol_version)

        # Process the maximum response size
        max_response_size = None
        if header.maximum_response_size:
            max_response_size = header.maximum_response_size.value

        # Process the time stamp
        now = int(time.time())
        if header.time_stamp:
            then = header.time_stamp.value

            if (now >= then) and ((now - then) < 60):
                self._logger.info("Received request at time: {0}".format(
                    time.strftime(
                        "%Y-%m-%d %H:%M:%S",
                        time.gmtime(then)
                    )
                ))
            else:
                if now < then:
                    self._logger.warning(
                        "Received request with future timestamp. Received "
                        "timestamp: {0}, Current timestamp: {1}".format(
                            then,
                            now
                        )
                    )

                    raise exceptions.InvalidMessage(
                        "Future request rejected by server."
                    )
                else:
                    self._logger.warning(
                        "Received request with old timestamp. Possible "
                        "replay attack. Received timestamp: {0}, Current "
                        "timestamp: {1}".format(then, now)
                    )

                    raise exceptions.InvalidMessage(
                        "Stale request rejected by server."
                    )
        else:
            self._logger.info("Received request at time: {0}".format(
                time.strftime(
                    "%Y-%m-%d %H:%M:%S",
                    time.gmtime(now)
                )
            ))

        # Process the asynchronous indicator
        self.is_asynchronous = False
        if header.asynchronous_indicator is not None:
            self.is_asynchronous = header.asynchronous_indicator.value

        if self.is_asynchronous:
            raise exceptions.InvalidMessage(
                "Asynchronous operations are not supported."
            )

        # Process the authentication credentials
        if header.authentication:
            if header.authentication.credentials:
                auth_credentials = header.authentication.credentials[0]
            else:
                auth_credentials = None
        else:
            auth_credentials = None

        self._verify_credential(auth_credentials, credential)

        # Process the batch error continuation option
        batch_error_option = enums.BatchErrorContinuationOption.STOP
        if header.batch_error_cont_option is not None:
            batch_error_option = header.batch_error_cont_option.value

        if batch_error_option == enums.BatchErrorContinuationOption.UNDO:
            raise exceptions.InvalidMessage(
                "Undo option for batch handling is not supported."
            )

        # Process the batch order option
        batch_order_option = False
        if header.batch_order_option:
            batch_order_option = header.batch_order_option.value

        response_batch = self._process_batch(
            request.batch_items,
            batch_error_option,
            batch_order_option
        )
        response = self._build_response(
            header.protocol_version,
            response_batch
        )

        return response, max_response_size, header.protocol_version


def build_error_response(self, version, reason, message):
        """
        Build a simple ResponseMessage with a single error result.

        Args:
            version (ProtocolVersion): The protocol version the response
                should be addressed with.
            reason (ResultReason): An enumeration classifying the type of
                error occurred.
            message (str): A string providing additional information about
                the error.

        Returns:
            ResponseMessage: The simple ResponseMessage containing a
                single error result.
        """
        batch_item = messages.ResponseBatchItem(
            result_status=contents.ResultStatus(
                enums.ResultStatus.OPERATION_FAILED
            ),
            result_reason=contents.ResultReason(reason),
            result_message=contents.ResultMessage(message)
        )
        return self._build_response(version, [batch_item])

def build_error_response ( self , version , reason , message ) : batch_item = messages . ResponseBatchItem ( result_status = contents . ResultStatus ( enums . ResultStatus . OPERATION_FAILED ) , result_reason = contents . ResultReason ( reason ) , result_message = contents . ResultMessage ( message ) ) return self . _build_response ( version , [ batch_item ] )

Build a simple ResponseMessage with a single error result .


def _process_template_attribute(self, template_attribute):
        """
        Given a kmip.core TemplateAttribute object, extract the attribute
        value data into a usable dictionary format.
        """
        attributes = {}

        if len(template_attribute.names) > 0:
            raise exceptions.ItemNotFound(
                "Attribute templates are not supported."
            )

        for attribute in template_attribute.attributes:
            name = attribute.attribute_name.value

            if not self._attribute_policy.is_attribute_supported(name):
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(name)
                )

            if self._attribute_policy.is_attribute_multivalued(name):
                values = attributes.get(name, list())
                if (not attribute.attribute_index) and len(values) > 0:
                    raise exceptions.InvalidField(
                        "Attribute index missing from multivalued attribute."
                    )

                values.append(attribute.attribute_value)
                attributes.update([(name, values)])
            else:
                if attribute.attribute_index:
                    if attribute.attribute_index.value != 0:
                        raise exceptions.InvalidField(
                            "Non-zero attribute index found for "
                            "single-valued attribute."
                        )
                value = attributes.get(name, None)
                if value:
                    raise exceptions.IndexOutOfBounds(
                        "Cannot set multiple instances of the "
                        "{0} attribute.".format(name)
                    )
                else:
                    attributes.update([(name, attribute.attribute_value)])

        return attributes

Given a kmip . core TemplateAttribute object extract the attribute value data into a usable dictionary format .


def _get_attributes_from_managed_object(self, managed_object, attr_names):
        """
        Given a kmip.pie object and a list of attribute names, attempt to get
        all of the existing attribute values from the object.
        """
        attr_factory = attribute_factory.AttributeFactory()
        retrieved_attributes = list()

        if not attr_names:
            attr_names = self._attribute_policy.get_all_attribute_names()

        for attribute_name in attr_names:
            object_type = managed_object._object_type

            if not self._attribute_policy.is_attribute_supported(
                    attribute_name
            ):
                continue

            if self._attribute_policy.is_attribute_applicable_to_object_type(
                attribute_name,
                object_type
            ):
                try:
                    attribute_value = self._get_attribute_from_managed_object(
                        managed_object,
                        attribute_name
                    )
                except Exception:
                    attribute_value = None

                if attribute_value is not None:
                    if self._attribute_policy.is_attribute_multivalued(
                            attribute_name
                    ):
                        for count, value in enumerate(attribute_value):
                            attribute = attr_factory.create_attribute(
                                enums.AttributeType(attribute_name),
                                value,
                                count
                            )
                            retrieved_attributes.append(attribute)
                    else:
                        attribute = attr_factory.create_attribute(
                            enums.AttributeType(attribute_name),
                            attribute_value
                        )
                        retrieved_attributes.append(attribute)

        return retrieved_attributes

def _get_attributes_from_managed_object ( self , managed_object , attr_names ) : attr_factory = attribute_factory . AttributeFactory ( ) retrieved_attributes = list ( ) if not attr_names : attr_names = self . _attribute_policy . get_all_attribute_names ( ) for attribute_name in attr_names : object_type = managed_object . _object_type if not self . _attribute_policy . is_attribute_supported ( attribute_name ) : continue if self . _attribute_policy . is_attribute_applicable_to_object_type ( attribute_name , object_type ) : try : attribute_value = self . _get_attribute_from_managed_object ( managed_object , attribute_name ) except Exception : attribute_value = None if attribute_value is not None : if self . _attribute_policy . is_attribute_multivalued ( attribute_name ) : for count , value in enumerate ( attribute_value ) : attribute = attr_factory . create_attribute ( enums . AttributeType ( attribute_name ) , value , count ) retrieved_attributes . append ( attribute ) else : attribute = attr_factory . create_attribute ( enums . AttributeType ( attribute_name ) , attribute_value ) retrieved_attributes . append ( attribute ) return retrieved_attributes

Given a kmip . pie object and a list of attribute names attempt to get all of the existing attribute values from the object .


def _get_attribute_from_managed_object(self, managed_object, attr_name):
        """
        Get the attribute value from the kmip.pie managed object.
        """
        if attr_name == 'Unique Identifier':
            return str(managed_object.unique_identifier)
        elif attr_name == 'Name':
            names = list()
            for name in managed_object.names:
                name = attributes.Name(
                    attributes.Name.NameValue(name),
                    attributes.Name.NameType(
                        enums.NameType.UNINTERPRETED_TEXT_STRING
                    )
                )
                names.append(name)
            return names
        elif attr_name == 'Object Type':
            return managed_object._object_type
        elif attr_name == 'Cryptographic Algorithm':
            return managed_object.cryptographic_algorithm
        elif attr_name == 'Cryptographic Length':
            return managed_object.cryptographic_length
        elif attr_name == 'Cryptographic Parameters':
            return None
        elif attr_name == 'Cryptographic Domain Parameters':
            return None
        elif attr_name == 'Certificate Type':
            return managed_object.certificate_type
        elif attr_name == 'Certificate Length':
            return None
        elif attr_name == 'X.509 Certificate Identifier':
            return None
        elif attr_name == 'X.509 Certificate Subject':
            return None
        elif attr_name == 'X.509 Certificate Issuer':
            return None
        elif attr_name == 'Certificate Identifier':
            return None
        elif attr_name == 'Certificate Subject':
            return None
        elif attr_name == 'Certificate Issuer':
            return None
        elif attr_name == 'Digital Signature Algorithm':
            return None
        elif attr_name == 'Digest':
            return None
        elif attr_name == 'Operation Policy Name':
            return managed_object.operation_policy_name
        elif attr_name == 'Cryptographic Usage Mask':
            return managed_object.cryptographic_usage_masks
        elif attr_name == 'Lease Time':
            return None
        elif attr_name == 'Usage Limits':
            return None
        elif attr_name == 'State':
            return managed_object.state
        elif attr_name == 'Initial Date':
            return managed_object.initial_date
        elif attr_name == 'Activation Date':
            return None
        elif attr_name == 'Process Start Date':
            return None
        elif attr_name == 'Protect Stop Date':
            return None
        elif attr_name == 'Deactivation Date':
            return None
        elif attr_name == 'Destroy Date':
            return None
        elif attr_name == 'Compromise Occurrence Date':
            return None
        elif attr_name == 'Compromise Date':
            return None
        elif attr_name == 'Revocation Reason':
            return None
        elif attr_name == 'Archive Date':
            return None
        elif attr_name == 'Object Group':
            return None
        elif attr_name == 'Fresh':
            return None
        elif attr_name == 'Link':
            return None
        elif attr_name == 'Application Specific Information':
            return None
        elif attr_name == 'Contact Information':
            return None
        elif attr_name == 'Last Change Date':
            return None
        else:
            # Since custom attribute names are possible, just return None
            # for unrecognized attributes. This satisfies the spec.
            return None

Get the attribute value from the kmip . pie managed object .


def _set_attributes_on_managed_object(self, managed_object, attributes):
        """
        Given a kmip.pie object and a dictionary of attributes, attempt to set
        the attribute values on the object.
        """
        for attribute_name, attribute_value in six.iteritems(attributes):
            object_type = managed_object._object_type
            if self._attribute_policy.is_attribute_applicable_to_object_type(
                    attribute_name,
                    object_type):
                self._set_attribute_on_managed_object(
                    managed_object,
                    (attribute_name, attribute_value)
                )
            else:
                name = object_type.name
                raise exceptions.InvalidField(
                    "Cannot set {0} attribute on {1} object.".format(
                        attribute_name,
                        ''.join([x.capitalize() for x in name.split('_')])
                    )
                )

Given a kmip . pie object and a dictionary of attributes attempt to set the attribute values on the object .


def _set_attribute_on_managed_object(self, managed_object, attribute):
        """
        Set the attribute value on the kmip.pie managed object.
        """
        attribute_name = attribute[0]
        attribute_value = attribute[1]

        if self._attribute_policy.is_attribute_multivalued(attribute_name):
            if attribute_name == 'Name':
                managed_object.names.extend(
                    [x.name_value.value for x in attribute_value]
                )
                for name in managed_object.names:
                    if managed_object.names.count(name) > 1:
                        raise exceptions.InvalidField(
                            "Cannot set duplicate name values."
                        )
            else:
                # TODO (peterhamilton) Remove when all attributes are supported
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(attribute_name)
                )
        else:
            field = None
            value = attribute_value.value

            if attribute_name == 'Cryptographic Algorithm':
                field = 'cryptographic_algorithm'
            elif attribute_name == 'Cryptographic Length':
                field = 'cryptographic_length'
            elif attribute_name == 'Cryptographic Usage Mask':
                field = 'cryptographic_usage_masks'
                value = list()
                for e in enums.CryptographicUsageMask:
                    if e.value & attribute_value.value:
                        value.append(e)
            elif attribute_name == 'Operation Policy Name':
                field = 'operation_policy_name'

            if field:
                existing_value = getattr(managed_object, field)
                if existing_value:
                    if existing_value != value:
                        raise exceptions.InvalidField(
                            "Cannot overwrite the {0} attribute.".format(
                                attribute_name
                            )
                        )
                else:
                    setattr(managed_object, field, value)
            else:
                # TODO (peterhamilton) Remove when all attributes are supported
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(attribute_name)
                )

Set the attribute value on the kmip . pie managed object .


def is_allowed(
            self,
            policy_name,
            session_user,
            session_group,
            object_owner,
            object_type,
            operation
    ):
        """
        Determine if object access is allowed for the provided policy and
        session settings.
        """
        policy_section = self.get_relevant_policy_section(
            policy_name,
            session_group
        )
        if policy_section is None:
            return False

        object_policy = policy_section.get(object_type)
        if not object_policy:
            self._logger.warning(
                "The '{0}' policy does not apply to {1} objects.".format(
                    policy_name,
                    self._get_enum_string(object_type)
                )
            )
            return False

        operation_object_policy = object_policy.get(operation)
        if not operation_object_policy:
            self._logger.warning(
                "The '{0}' policy does not apply to {1} operations on {2} "
                "objects.".format(
                    policy_name,
                    self._get_enum_string(operation),
                    self._get_enum_string(object_type)
                )
            )
            return False

        if operation_object_policy == enums.Policy.ALLOW_ALL:
            return True
        elif operation_object_policy == enums.Policy.ALLOW_OWNER:
            if session_user == object_owner:
                return True
            else:
                return False
        elif operation_object_policy == enums.Policy.DISALLOW_ALL:
            return False
        else:
            return False

Determine if object access is allowed for the provided policy and session settings .


def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Decrypt request 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._cryptographic_parameters:
            self._cryptographic_parameters.write(
                local_stream,
                kmip_version=kmip_version
            )

        if self._data:
            self._data.write(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError("invalid payload missing the data attribute")

        if self._iv_counter_nonce:
            self._iv_counter_nonce.write(
                local_stream,
                kmip_version=kmip_version
            )

        self.length = local_stream.length()
        super(DecryptRequestPayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)

Write the data encoding the Decrypt request payload to a stream .


def create(self, secret_type, value=None):
        """
        Create a secret object of the specified type with the given value.

        Args:
            secret_type (ObjectType): An ObjectType enumeration specifying the
                type of secret to create.
            value (dict): A dictionary containing secret data. Optional,
                defaults to None.

        Returns:
            secret: The newly constructed secret object.

        Raises:
            TypeError: If the provided secret type is unrecognized.

        Example:
            >>> factory.create(ObjectType.SYMMETRIC_KEY)
            SymmetricKey(...)
        """
        if secret_type is ObjectType.CERTIFICATE:
            return self._create_certificate(value)
        elif secret_type is ObjectType.SYMMETRIC_KEY:
            return self._create_symmetric_key(value)
        elif secret_type is ObjectType.PUBLIC_KEY:
            return self._create_public_key(value)
        elif secret_type is ObjectType.PRIVATE_KEY:
            return self._create_private_key(value)
        elif secret_type is ObjectType.SPLIT_KEY:
            return self._create_split_key(value)
        elif secret_type is ObjectType.TEMPLATE:
            return self._create_template(value)
        elif secret_type is ObjectType.SECRET_DATA:
            return self._create_secret_data(value)
        elif secret_type is ObjectType.OPAQUE_DATA:
            return self._create_opaque_data(value)
        else:
            raise TypeError("Unrecognized secret type: {0}".format(
                secret_type))

def
create
(
self
,
secret_type
,
value
=
)
:
if
secret_type
is
ObjectType
.
CERTIFICATE
:
return
self
.
_create_certificate
(
value
)
elif
secret_type
is
ObjectType
.
SYMMETRIC_KEY
:
return
self
.
_create_symmetric_key
(
value
)
elif
secret_type
is
ObjectType
.
PUBLIC_KEY
:
return
self
.
_create_public_key
(
value
)
elif
secret_type
is
ObjectType
.
PRIVATE_KEY
:
return
self
.
_create_private_key
(
value
)
elif
secret_type
is
ObjectType
.
SPLIT_KEY
:
return
self
.
_create_split_key
(
value
)
elif
secret_type
is
ObjectType
.
TEMPLATE
:
return
self
.
_create_template
(
value
)
elif
secret_type
is
ObjectType
.
SECRET_DATA
:
return
self
.
_create_secret_data
(
value
)
elif
secret_type
is
ObjectType
.
OPAQUE_DATA
:
return
self
.
_create_opaque_data
(
value
)
else
:
raise
TypeError
(
"Unrecognized secret type: {0}"
.
format
(
secret_type
)
)

Create a secret object of the specified type with the given value .


def set_setting(self, setting, value):
        """
        Set a specific setting value.

        This will overwrite the current setting value for the specified
        setting.

        Args:
            setting (string): The name of the setting to set (e.g.,
                'certificate_path', 'hostname'). Required.
            value (misc): The value of the setting to set. Type varies based
                on setting. Required.
        Raises:
            ConfigurationError: Raised if the setting is not supported or if
                the setting value is invalid.
        """
        if setting not in self._expected_settings + self._optional_settings:
            raise exceptions.ConfigurationError(
                "Setting '{0}' is not supported.".format(setting)
            )

        if setting == 'hostname':
            self._set_hostname(value)
        elif setting == 'port':
            self._set_port(value)
        elif setting == 'certificate_path':
            self._set_certificate_path(value)
        elif setting == 'key_path':
            self._set_key_path(value)
        elif setting == 'ca_path':
            self._set_ca_path(value)
        elif setting == 'auth_suite':
            self._set_auth_suite(value)
        elif setting == 'policy_path':
            self._set_policy_path(value)
        elif setting == 'enable_tls_client_auth':
            self._set_enable_tls_client_auth(value)
        elif setting == 'tls_cipher_suites':
            self._set_tls_cipher_suites(value)
        elif setting == 'logging_level':
            self._set_logging_level(value)
        else:
            self._set_database_path(value)

def
set_setting
(
self
,
setting
,
value
)
:
if
setting
not
in
self
.
_expected_settings
+
self
.
_optional_settings
:
raise
exceptions
.
ConfigurationError
(
"Setting '{0}' is not supported."
.
format
(
setting
)
)
if
setting
==
'hostname'
:
self
.
_set_hostname
(
value
)
elif
setting
==
'port'
:
self
.
_set_port
(
value
)
elif
setting
==
'certificate_path'
:
self
.
_set_certificate_path
(
value
)
elif
setting
==
'key_path'
:
self
.
_set_key_path
(
value
)
elif
setting
==
'ca_path'
:
self
.
_set_ca_path
(
value
)
elif
setting
==
'auth_suite'
:
self
.
_set_auth_suite
(
value
)
elif
setting
==
'policy_path'
:
self
.
_set_policy_path
(
value
)
elif
setting
==
'enable_tls_client_auth'
:
self
.
_set_enable_tls_client_auth
(
value
)
elif
setting
==
'tls_cipher_suites'
:
self
.
_set_tls_cipher_suites
(
value
)
elif
setting
==
'logging_level'
:
self
.
_set_logging_level
(
value
)
else
:
self
.
_set_database_path
(
value
)


def load_settings(self, path):
        """
        Load configuration settings from the file pointed to by path.

        This will overwrite all current setting values.

        Args:
            path (string): The path to the configuration file containing
                the settings to load. Required.
        Raises:
            ConfigurationError: Raised if the path does not point to an
                existing file or if a setting value is invalid.
        """
        if not os.path.exists(path):
            raise exceptions.ConfigurationError(
                "The server configuration file ('{0}') could not be "
                "located.".format(path)
            )

        self._logger.info(
            "Loading server configuration settings from: {0}".format(path)
        )

        parser = configparser.ConfigParser()
        parser.read(path)
        self._parse_settings(parser)
        self.parse_auth_settings(parser)

Load configuration settings from the file pointed to by path .


def process_bind_param(self, value, dialect):
        """
        Returns the integer value of the usage mask bitmask. This value is
        stored in the database.

        Args:
            value(list<enums.CryptographicUsageMask>): list of enums in the
            usage mask
            dialect(string): SQL dialect
        """
        bitmask = 0x00
        for e in value:
            bitmask = bitmask | e.value
        return bitmask

def process_bind_param ( self , value , dialect ) : bitmask = 0x00 for e in value : bitmask = bitmask | e . value return bitmask

Returns the integer value of the usage mask bitmask . This value is stored in the database .


def process_result_value(self, value, dialect):
        """
        Returns a new list of enums.CryptographicUsageMask Enums. This converts
        the integer value into the list of enums.

        Args:
            value(int): The integer value stored in the database that is used
                to create the list of enums.CryptographicUsageMask Enums.
            dialect(string): SQL dialect
        """
        masks = list()
        if value:
            for e in enums.CryptographicUsageMask:
                if e.value & value:
                    masks.append(e)
        return masks

def process_result_value ( self , value , dialect ) : masks = list ( ) if value : for e in enums . CryptographicUsageMask : if e . value & value : masks . append ( e ) return masks

Returns a new list of enums . CryptographicUsageMask Enums . This converts the integer value into the list of enums .


def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the encoding of the LongInteger from the input stream.

        Args:
            istream (stream): A buffer containing the encoded bytes of a
                LongInteger. 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 long integer encoding read in has
                an invalid encoded length.
        """
        super(LongInteger, self).read(istream, kmip_version=kmip_version)

        if self.length is not LongInteger.LENGTH:
            raise exceptions.InvalidPrimitiveLength(
                "invalid long integer length read; "
                "expected: {0}, observed: {1}".format(
                    LongInteger.LENGTH, self.length))

        self.value = unpack('!q', istream.read(self.length))[0]
        self.validate()

def
read
(
self
,
istream
,
kmip_version
=
enums
.
KMIPVersion
.
KMIP_1_0
)
:
super
(
LongInteger
,
self
)
.
read
(
istream
,
kmip_version
=
kmip_version
)
if
self
.
length
is
not
LongInteger
.
LENGTH
:
raise
exceptions
.
InvalidPrimitiveLength
(
"invalid long integer length read; "
"expected: {0}, observed: {1}"
.
format
(
LongInteger
.
LENGTH
,
self
.
length
)
)
self
.
value
=
unpack
(
'!q'
,
istream
.
read
(
self
.
length
)
)
[
0
]
self
.
validate
(
)

Read the encoding of the LongInteger from the input stream .


def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the encoding of the LongInteger to the output stream.

        Args:
            ostream (stream): A buffer to contain the encoded bytes of a
                LongInteger. 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(LongInteger, self).write(ostream, kmip_version=kmip_version)
        ostream.write(pack('!q', self.value))

def write ( self , ostream , kmip_version = enums . KMIPVersion . KMIP_1_0 ) : super ( LongInteger , self ) . write ( ostream , kmip_version = kmip_version ) ostream . write ( pack ( '!q' , self . value ) )

Write the encoding of the LongInteger to the output stream .


def validate(self):
        """
        Verify that the value of the LongInteger is valid.

        Raises:
            TypeError: if the value is not of type int or long
            ValueError: if the value cannot be represented by a signed 64-bit
                integer
        """
        if self.value is not None:
            if not isinstance(self.value, six.integer_types):
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(self.value)))
            else:
                if self.value > LongInteger.MAX:
                    raise ValueError(
                        'long integer value greater than accepted max')
                elif self.value < LongInteger.MIN:
                    raise ValueError(
                        'long integer value less than accepted min')

Verify that the value of the LongInteger is valid .


def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the encoding of the BigInteger from the input stream.

        Args:
            istream (stream): A buffer containing the encoded bytes of the
                value of a BigInteger. 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 big integer encoding read in has
                an invalid encoded length.
        """
        super(BigInteger, self).read(istream, kmip_version=kmip_version)

        # Check for a valid length before even trying to parse the value.
        if self.length % 8:
            raise exceptions.InvalidPrimitiveLength(
                "invalid big integer length read; "
                "expected: multiple of 8, observed: {0}".format(self.length))

        sign = 1
        binary = ''

        # Read the value byte by byte and convert it into binary, padding each
        # byte as needed.
        for _ in range(self.length):
            byte = struct.unpack('!B', istream.read(1))[0]
            bits = "{0:b}".format(byte)
            pad = len(bits) % 8
            if pad:
                bits = ('0' * (8 - pad)) + bits
            binary += bits

        # If the value is negative, convert via two's complement.
        if binary[0] == '1':
            sign = -1
            binary = binary.replace('1', 'i')
            binary = binary.replace('0', '1')
            binary = binary.replace('i', '0')

            pivot = binary.rfind('0')
            binary = binary[0:pivot] + '1' + ('0' * len(binary[pivot + 1:]))

        # Convert the value back to an integer and reapply the sign.
        self.value = int(binary, 2) * sign

Read the encoding of the BigInteger from the input stream .


def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the encoding of the BigInteger to the output stream.

        Args:
            ostream (Stream): A buffer to contain the encoded bytes of a
                BigInteger 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.
        """
        # Convert the value to binary and pad it as needed.
        binary = "{0:b}".format(abs(self.value))
        binary = ("0" * (64 - (len(binary) % 64))) + binary

        # If the value is negative, convert via two's complement.
        if self.value < 0:
            binary = binary.replace('1', 'i')
            binary = binary.replace('0', '1')
            binary = binary.replace('i', '0')

            pivot = binary.rfind('0')
            binary = binary[0:pivot] + '1' + ('0' * len(binary[pivot + 1:]))

        # Convert each byte to hex and build the hex string for the value.
        hexadecimal = b''
        for i in range(0, len(binary), 8):
            byte = binary[i:i + 8]
            byte = int(byte, 2)
            hexadecimal += struct.pack('!B', byte)

        self.length = len(hexadecimal)
        super(BigInteger, self).write(ostream, kmip_version=kmip_version)
        ostream.write(hexadecimal)

Write the encoding of the BigInteger to the output stream .


def validate(self):
        """
        Verify that the value of the BigInteger is valid.

        Raises:
            TypeError: if the value is not of type int or long
        """
        if self.value is not None:
            if not isinstance(self.value, six.integer_types):
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(self.value)))

def
validate
(
self
)
:
if
self
.
value
is
not
:
if
not
isinstance
(
self
.
value
,
six
.
integer_types
)
:
raise
TypeError
(
'expected (one of): {0}, observed: {1}'
.
format
(
six
.
integer_types
,
type
(
self
.
value
)
)
)

Verify that the value of the BigInteger is valid .


def validate(self):
        """
        Verify that the value of the Enumeration is valid.

        Raises:
            TypeError: if the enum is not of type Enum
            ValueError: if the value is not of the expected Enum subtype or if
                the value cannot be represented by an unsigned 32-bit integer
        """
        if not isinstance(self.enum, enumeration.EnumMeta):
            raise TypeError(
                'enumeration type {0} must be of type EnumMeta'.format(
                    self.enum))
        if self.value is not None:
            if not isinstance(self.value, self.enum):
                raise TypeError(
                    'enumeration {0} must be of type {1}'.format(
                        self.value, self.enum))
            if type(self.value.value) not in six.integer_types:
                raise TypeError('enumeration value must be an int')
            else:
                if self.value.value > Enumeration.MAX:
                    raise ValueError(
                        'enumeration value greater than accepted max')
                elif self.value.value < Enumeration.MIN:
                    raise ValueError(
                        'enumeration value less than accepted min')

Verify that the value of the Enumeration is valid .


def read_value(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the value of the Boolean object from the input stream.

        Args:
            istream (Stream): A buffer containing the encoded bytes of the
                value of a Boolean object. 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:
            ValueError: if the read boolean value is not a 0 or 1.
        """
        try:
            value = unpack('!Q', istream.read(self.LENGTH))[0]
        except Exception:
            self.logger.error("Error reading boolean value from buffer")
            raise

        if value == 1:
            self.value = True
        elif value == 0:
            self.value = False
        else:
            raise ValueError("expected: 0 or 1, observed: {0}".format(value))

        self.validate()

Read the value of the Boolean object from the input stream .


def write_value(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the value of the Boolean object to the output stream.

        Args:
            ostream (Stream): A buffer to contain the encoded bytes of the
                value 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.
        """
        try:
            ostream.write(pack('!Q', self.value))
        except Exception:
            self.logger.error("Error writing boolean value to buffer")
            raise

def
write_value
(
self
,
ostream
,
kmip_version
=
enums
.
KMIPVersion
.
KMIP_1_0
)
:
try
:
ostream
.
write
(
pack
(
'!Q'
,
self
.
value
)
)
except
Exception
:
self
.
logger
.
error
(
"Error writing boolean value to buffer"
)
raise

Write the value of the Boolean object to the output stream .


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)

def write ( self , ostream , kmip_version = enums . KMIPVersion . KMIP_1_0 ) : super ( Boolean , self ) . write ( ostream , kmip_version = kmip_version ) self . write_value ( ostream , kmip_version = kmip_version )

Write the encoding of the Boolean object to the output stream .


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)))

def
validate
(
self
)
:
if
self
.
value
:
if
not
isinstance
(
self
.
value
,
bool
)
:
raise
TypeError
(
"expected: {0}, observed: {1}"
.
format
(
bool
,
type
(
self
.
value
)
)
)

Verify that the value of the Boolean object is valid .


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()

Read the encoding of the Interval from the input stream .


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')

Verify that the value of the Interval is valid .


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

Retrieve all of the relevant key wrapping data fields and return them as a dictionary .


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')

Set the key wrapping data attributes using a dictionary .


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))

Verify that the contents of the PublicKey object are valid .


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))

Verify that the contents of the SecretData object are valid .


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))

Verify that the contents of the OpaqueObject are valid .


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))

def
convert_attribute_name_to_tag
(
value
)
:
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
)
)

A utility function that converts an attribute name string into the corresponding attribute tag .


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))

A utility function that converts an attribute tag into the corresponding attribute name string .


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]
    )

def get_bit_mask_from_enumerations ( enumerations ) : return functools . reduce ( lambda x , y : x | y , [ z . value for z in enumerations ] )

A utility function that computes a bit mask from a collection of enumeration values .


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]

def get_enumerations_from_bit_mask ( enumeration , mask ) : return [ x for x in enumeration if ( x . value & mask ) == x . value ]

A utility function that creates a list of enumeration values from a bit mask for a specific mask enumeration class .


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

def is_bit_mask ( enumeration , potential_mask ) : 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

A utility function that checks if the provided value is a composite bit mask of enumeration values in the specified enumeration class .


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)

Read the data encoding the CreateKeyPair request payload and decode it into its constituent parts .


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)

Write the data encoding the CreateKeyPair request payload to a buffer .


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)

Read the data encoding the CreateKeyPair response payload and decode it into its constituent parts .


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)

Write the data encoding the CreateKeyPair response payload to a buffer .


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)

def read ( self , input_buffer , kmip_version = enums . KMIPVersion . 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 )

Read the data encoding the GetAttributeList request payload and decode it into its constituent parts .


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)

def write ( self , output_buffer , kmip_version = enums . KMIPVersion . 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 )

Write the data encoding the GetAttributeList request payload to a stream .


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)

Read the data encoding the GetAttributeList response payload and decode it into its constituent parts .


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)

Write the data encoding the GetAttributeList response payload to a stream .


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)

def get_json_files ( p ) : f = [ os . path . join ( p , x ) for x in os . listdir ( p ) if x . endswith ( ".json" ) ] return sorted ( f )

Scan the provided policy directory for all JSON policy files .


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)

Scan the policy directory for policy data .


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()

Start monitoring operation policy files .


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

def get_certificate_from_connection ( connection ) : certificate = connection . getpeercert ( binary_form = True ) if certificate : return x509 . load_der_x509_certificate ( certificate , backends . default_backend ( ) ) return None

Extract an X . 509 certificate from a socket connection .


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

def get_extended_key_usage_from_certificate ( certificate ) : try : return certificate . extensions . get_extension_for_oid ( x509 . oid . ExtensionOID . EXTENDED_KEY_USAGE ) . value except x509 . ExtensionNotFound : return None

Given an X . 509 certificate extract and return the extendedKeyUsage extension .


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]

def get_common_names_from_certificate ( certificate ) : common_names = certificate . subject . get_attributes_for_oid ( x509 . oid . NameOID . COMMON_NAME ) return [ common_name . value for common_name in common_names ]

Given an X . 509 certificate extract and return all common names .


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."
        )

Given an X . 509 certificate extract and return the client identity .


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)

Read the data encoding the Create request payload and decode it into its constituent parts .


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)

Write the data encoding the Create request payload to a buffer .


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)

Read the data encoding the Create response payload and decode it into its constituent parts .


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)

Write the data encoding the Create response payload to a buffer .