kmipclient

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2025 License: Apache-2.0 Imports: 23 Imported by: 3

Documentation

Overview

Package kmipclient provides a client implementation for interacting with KMIP (Key Management Interoperability Protocol) servers. It supports protocol version negotiation, TLS configuration, middleware chaining, and batch operations.

The client is highly configurable via functional options, allowing customization of TLS settings, supported protocol versions, client certificates, and middleware. It provides methods for sending KMIP requests, handling batch operations, and cloning clients.

Key Features:

  • Protocol version negotiation with the KMIP server, with support for enforcing a specific version.
  • Flexible TLS configuration, including custom root CAs, client certificates, and cipher suites.
  • Middleware support for request/response processing.
  • Batch operation support for sending multiple KMIP operations in a single request.
  • Safe concurrent usage via internal locking.

Usage Example:

client, err := kmipclient.Dial("kmip.example.com:5696",
	kmipclient.WithClientCertFiles("client.crt", "client.key"),
	kmipclient.WithRootCAFile("ca.crt"),
)
if err != nil {
	log.Fatal(err)
}
defer client.Close()

resp, err := client.Request(context.Background(), payload)
if err != nil {
	log.Fatal(err)
}

Types:

  • Client: Represents a KMIP client connection.
  • Option: Functional option for configuring the client.
  • Executor: Generic type for building and executing KMIP requests.
  • AttributeExecutor: Executor with attribute-building helpers.
  • BatchExec: Helper for building and executing batch requests.
  • BatchResult: Result type for batch operations.

See the documentation for each type and function for more details.

Example

Example demonstrates how to establish a connection to a KMIP server. This shows the basic client setup with TLS certificates.

package main

import (
	"fmt"
	"log"

	"github.com/ovh/kmip-go/kmipclient"
)

func main() {
	// Connect to KMIP server with client certificates
	client, err := kmipclient.Dial(
		"your-kmip-server.example.com:5696",
		kmipclient.WithClientCertFiles("client-cert.pem", "client-key.pem"),
		// Optionally specify root CA if needed
		// kmipclient.WithRootCAFile("ca.pem"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	fmt.Printf("Connected using KMIP version %s\n", client.Version())
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AttributeExecutor

type AttributeExecutor[Req, Resp kmip.OperationPayload, Wrap any] struct {
	Executor[Req, Resp]
	// contains filtered or unexported fields
}

AttributeExecutor is a generic struct that extends Executor to provide additional functionality for handling KMIP operation payloads with attribute manipulation.

Type Parameters:

  • Req: The request payload type, which must implement kmip.OperationPayload.
  • Resp: The response payload type, which must implement kmip.OperationPayload.
  • Wrap: An arbitrary type used for wrapping or extending the executor.

Fields:

  • Executor: Embeds the base Executor for handling request and response payloads.
  • attrFunc: A function that takes a pointer to the request payload and returns a pointer to a slice of kmip.Attribute, allowing for attribute extraction or modification.
  • wrap: A function that takes an AttributeExecutor and returns a value of type Wrap, enabling custom wrapping or extension of the executor's behavior.

func (AttributeExecutor[Req, Resp, Wrap]) WithAttribute

func (ex AttributeExecutor[Req, Resp, Wrap]) WithAttribute(name kmip.AttributeName, value any) Wrap

WithAttribute adds a single attribute to the executor by specifying the attribute name and value. The attribute index is set to nil by default.

Parameters:

  • name: The name of the attribute to add.
  • value: The value of the attribute to add.

func (AttributeExecutor[Req, Resp, Wrap]) WithAttributes

func (ex AttributeExecutor[Req, Resp, Wrap]) WithAttributes(attributes ...kmip.Attribute) Wrap

WithAttributes appends the provided KMIP attributes to the request's attribute list.

Parameters:

  • attributes - One or more kmip.Attribute values to be added to the request.
func (ex AttributeExecutor[Req, Resp, Wrap]) WithLink(linkType kmip.LinkType, linkedObjectID string) Wrap

WithLink adds a Link attribute to the request, specifying the relationship between the current object and another KMIP object identified by linkedObjectID and the given linkType. This method is typically used to establish associations such as "parent", "child", or "previous" between managed objects in KMIP.

func (AttributeExecutor[Req, Resp, Wrap]) WithName

func (ex AttributeExecutor[Req, Resp, Wrap]) WithName(name string) Wrap

WithName sets the "Name" attribute for the request using the provided name string. It wraps the name in a kmip.Name struct with NameType set to UninterpretedTextString.

func (AttributeExecutor[Req, Resp, Wrap]) WithObjectType

func (ex AttributeExecutor[Req, Resp, Wrap]) WithObjectType(objectType kmip.ObjectType) Wrap

WithObjectType sets the ObjectType attribute for the request. It attaches the specified kmip.ObjectType to the request attributes.

func (AttributeExecutor[Req, Resp, Wrap]) WithURI

func (ex AttributeExecutor[Req, Resp, Wrap]) WithURI(uri string) Wrap

WithURI sets the URI attribute for the request by adding a Name attribute with the specified URI value.

Parameters:

  • uri: The URI string to be set as the Name attribute.

func (AttributeExecutor[Req, Resp, Wrap]) WithUniqueID

func (ex AttributeExecutor[Req, Resp, Wrap]) WithUniqueID(id string) Wrap

WithUniqueID sets the Unique Identifier attribute for the request. The Unique Identifier is typically used to specify the object to operate on in KMIP operations.

Parameters:

  • id: The unique identifier string to set.

func (AttributeExecutor[Req, Resp, Wrap]) WithUsageLimit

func (ex AttributeExecutor[Req, Resp, Wrap]) WithUsageLimit(total int64, unit kmip.UsageLimitsUnit) Wrap

WithUsageLimit sets the usage limits attribute for a KMIP object. It specifies the total allowed usage, the unit of usage, and sets the usage count pointer. Parameters:

  • total: The total number of allowed usages.
  • unit: The unit of usage limits (e.g., operations, time).

type BatchExec added in v0.4.0

type BatchExec struct {
	// contains filtered or unexported fields
}

BatchExec manages the building and the execution of a batch of KMIP operations using a client. It holds a reference to the client, any error encountered during batch construction, and the list of operation payloads to be executed as a batch.

func (BatchExec) Exec added in v0.4.0

func (ex BatchExec) Exec(opts ...BatchOption) (BatchResult, error)

Exec sends the batch to the remote KMIP server, and returns the parsed responses.

Parameters:

  • opts: Optional BatchOption functions to modify the request message.

Returns:

  • BatchResult: The results of the batch operations.
  • error: An error if the batch request fails.

func (BatchExec) ExecContext added in v0.4.0

func (ex BatchExec) ExecContext(ctx context.Context, opts ...BatchOption) (BatchResult, error)

ExecContext sends the batch to the remote KMIP server, and returns the parsed responses.

Parameters:

  • ctx: Context for request cancellation and timeout.
  • opts: Optional BatchOption functions to modify the request message.

Returns:

  • BatchResult: The results of the batch operations.
  • error: An error if the batch request fails.

func (BatchExec) MustExec added in v0.4.0

func (ex BatchExec) MustExec(opts ...BatchOption) BatchResult

MustExec is like Exec except it panics if the request fails.

Parameters:

  • opts: Optional BatchOption functions to modify the request message.

Returns:

  • BatchResult: The results of the batch operations.

Panics:

  • If the request fails, this function panics with the error.

func (BatchExec) MustExecContext added in v0.4.0

func (ex BatchExec) MustExecContext(ctx context.Context, opts ...BatchOption) BatchResult

MustExecContext is like Exec except it panics if the request fails.

Parameters:

  • ctx: Context for request cancellation and timeout.
  • opts: Optional BatchOption functions to modify the request message.

Returns:

  • BatchResult: The results of the batch operations.

Panics:

  • If the request fails, this function panics with the error.

func (BatchExec) Then added in v0.4.0

func (ex BatchExec) Then(f func(client *Client) PayloadBuilder) BatchExec

Then adds a new payload to the batch by invoking the provided function f with the current client. If an error has already occurred in the batch execution, it returns the existing BatchExec without modification. Otherwise, it builds the payload using the PayloadBuilder returned by f, appends it to the batch, and returns the updated BatchExec. If building the payload results in an error, the error is stored in the BatchExec and returned.

type BatchOption added in v0.4.0

type BatchOption func(*kmip.RequestMessage)

BatchOption defines a function type that modifies a kmip.RequestMessage, allowing customization of batch operations in KMIP client requests.

func OnBatchErr added in v0.4.0

func OnBatchErr(opt kmip.BatchErrorContinuationOption) BatchOption

OnBatchErr returns a BatchOption that sets the BatchErrorContinuationOption in the request message header. This option determines how the server should handle errors encountered during batch processing. The provided 'opt' parameter specifies the desired error continuation behavior.

type BatchResult added in v0.4.0

type BatchResult []kmip.ResponseBatchItem

BatchResult represents a collection of KMIP response batch items returned from a KMIP operation.

func (BatchResult) MustUnwrap added in v0.4.0

func (br BatchResult) MustUnwrap() []kmip.OperationPayload

MustUnwrap is like Unwrap except that it panics if it encounters an error. This function should probably not be used in production code and exists only to ease testing and experimenting.

Returns:

  • []kmip.OperationPayload: The slice of operation payloads from the batch result.

Panics:

  • If any error is encountered in the batch result, this function panics with the error.

func (BatchResult) Unwrap added in v0.4.0

func (br BatchResult) Unwrap() ([]kmip.OperationPayload, error)

Unwrap checks for eventual errors in all the batch items, and returns an array of item's payloads, and the encountered errors. If an item has no payload, the returned array will contain a nil element at the item index.

Returns:

  • []kmip.OperationPayload: The slice of operation payloads from the batch result.
  • error: An error if any batch item contains an error; otherwise, nil.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a KMIP client that manages a connection to a KMIP server, handles protocol version negotiation, and supports middleware for request/response processing. It provides thread-safe access to the underlying connection and configuration options such as supported protocol versions and custom dialers.

Example (ContextUsage)

ExampleClient_contextUsage demonstrates using context for request cancellation.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Use context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

resp, err := client.Create().
	AES(256, kmip.CryptographicUsageEncrypt).
	WithName("timeout-key").
	ExecContext(ctx)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Created key with timeout: %s\n", resp.UniqueIdentifier)

func Dial

func Dial(addr string, options ...Option) (*Client, error)

Dial establishes a connection to the KMIP server at the specified address using the provided options. It is a convenience wrapper around DialContext with a background context. Returns a pointer to a Client and an error, if any occurs during connection setup.

func DialContext

func DialContext(ctx context.Context, addr string, options ...Option) (*Client, error)

DialContext establishes a new KMIP client connection to the specified address using the provided context and optional configuration options. It applies the given options, sets up TLS configuration, and negotiates the protocol version with the server. Returns a pointer to the initialized Client or an error if the connection or negotiation fails.

Parameters:

  • ctx - The context for controlling cancellation and timeout of the dialing process.
  • addr - The network address of the KMIP server to connect to.
  • options - Optional configuration functions to customize client behavior.

Returns:

  • *Client - The initialized KMIP client.
  • error - An error if the connection or protocol negotiation fails.

func (*Client) Activate

func (c *Client) Activate(id string) ExecActivate

Activate creates and returns an ExecActivate struct initialized with the provided unique identifier. This method prepares an activation request payload for the specified object ID using the client instance. The returned ExecActivate can be used to execute the activation operation by calling Exec or ExecContext.

Parameters:

  • id: Unique identifier of the KMIP object to activate.

Returns:

  • ExecActivate: Executor for the Activate operation, pre-filled with the unique identifier.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecActivate.

func (*Client) AddAttribute

func (c *Client) AddAttribute(id string, name kmip.AttributeName, value any) ExecAddAttribute

AddAttribute creates an ExecAddAttribute operation to add a new attribute to an existing object identified by the given unique identifier. The attribute is specified by its name and value.

Parameters:

  • id: The unique identifier of the object to which the attribute will be added.
  • name: The name of the attribute to add.
  • value: The value of the attribute to add. This can be any type supported by the KMIP attribute system.

Returns:

  • ExecAddAttribute: An executor that can be used to perform the add attribute operation.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecAddAttribute.
  • If the attribute name or value is not supported by the server, an error will be returned during execution.

func (*Client) Addr

func (c *Client) Addr() string

Addr returns the address of the KMIP server that the client is configured to connect to.

func (*Client) Archive

func (c *Client) Archive(id string) ExecArchive

Archive creates an ExecArchive operation for the specified unique identifier. This method prepares an archive request payload for the specified object ID using the client instance. The returned ExecArchive can be used to execute the archive operation by calling Exec or ExecContext.

Parameters:

  • id: The unique identifier of the object to be archived.

Returns:

  • ExecArchive: Executor for the Archive operation, pre-filled with the unique identifier.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecArchive.
  • If the object does not exist or cannot be archived, an error will be returned during execution.

func (*Client) Batch

func (c *Client) Batch(ctx context.Context, payloads ...kmip.OperationPayload) (BatchResult, error)

Batch sends one or more KMIP operation payloads to the server as a batch request. It returns a BatchResult containing the results of each operation, or an error if the request fails. This method is a convenience wrapper around BatchOpt.

Parameters:

ctx      - The context for controlling cancellation and deadlines.
payloads - One or more KMIP operation payloads to be executed in the batch.

Returns:

BatchResult - The results of the batch operations.
error       - An error if the batch request fails.
Example

ExampleClient_Batch demonstrates executing multiple operations in a single request.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create two keys in a single batch request
resp, err := client.Create().AES(256, kmip.CryptographicUsageEncrypt).WithName("batch-key-1").
	Then(func(client *kmipclient.Client) kmipclient.PayloadBuilder {
		return client.Create().AES(256, kmip.CryptographicUsageEncrypt).WithName("batch-key-2")
	}).Then(func(client *kmipclient.Client) kmipclient.PayloadBuilder {
	return client.Create().AES(256, kmip.CryptographicUsageEncrypt).WithName("batch-key-3")
}).
	Exec(kmipclient.OnBatchErr(kmip.BatchErrorContinuationOptionStop))
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Created %d keys in batch:\n", len(resp))
for i, resp := range resp {
	if err := resp.Err(); err != nil {
		log.Fatal(err)
	}
	if createResp, ok := resp.ResponsePayload.(*payloads.CreateResponsePayload); ok {
		fmt.Printf("  Key %d: %s\n", i+1, createResp.UniqueIdentifier)
	}
}

func (*Client) BatchOpt added in v0.4.0

func (c *Client) BatchOpt(ctx context.Context, payloads []kmip.OperationPayload, opts ...BatchOption) (BatchResult, error)

BatchOpt sends a batch of KMIP operation payloads to the server and applies optional batch options. It constructs a KMIP request message with the provided payloads and applies any BatchOption functions. The request is sent using the client's Roundtrip method. If the response's batch count does not match the number of payloads, an error is returned. On success, it returns the batch result items.

Parameters:

  • ctx: Context for request cancellation and timeout.
  • payloads: Slice of KMIP operation payloads to be sent in the batch.
  • opts: Optional BatchOption functions to modify the request message.

Returns:

  • BatchResult: The result items from the batch response.
  • error: An error if the request fails or the batch count does not match.

func (*Client) Clone

func (c *Client) Clone() (*Client, error)

Clone is like CloneCtx but uses internally a background context.

func (*Client) CloneCtx added in v0.2.5

func (c *Client) CloneCtx(ctx context.Context) (*Client, error)

CloneCtx clones the current kmip client into a new independent client with a separate new connection. The new client inherits allt he configured parameters as well as the negotiated kmip protocol version. Meaning that cloning a client does not perform protocol version negotiation.

Cloning a closed client is valid and will create a new connected client.

func (*Client) Close

func (c *Client) Close() error

Close terminates the client's connection and releases any associated resources. It returns an error if the connection could not be closed.

func (*Client) Create

func (c *Client) Create() ExecCreateWantType

Create initializes and returns a new ExecCreateWantType instance associated with the current Client. This method is typically used to begin the creation process for a KMIP object using the client context.

Example

ExampleClient_Create demonstrates creating an AES symmetric key. This is the most common operation for creating encryption keys.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create a 256-bit AES key for encryption and decryption
resp, err := client.Create().
	AES(256, kmip.CryptographicUsageEncrypt|kmip.CryptographicUsageDecrypt).
	WithName("my-aes-key").
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Created AES key with ID: %s\n", resp.UniqueIdentifier)
Example (WithAttributes)

ExampleClient_Create_withAttributes demonstrates creating a key with custom attributes.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create an AES key with additional security attributes
resp, err := client.Create().
	AES(256, kmip.CryptographicUsageEncrypt|kmip.CryptographicUsageDecrypt).
	WithName("secure-key").
	WithAttribute(kmip.AttributeNameSensitive, true).
	WithAttribute(kmip.AttributeNameExtractable, false).
	WithAttribute(kmip.AttributeNameComment, "Production encryption key").
	WithAttribute("x-custom", "random value").
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Created secure AES key with ID: %s\n", resp.UniqueIdentifier)

func (*Client) CreateKeyPair

func (c *Client) CreateKeyPair() ExecCreateKeyPair

CreateKeyPair initializes and returns an ExecCreateKeyPair instance with default template attributes for common, private, and public key templates. This method prepares the request payload for creating a new key pair using the KMIP protocol.

Returns:

  • ExecCreateKeyPair: An executor configured with the client and default key pair request payload.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecCreateKeyPair.
  • If the server does not support key pair creation or the request is malformed, an error will be returned during execution.
Example

ExampleClient_CreateKeyPair demonstrates creating an asymmetric key pair.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create an RSA key pair with separate usage masks for private and public keys
resp, err := client.CreateKeyPair().
	RSA(2048, kmip.CryptographicUsageSign, kmip.CryptographicUsageVerify).
	PrivateKey().WithName("rsa-private-key").
	PublicKey().WithName("rsa-public-key").
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Created RSA key pair:\n")
fmt.Printf("  Private Key ID: %s\n", resp.PrivateKeyUniqueIdentifier)
fmt.Printf("  Public Key ID: %s\n", resp.PublicKeyUniqueIdentifier)

func (*Client) Decrypt added in v0.2.5

func (c *Client) Decrypt(id string) ExecDecryptWantsData

Decrypt creates an ExecDecryptWantsData builder for decrypting data with the specified key ID. Returns an ExecDecryptWantsData that can be further configured before calling Data().

Example

ExampleClient_Decrypt demonstrates decrypting data with a key.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Decrypt data using an existing key
resp, err := client.Decrypt("key-12345").
	WithCryptographicParameters(kmip.AES_GCM).
	WithIvCounterNonce([]byte{ /* IV / Nonce data */ }). // May be optional depending on the encryption algorithm used
	WithAuthTag([]byte{ /* Authentication tag */ }).     // May be optional depending on the encryption algorithm used
	Data([]byte{ /* Ciphertext data */ }).
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Decrypted data: %s\n", string(resp.Data))

func (*Client) DeleteAttribute

func (c *Client) DeleteAttribute(id string, name kmip.AttributeName) ExecDeleteAttribute

DeleteAttribute creates an ExecDeleteAttribute operation to remove an attribute from an existing object identified by the given unique identifier and attribute name. The returned ExecDeleteAttribute can be further configured (e.g., with an index) and executed to perform the deletion.

Parameters:

  • id: The unique identifier of the object from which the attribute will be deleted.
  • name: The name of the attribute to delete.

Returns:

  • ExecDeleteAttribute: An executor for the delete attribute operation.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecDeleteAttribute.
  • If the attribute or object does not exist, or the server rejects the operation, an error will be returned during execution.

func (*Client) Destroy

func (c *Client) Destroy(id string) ExecDestroy

Destroy creates an ExecDestroy operation for the specified unique identifier. It prepares a DestroyRequestPayload with the given ID and associates it with the client. The returned ExecDestroy can be used to execute the destroy operation on the KMIP server by calling Exec or ExecContext.

Parameters:

  • id: The unique identifier of the object to be destroyed.

Returns:

  • ExecDestroy: An executable destroy operation configured with the provided identifier.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecDestroy.
  • If the object does not exist or cannot be destroyed, an error will be returned during execution.
Example

ExampleClient_Destroy demonstrates destroying a key from the server.

package main

import (
	"fmt"
	"log"

	"github.com/ovh/kmip-go/kmipclient"
)

func main() {
	client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// Destroy a key by its unique identifier
	resp, err := client.Destroy("key-12345").Exec()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Destroyed key: %s\n", resp.UniqueIdentifier)
}

func (*Client) Encrypt added in v0.2.5

func (c *Client) Encrypt(id string) ExecEncryptWantsData

Encrypt creates an ExecEncryptWantsData builder for encrypting data with the specified key ID. Returns an ExecEncryptWantsData that can be further configured before calling Data().

Example

ExampleClient_Encrypt demonstrates encrypting data with a key.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create a random Nonce / IV
iv := make([]byte, kmip.AES_GCM.IVLength)
_, _ = rand.Read(iv)

// Encrypt data using an existing key
plaintext := []byte("Hello, KMIP!")
resp, err := client.Encrypt("key-12345").
	WithCryptographicParameters(kmip.AES_GCM).
	WithIvCounterNonce(iv). // May be optional depending on the cryptographic parameters used
	Data(plaintext).
	Exec()
if err != nil {
	log.Fatal(err)
}

// Concatenate IV, ciphertext and tag, then display the result
cipher := append(resp.IVCounterNonce, resp.Data...)
cipher = append(cipher, resp.AuthenticatedEncryptionTag...)
fmt.Println("Cipher text:", hex.EncodeToString(cipher))

func (*Client) Export added in v0.7.0

func (c *Client) Export(id string) ExecExport

Export initializes an export operation with the client for a given key ID.

func (*Client) Get

func (c *Client) Get(id string) ExecGet

Get creates an ExecGet instance to execute a KMIP Get operation. This function prepares a Get request for the object identified by the given unique identifier. The returned ExecGet must be executed using Exec or ExecContext to perform the operation.

Parameters:

  • id: Unique identifier of the KMIP object to retrieve.

Returns:

  • ExecGet: Executor for the Get operation, pre-filled with the unique identifier.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecGet.
Example

ExampleClient_Get demonstrates retrieving a symmetric key from the server.

package main

import (
	"encoding/hex"
	"fmt"
	"log"

	"github.com/ovh/kmip-go/kmipclient"
)

func main() {
	client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// Get a key by its unique identifier
	resp, err := client.Get("key-12345").Exec()
	if err != nil {
		log.Fatal(err)
	}

	key, err := resp.SymmetricKey()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Key Material:", hex.EncodeToString(key))
}

func (*Client) GetAttributeList

func (c *Client) GetAttributeList(id string) ExecGetAttributeList

GetAttributeList creates an ExecGetAttributeList operation to retrieve the list of attribute names for the object identified by the given unique identifier. The returned ExecGetAttributeList can be executed to obtain the list of attribute names supported by the object.

Parameters:

  • id: The unique identifier of the object whose attribute list is to be retrieved.

Returns:

  • ExecGetAttributeList: An executor for the get attribute list operation.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecGetAttributeList.
  • If the object does not exist or the server rejects the operation, an error will be returned during execution.
Example

ExampleClient_GetAttributeList demonstrates getting all available attributes for a key.

package main

import (
	"fmt"
	"log"

	"github.com/ovh/kmip-go/kmipclient"
)

func main() {
	client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// Get list of all attributes for a key
	resp, err := client.GetAttributeList("key-12345").Exec()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Key has %d attributes:\n", len(resp.AttributeName))
	for _, attrName := range resp.AttributeName {
		fmt.Printf("  - %s\n", attrName)
	}
}

func (*Client) GetAttributes

func (c *Client) GetAttributes(id string, attributes ...kmip.AttributeName) ExecGetAttributes

GetAttributes retrieves the specified attributes for a given unique identifier. It returns an ExecGetAttributes instance which can be used to execute the request. Note that the returned value does not execute the operation. Exec() or ExecContext() must be called to execute the operation.

Parameters:

  • id: The unique identifier for which attributes are to be retrieved.
  • attributes: A variadic list of attribute names to be retrieved.

Returns:

  • ExecGetAttributes: An instance that can be used to execute the GetAttributes request.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecGetAttributes.
  • If the object does not exist or the server rejects the operation, an error will be returned during execution.
Example

ExampleClient_GetAttributes demonstrates retrieving object attributes.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Get specific attributes for a key
resp, err := client.GetAttributes("key-12345",
	kmip.AttributeNameCryptographicAlgorithm,
	kmip.AttributeNameCryptographicLength,
	kmip.AttributeNameState,
).Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Key attributes:\n")
for _, attr := range resp.Attribute {
	fmt.Printf("  %s: %v\n", attr.AttributeName, attr.AttributeValue)
}

func (*Client) GetUsageAllocation

func (c *Client) GetUsageAllocation(id string, limitCount int64) ExecGetUsageAllocation

GetUsageAllocation creates an ExecGetUsageAllocation instance with the specified unique identifier and usage limits count. This function initializes the request payload with the provided parameters. Note that the returned value does not execute the operation; the Exec or ExecContext method must be called to perform the execution.

Parameters:

  • id: A string representing the unique identifier for the usage allocation request.
  • limitCount: An int64 representing the usage limits count for the allocation.

Returns:

  • ExecGetUsageAllocation: An instance initialized with the provided client and request payload.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecGetUsageAllocation.
  • If the object does not exist or the server rejects the operation, an error will be returned during execution.

func (*Client) Import added in v0.7.0

func (c *Client) Import(id string, object kmip.Object) ExecImport

Import initializes an import operation with the client.

func (*Client) Locate

func (c *Client) Locate() ExecLocate

Locate creates an ExecLocate operation for searching KMIP objects based on attributes and filters. The returned ExecLocate can be further configured with additional filters (e.g., storage status mask, max items, offset, group member) and executed to perform the locate operation.

Returns:

  • ExecLocate: An executor for the locate operation.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecLocate.
  • If the search criteria are not supported or the server rejects the operation, an error will be returned during execution.
Example

ExampleClient_Locate demonstrates searching for keys by attributes.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Find all AES keys with a specific name
resp, err := client.Locate().
	WithName("my-aes-key").
	WithAttribute(kmip.AttributeNameCryptographicAlgorithm, kmip.CryptographicAlgorithmAES).
	WithMaxItems(10).
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Found %d matching keys\n", len(resp.UniqueIdentifier))
for _, id := range resp.UniqueIdentifier {
	fmt.Printf("  - %s\n", id)
}
Example (ByState)

ExampleClient_Locate_byState demonstrates searching for keys by their state.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Find all active AES keys
resp, err := client.Locate().
	WithAttribute(kmip.AttributeNameCryptographicAlgorithm, kmip.CryptographicAlgorithmAES).
	WithAttribute(kmip.AttributeNameState, kmip.StateActive).
	WithMaxItems(5).
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Found %d active AES keys\n", len(resp.UniqueIdentifier))

func (*Client) ModifyAttribute

func (c *Client) ModifyAttribute(id string, name kmip.AttributeName, value any) ExecModifyAttribute

ModifyAttribute creates an ExecModifyAttribute operation to modify an attribute of an existing object identified by the given unique identifier and attribute name. The returned ExecModifyAttribute can be further configured (e.g., with an index) and executed to perform the modification.

Parameters:

  • id: The unique identifier of the object whose attribute will be modified.
  • name: The name of the attribute to modify.
  • value: The new value to set for the attribute.

Returns:

  • ExecModifyAttribute: An executor for the modify attribute operation.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecModifyAttribute.
  • If the attribute or object does not exist, or the server rejects the operation, an error will be returned during execution.

func (*Client) ObtainLease

func (c *Client) ObtainLease(id string) ExecObtainLease

ObtainLease creates an ExecObtainLease operation to obtain a lease for the object identified by the given unique identifier. The returned ExecObtainLease can be executed to perform the obtain lease operation.

Parameters:

  • id: The unique identifier of the object for which to obtain a lease.

Returns:

  • ExecObtainLease: An executor for the obtain lease operation.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecObtainLease.
  • If the object does not exist or the server rejects the operation, an error will be returned during execution.

func (*Client) Query

func (c *Client) Query() ExecQuery

func (*Client) Recover

func (c *Client) Recover(id string) ExecRecover

Recover creates and returns an ExecRecover instance initialized with the provided unique identifier. This method prepares a recovery request payload for the specified object ID, allowing the client to initiate a recover operation using the KMIP protocol. The returned ExecRecover can be executed to perform the recovery operation.

Parameters:

  • id: The unique identifier of the object to be recovered.

Returns:

  • ExecRecover: Executor for the Recover operation, pre-filled with the unique identifier.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecRecover.
  • If the object does not exist or cannot be recovered, an error will be returned during execution.

func (*Client) Register

func (c *Client) Register() ExecRegisterWantType

Register initializes the registration process for a KMIP object. Returns an ExecRegisterWantType which can be used to specify the type of object to register.

Returns:

  • ExecRegisterWantType: Used to configure and execute the register operation.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecRegister.
Example (Ecdsa_keypair)

ExampleClient_Register_highlevel demonstrates registering an existing and ECDSA keypair from go's stdlib.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create a symmetric key object to register
pkey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
	log.Fatal(err)
}

// Register the private key with attributes
resp, err := client.Register().
	EcdsaPrivateKey(pkey, kmip.CryptographicUsageSign).
	WithName("imported-key").
	Exec()
if err != nil {
	log.Fatal(err)
}

// Register the public key with attributes and a link to the private key
resp2, err := client.Register().
	EcdsaPublicKey(&pkey.PublicKey, kmip.CryptographicUsageVerify).
	WithName("imported-key").
	WithLink(kmip.LinkTypePrivateKeyLink, resp.UniqueIdentifier).
	Exec()
if err != nil {
	log.Fatal(err)
}

// Link the public key into the private key
_, err = client.AddAttribute(resp.UniqueIdentifier, kmip.AttributeNameLink, kmip.Link{
	LinkType:               kmip.LinkTypePublicKeyLink,
	LinkedObjectIdentifier: resp2.UniqueIdentifier,
}).Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Println("Registered key-pair")
Example (Highlevel)

ExampleClient_Register_highlevel demonstrates registering an existing key using high-level API

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create a symmetric key object to register
keyBytes := make([]byte, 32) // 256-bit key
// In practice, you would fill this with actual key material

// Register the key with attributes
resp, err := client.Register().
	SymmetricKey(kmip.CryptographicAlgorithmAES, kmip.CryptographicUsageEncrypt|kmip.CryptographicUsageDecrypt, keyBytes).
	WithName("imported-key").
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Registered key with ID: %s\n", resp.UniqueIdentifier)
Example (Raw)

ExampleClient_Register_raw demonstrates registering an existing key using low level kmip object

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Create a symmetric key object to register
keyBytes := make([]byte, 32) // 256-bit key
// In practice, you would fill this with actual key material

symKey := &kmip.SymmetricKey{
	KeyBlock: kmip.KeyBlock{
		KeyFormatType: kmip.KeyFormatTypeRaw,
		KeyValue: &kmip.KeyValue{
			Plain: &kmip.PlainKeyValue{
				KeyMaterial: kmip.KeyMaterial{
					Bytes: &keyBytes,
				},
			},
		},
		CryptographicAlgorithm: kmip.CryptographicAlgorithmAES,
		CryptographicLength:    256,
	},
}

// Register the key with attributes
resp, err := client.Register().
	Object(symKey).
	WithName("imported-key").
	WithAttribute(kmip.AttributeNameCryptographicUsageMask,
		kmip.CryptographicUsageEncrypt|kmip.CryptographicUsageDecrypt).
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Registered key with ID: %s\n", resp.UniqueIdentifier)

func (*Client) Rekey

func (c *Client) Rekey(id string) ExecRekey

Rekey creates an ExecRekey operation for the specified unique identifier. This method prepares a rekey request payload for the specified object ID using the client instance. The returned ExecRekey can be used to execute the rekey operation by calling Exec or ExecContext.

Parameters:

  • id: The unique identifier of the object to be rekeyed.

Returns:

  • ExecRekey: Executor for the Rekey operation, pre-filled with the unique identifier.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecRekey.
  • If the object does not exist or cannot be rekeyed, an error will be returned during execution.

func (*Client) RekeyKeyPair added in v0.4.0

func (c *Client) RekeyKeyPair(privateKeyId string) ExecRekeyKeyPair

RekeyKeyPair initializes a RekeyKeyPair operation for the given private key ID. It returns an ExecRekeyKeyPair builder for setting template attributes and executing the operation.

func (*Client) Request

func (c *Client) Request(ctx context.Context, payload kmip.OperationPayload) (kmip.OperationPayload, error)

Request sends a single KMIP operation request with the specified payload and returns the corresponding response payload. It wraps the Batch method to handle single-operation requests, returning the response payload or an error if the operation fails.

Parameters:

  • ctx - The context for controlling cancellation and deadlines.
  • payload - The KMIP operation payload to send.

Returns:

  • The response payload for the operation, or an error if the request fails or the response contains an error.

func (*Client) Revoke

func (c *Client) Revoke(id string) ExecRevoke

Revoke creates an ExecRevoke operation for the specified unique identifier. This method prepares a revoke request payload for the specified object ID using the client instance. The returned ExecRevoke can be used to execute the revoke operation by calling Exec or ExecContext.

Parameters:

  • id: The unique identifier of the object to be revoked.

Returns:

  • ExecRevoke: Executor for the Revoke operation, pre-filled with the unique identifier.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecRevoke.
  • If the object does not exist or cannot be revoked, an error will be returned during execution.
Example

ExampleClient_Revoke demonstrates revoking a key.

client, err := kmipclient.Dial("your-kmip-server.example.com:5696")
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Revoke a key with a specific reason
resp, err := client.Revoke("key-12345").
	WithRevocationReasonCode(kmip.RevocationReasonCodeKeyCompromise).
	WithRevocationMessage("Key may have been compromised").
	Exec()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Revoked key: %s\n", resp.UniqueIdentifier)

func (*Client) Roundtrip

func (c *Client) Roundtrip(ctx context.Context, msg *kmip.RequestMessage) (*kmip.ResponseMessage, error)

Roundtrip sends a KMIP request message through the client's middleware chain and returns the response. Each middleware can process the request and response, or pass it along to the next middleware in the chain. The final handler sends the request using the client's doRountrip method.

Parameters:

  • ctx - The context for controlling cancellation and deadlines.
  • msg - The KMIP request message to be sent.

Returns:

  • *kmip.ResponseMessage - The KMIP response message received.
  • error - Any error encountered during processing or sending the request.

func (*Client) Sign added in v0.2.5

func (c *Client) Sign(id string) ExecSignWantsData

Sign initializes a signing operation for the object identified by the given unique identifier. It returns an ExecSignWantsData struct, which allows the caller to provide the data to be signed. The signing operation is not executed until the data is supplied.

func (*Client) SignatureVerify added in v0.2.5

func (c *Client) SignatureVerify(id string) ExecSignatureVerifyWantsData

SignatureVerify initializes a signature verification operation for the object identified by the given unique identifier. It returns an ExecSignatureVerifyWantsData struct, which allows the caller to provide the data and signature to be verified. The verification process is performed using the cryptographic object referenced by the unique identifier.

Parameters:

  • id: The unique identifier of the cryptographic object to be used for signature verification.

Returns:

  • ExecSignatureVerifyWantsData: A struct for chaining the next steps of the signature verification process.

Errors:

  • This function does not return errors directly. Errors may be returned when executing the ExecSignatureVerifyWantsData or ExecSignatureVerify.
  • If the object does not exist or the server rejects the operation, an error will be returned during execution.

func (*Client) Signer added in v0.3.4

func (c *Client) Signer(ctx context.Context, privateKeyId, publicKeyId string) (crypto.Signer, error)

Signer creates a crypto.Signer using the provided private and public key IDs. It verifies the attributes of the keys to ensure they are suitable for signing and verifying operations. If only one key ID is provided, it attempts to find the corresponding linked key ID.

Parameters:

  • ctx: The context for the operation.
  • privateKeyId: The ID of the private key. Can be empty if publicKeyId is provided.
  • publicKeyId: The ID of the public key. Can be empty if privateKeyId is provided.

Returns:

  • crypto.Signer: The signer object that can be used for signing operations.
  • error: An error if the key attributes are invalid or if required keys are missing.

func (*Client) Version

func (c *Client) Version() kmip.ProtocolVersion

Version returns the KMIP protocol version used by the client.

type ExecActivate

ExecActivate is a type alias for Executor that operates on ActivateRequestPayload and ActivateResponsePayload. It is used to execute activation operations within the KMIP client. Use Exec or ExecContext to perform the operation.

Usage:

exec := client.Activate("object-id")
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the activation operation if the object does not exist, is not in a state that can be activated, or if the server returns an error.

type ExecAddAttribute

ExecAddAttribute is a specialized executor for handling AddAttribute operations. It embeds the generic Executor with request and response payload types specific to the AddAttribute KMIP operation, facilitating the execution and management of attribute addition requests and their corresponding responses.

Usage:

exec := client.AddAttribute("object-id", kmip.AttributeNameCustom, "value")
exec = exec.WithIndex(1) // Optional: set attribute index
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the add attribute operation if the object does not exist, if the attribute is not supported, or if the server returns an error.

func (ExecAddAttribute) WithIndex

func (ex ExecAddAttribute) WithIndex(index int32) ExecAddAttribute

WithIndex sets the AttributeIndex field of the request's Attribute to the provided index value. This is useful when adding an attribute that supports multiple values and you want to specify the position of the new attribute value.

Parameters:

  • index: The index at which to add the attribute value.

Returns:

  • ExecAddAttribute: The updated ExecAddAttribute instance to allow for method chaining.

Errors:

  • No error is returned by this method. If the index is not supported by the server or is out of range, an error may occur during execution.

type ExecArchive

ExecArchive is a type alias for Executor that operates on ArchiveRequestPayload and ArchiveResponsePayload types. It is used to execute archive operations within the KMIP client, handling the request and response payloads specific to the archive functionality.

Usage:

exec := client.Archive("object-id")
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the archive operation if the object does not exist, is not in a state that can be archived, or if the server returns an error.

type ExecCreate

ExecCreate is a wrapper struct that embeds AttributeExecutor to facilitate the execution of KMIP Create operations. It manages the request and response payloads specific to the Create operation, providing type safety and reuse of attribute execution logic.

func (ExecCreate) WithTemplate deprecated

func (ex ExecCreate) WithTemplate(name string, nameType kmip.NameType) ExecCreate

WithTemplate adds a new name with the specified value and type to the TemplateAttribute of the request.

Deprecated: Templates have been deprecated in KMIP v1.3.

func (ExecCreate) WithTemplates deprecated

func (ex ExecCreate) WithTemplates(names ...kmip.Name) ExecCreate

WithTemplates appends the provided KMIP names to the TemplateAttribute's Name slice in the ExecCreate request.

Deprecated: Templates have been deprecated in KMIP v1.3.

type ExecCreateKeyPair

ExecCreateKeyPair is a specialized executor for handling CreateKeyPair operations. It embeds the generic Executor with request and response payload types specific to key pair creation, enabling execution of KMIP CreateKeyPair requests and processing of their responses.

Usage:

exec := client.CreateKeyPair().RSA(2048, privateUsage, publicUsage)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the key pair creation operation if the parameters are invalid, the server does not support the requested algorithm or curve, or if the server returns an error.

func (ExecCreateKeyPair) Common

Common returns an ExecCreateKeyPairAttr that provides access to the common template attributes and names within a CreateKeyPairRequestPayload. This method constructs an attribute executor for handling the common attributes and names, ensuring backward compatibility with existing structures. It is primarily used to facilitate attribute manipulation for key pair creation requests in the KMIP client.

Usage:

attr := exec.Common().WithAttribute(...)
names := exec.Common().WithTemplates(...)

Errors:

  • No error is returned by this method. Errors may occur during execution if the attributes are not supported.

func (ExecCreateKeyPair) ECDSA

func (ex ExecCreateKeyPair) ECDSA(curve kmip.RecommendedCurve, privateUsage, publicUsage kmip.CryptographicUsageMask) ExecCreateKeyPairAttr

ECDSA configures the ExecCreateKeyPair operation for generating an ECDSA key pair. It sets the cryptographic algorithm to ECDSA, specifies the curve and its bit length, and applies the provided cryptographic usage masks to the public and private keys.

Parameters:

  • curve: The recommended elliptic curve to use for key generation.
  • privateUsage: The cryptographic usage mask for the private key.
  • publicUsage: The cryptographic usage mask for the public key.

Returns:

  • ExecCreateKeyPairAttr: The configured key pair creation attributes.

Errors:

  • Errors may be returned when executing the operation if the server does not support the requested curve.

func (ExecCreateKeyPair) PrivateKey

func (ex ExecCreateKeyPair) PrivateKey() ExecCreateKeyPairAttr

PrivateKey returns an ExecCreateKeyPairAttr configured to operate on the PrivateKeyTemplateAttribute of a CreateKeyPairRequestPayload. This allows manipulation of private key attributes and names within the key pair creation request, supporting both attribute and name access for backward compatibility.

Usage:

attr := exec.PrivateKey().WithAttribute(...)
names := exec.PrivateKey().WithTemplates(...)

Errors:

  • No error is returned by this method. Errors may occur during execution if the attributes are not supported.

func (ExecCreateKeyPair) PublicKey

PublicKey returns an ExecCreateKeyPairAttr configured to operate on the PublicKeyTemplateAttribute of the CreateKeyPairRequestPayload. This allows for manipulation of public key attributes and names within the key pair creation request, supporting backward compatibility for legacy field usage.

Usage:

attr := exec.PublicKey().WithAttribute(...)
names := exec.PublicKey().WithTemplates(...)

Errors:

  • No error is returned by this method. Errors may occur during execution if the attributes are not supported.

func (ExecCreateKeyPair) RSA

func (ex ExecCreateKeyPair) RSA(bitlen int, privateUsage, publicUsage kmip.CryptographicUsageMask) ExecCreateKeyPairAttr

RSA configures the ExecCreateKeyPair to generate an RSA key pair with the specified bit length and usage masks. It sets the cryptographic algorithm to RSA, assigns the provided bit length, and applies the given usage masks to the public and private keys respectively. If the bit length is out of the valid int32 range, the function panics.

Parameters:

  • bitlen: The length of the RSA key in bits.
  • privateUsage: The cryptographic usage mask for the private key.
  • publicUsage: The cryptographic usage mask for the public key.

Returns:

  • ExecCreateKeyPairAttr: The configured key pair attributes for RSA key generation.

Errors:

  • Panics if bitlen is negative or exceeds the maximum int32 value.
  • Errors may be returned when executing the operation if the server does not support the requested bit length.

type ExecCreateKeyPairAttr

type ExecCreateKeyPairAttr struct {
	AttributeExecutor[*payloads.CreateKeyPairRequestPayload, *payloads.CreateKeyPairResponsePayload, ExecCreateKeyPairAttr]
	// contains filtered or unexported fields
}

func (ExecCreateKeyPairAttr) Common

func (ExecCreateKeyPairAttr) PrivateKey

func (ExecCreateKeyPairAttr) PublicKey

func (ExecCreateKeyPairAttr) WithTemplate deprecated

func (ex ExecCreateKeyPairAttr) WithTemplate(name string, nameType kmip.NameType) ExecCreateKeyPairAttr

Deprecated: Templates have been deprecated in KMIP v1.3.

func (ExecCreateKeyPairAttr) WithTemplates deprecated

func (ex ExecCreateKeyPairAttr) WithTemplates(names ...kmip.Name) ExecCreateKeyPairAttr

Deprecated: Templates have been deprecated in KMIP v1.3.

type ExecCreateWantType

type ExecCreateWantType struct {
	// contains filtered or unexported fields
}

ExecCreateWantType encapsulates the dependencies required to execute a create operation, primarily holding a reference to the Client used for communication with the KMIP server.

func (ExecCreateWantType) AES

func (ex ExecCreateWantType) AES(length int, usage kmip.CryptographicUsageMask) ExecCreate

AES creates a symmetric key of the specified length using the AES cryptographic algorithm, and assigns the provided cryptographic usage mask. It returns an ExecCreate instance configured for AES key creation.

Parameters:

  • length: The length of the AES key in bits (e.g., 128, 192, 256).
  • usage: The intended cryptographic usage mask for the key.

Returns:

  • ExecCreate: An instance configured for AES key creation.

Errors:

  • Panics if length is negative or exceeds math.MaxInt32.
  • Errors may be returned when executing the operation if the server does not support the requested key length.

func (ExecCreateWantType) Object

func (ex ExecCreateWantType) Object(objectType kmip.ObjectType, attrs ...kmip.Attribute) ExecCreate

Object creates a new ExecCreate instance configured to create a KMIP object of the specified type, with the provided attributes. It constructs the appropriate CreateRequestPayload and sets up the attribute executor for further configuration or execution.

Parameters:

  • objectType: The KMIP object type to be created.
  • attrs: Optional list of KMIP attributes to associate with the object.

Returns:

  • ExecCreate: An executor for the create operation, allowing further configuration or execution.

func (ExecCreateWantType) Skipjack deprecated

func (ex ExecCreateWantType) Skipjack(usage kmip.CryptographicUsageMask) ExecCreate

Skipjack creates a symmetric key with the SKIPJACK cryptographic algorithm and a key length of 80 bits. It sets the specified cryptographic usage mask for the key. Returns an ExecCreate instance configured with these parameters.

Deprecated: SKIPJACK is insecure and shouldn't be used.

Errors:

  • Errors may be returned when executing the operation if the server does not support SKIPJACK.

func (ExecCreateWantType) SymmetricKey

func (ex ExecCreateWantType) SymmetricKey(alg kmip.CryptographicAlgorithm, length int, usage kmip.CryptographicUsageMask) ExecCreate

SymmetricKey configures the creation of a symmetric key object with the specified cryptographic algorithm, key length, and usage mask. It panics if the provided length is negative or exceeds the maximum value for an int32. The method sets the object type to SymmetricKey and attaches the relevant cryptographic attributes.

Parameters:

  • alg: The cryptographic algorithm to use for the symmetric key (e.g., AES, 3DES).
  • length: The length of the key in bits. Must be between 0 and math.MaxInt32.
  • usage: The intended usage mask for the key (bitmask of allowed operations).

Returns:

  • ExecCreate: The updated ExecCreate object with the symmetric key attributes set.

Errors:

  • Panics if length is negative or exceeds math.MaxInt32.
  • Errors may be returned when executing the operation if the server does not support the requested algorithm or key length.

func (ExecCreateWantType) TDES deprecated

func (ex ExecCreateWantType) TDES(length int, usage kmip.CryptographicUsageMask) ExecCreate

TDES creates a symmetric key using the 3DES cryptographic algorithm with the specified key length and usage mask. It returns an ExecCreate configured for 3DES key creation.

Parameters:

  • length: The length of the 3DES key in bits.
  • usage: The intended cryptographic usage mask for the key.

Returns:

  • ExecCreate: An instance configured for 3DES key creation.

Deprecated: 3DES is considered insecure and shouldn't be used.

Errors:

  • Panics if length is negative or exceeds math.MaxInt32.
  • Errors may be returned when executing the operation if the server does not support the requested key length.

type ExecDecrypt added in v0.2.5

ExecDecrypt is a specialized executor for handling Decrypt operations. It embeds the generic Executor with request and response payload types specific to the Decrypt KMIP operation, facilitating the execution and management of decrypt requests and their responses.

Usage:

exec := client.Decrypt("key-id").WithIvCounterNonce(...).WithAAD(...).WithAuthTag(...).Data(...)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the decrypt operation if the key is invalid, the server rejects the operation, or the cryptographic parameters are not supported.

type ExecDecryptWantsData added in v0.2.5

type ExecDecryptWantsData struct {
	// contains filtered or unexported fields
}

ExecDecryptWantsData is a builder for configuring decryption parameters before providing the data to decrypt. Use WithIvCounterNonce, WithAAD, WithCryptographicParameters, and WithAuthTag to set decryption options, then call Data() to finalize.

func (ExecDecryptWantsData) Data added in v0.2.5

func (ex ExecDecryptWantsData) Data(data []byte) ExecDecrypt

Data finalizes the encryption or decryption request by providing the data to be processed. Returns the corresponding ExecEncrypt or ExecDecrypt executor.

func (ExecDecryptWantsData) WithAAD added in v0.2.5

WithAAD sets the additional authenticated data (AAD) for the encryption or decryption operation. Returns the updated builder for method chaining.

func (ExecDecryptWantsData) WithAuthTag added in v0.2.5

func (ex ExecDecryptWantsData) WithAuthTag(tag []byte) ExecDecryptWantsData

WithAuthTag sets the authentication tag for the decryption operation (for AEAD modes). Returns the updated builder for method chaining.

func (ExecDecryptWantsData) WithCryptographicParameters added in v0.2.5

func (ex ExecDecryptWantsData) WithCryptographicParameters(params kmip.CryptographicParameters) ExecDecryptWantsData

WithCryptographicParameters sets the cryptographic parameters for the encryption or decryption operation. Returns the updated builder for method chaining.

func (ExecDecryptWantsData) WithIvCounterNonce added in v0.2.5

func (ex ExecDecryptWantsData) WithIvCounterNonce(iv []byte) ExecDecryptWantsData

WithIvCounterNonce sets the IV/counter/nonce for the encryption or decryption operation. Returns the updated builder for method chaining.

type ExecDeleteAttribute

ExecDeleteAttribute is a specialized executor for handling DeleteAttribute operations. It embeds the generic Executor with request and response payload types specific to the DeleteAttribute KMIP operation, facilitating the execution and management of attribute deletion requests and their corresponding responses.

Usage:

exec := client.DeleteAttribute("object-id", kmip.AttributeNameCustom)
exec = exec.WithIndex(1) // Optional: set attribute index
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the delete attribute operation if the object or attribute does not exist, or if the server returns an error.

func (ExecDeleteAttribute) WithIndex

func (ex ExecDeleteAttribute) WithIndex(index int32) ExecDeleteAttribute

WithIndex sets the AttributeIndex field of the request to the provided index value. This is useful when deleting an attribute that supports multiple values and you want to specify the position of the attribute value to delete.

Parameters:

  • index: The index of the attribute value to delete.

Returns:

  • ExecDeleteAttribute: The updated ExecDeleteAttribute instance to allow for method chaining.

Errors:

  • No error is returned by this method. If the index is not supported by the server or is out of range, an error may occur during execution.

type ExecDestroy

ExecDestroy is a type alias for Executor specialized with DestroyRequestPayload and DestroyResponsePayload. It is used to execute destroy operations in the KMIP client, handling the request and response payloads specific to the destroy operation.

Usage:

exec := client.Destroy("object-id")
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the destroy operation if the object does not exist, is not in a state that can be destroyed, or if the server returns an error.

type ExecEncrypt added in v0.2.5

ExecEncrypt is a specialized executor for handling Encrypt operations. It embeds the generic Executor with request and response payload types specific to the Encrypt KMIP operation, facilitating the execution and management of encrypt requests and their responses.

Usage:

exec := client.Encrypt("key-id").WithIvCounterNonce(...).WithAAD(...).Data(...)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the encrypt operation if the key is invalid, the server rejects the operation, or the cryptographic parameters are not supported.

type ExecEncryptWantsData added in v0.2.5

type ExecEncryptWantsData struct {
	// contains filtered or unexported fields
}

ExecEncryptWantsData is a builder for configuring encryption parameters before providing the data to encrypt. Use WithIvCounterNonce, WithAAD, and WithCryptographicParameters to set encryption options, then call Data() to finalize.

func (ExecEncryptWantsData) Data added in v0.2.5

func (ex ExecEncryptWantsData) Data(data []byte) ExecEncrypt

Data finalizes the encryption or decryption request by providing the data to be processed. Returns the corresponding ExecEncrypt or ExecDecrypt executor.

func (ExecEncryptWantsData) WithAAD added in v0.2.5

WithAAD sets the additional authenticated data (AAD) for the encryption or decryption operation. Returns the updated builder for method chaining.

func (ExecEncryptWantsData) WithCryptographicParameters added in v0.2.5

func (ex ExecEncryptWantsData) WithCryptographicParameters(params kmip.CryptographicParameters) ExecEncryptWantsData

WithCryptographicParameters sets the cryptographic parameters for the encryption or decryption operation. Returns the updated builder for method chaining.

func (ExecEncryptWantsData) WithIvCounterNonce added in v0.2.5

func (ex ExecEncryptWantsData) WithIvCounterNonce(iv []byte) ExecEncryptWantsData

WithIvCounterNonce sets the IV/counter/nonce for the encryption or decryption operation. Returns the updated builder for method chaining.

type ExecExport added in v0.7.0

ExecExport represents the execution of an export operation with the KMIP client.

func (ExecExport) WithKeyCompressionType added in v0.7.0

func (ex ExecExport) WithKeyCompressionType(keyCompressionType kmip.KeyCompressionType) ExecExport

WithKeyCompressionType sets the KeyCompressionType in the export request.

func (ExecExport) WithKeyFormatType added in v0.7.0

func (ex ExecExport) WithKeyFormatType(keyFormatType kmip.KeyFormatType) ExecExport

WithKeyFormatType sets the KeyFormatType in the export request.

func (ExecExport) WithKeyWrapType added in v0.7.0

func (ex ExecExport) WithKeyWrapType(keyWrapType kmip.KeyWrapType) ExecExport

WithKeyWrapType sets the KeyWrapType in the export request.

func (ExecExport) WithKeyWrappingSpecification added in v0.7.0

func (ex ExecExport) WithKeyWrappingSpecification(keyWrappingSpecification *kmip.KeyWrappingSpecification) ExecExport

WithKeyWrappingSpecification sets the KeyWrappingSpecification in the export request.

type ExecGet

ExecGet is a specialized executor for handling KMIP Get operations. It embeds the generic Executor with request and response payload types specific to the Get operation, enabling type-safe execution of Get requests.

Use the WithKeyFormat, WithKeyWrapType, WithKeyCompression, or WithKeyWrapping methods to further customize the Get request before execution.

func (ExecGet) WithKeyCompression

func (ex ExecGet) WithKeyCompression(compression kmip.KeyCompressionType) ExecGet

WithKeyCompression sets the KeyCompressionType for the Get request. Use this to specify the desired compression for the key material.

Parameters:

  • compression: The desired key compression type.

Returns:

  • ExecGet: The updated ExecGet with the KeyCompressionType set.

Errors:

  • No error is returned by this method. If the compression type is not supported by the server, an error may occur during execution.

func (ExecGet) WithKeyFormat

func (ex ExecGet) WithKeyFormat(format kmip.KeyFormatType) ExecGet

func (ExecGet) WithKeyWrapType

func (ex ExecGet) WithKeyWrapType(keyWrapType kmip.KeyWrapType) ExecGet

WithKeyWrapType sets the KeyWrapType for the Get request. Use this to specify the desired wrapping format for the key material.

Parameters:

  • keyWrapType: The desired key wrap type.

Returns:

  • ExecGet: The updated ExecGet with the KeyWrapType set.

Errors:

  • No error is returned by this method. If the wrap type is not supported by the server, an error may occur during execution.

func (ExecGet) WithKeyWrapping

func (ex ExecGet) WithKeyWrapping(spec kmip.KeyWrappingSpecification) ExecGet

WithKeyWrapping sets the KeyWrappingSpecification for the Get request. Use this to specify how the key material should be wrapped in the response.

Parameters:

  • spec: The key wrapping specification.

Returns:

  • ExecGet: The updated ExecGet with the KeyWrappingSpecification set.

Errors:

  • No error is returned by this method. If the wrapping specification is not supported by the server, an error may occur during execution.

type ExecGetAttributeList

ExecGetAttributeList is a type alias for Executor that operates on GetAttributeListRequestPayload and GetAttributeListResponsePayload. It is used to execute get attribute list operations within the KMIP client, handling the request and response payloads specific to the get attribute list functionality.

Usage:

exec := client.GetAttributeList("object-id")
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the get attribute list operation if the object does not exist, or if the server returns an error.

type ExecGetAttributes

ExecGetAttributes is a specialized executor for handling GetAttributes operations. It embeds the generic Executor with request and response payload types specific to the GetAttributes KMIP operation, facilitating the execution and management of attribute retrieval requests and their corresponding responses.

Usage:

exec := client.GetAttributes("object-id", kmip.AttributeNameCustom)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the get attributes operation if the object does not exist, or if the server returns an error.

func (ExecGetAttributes) WithAttributes

func (ex ExecGetAttributes) WithAttributes(names ...kmip.AttributeName) ExecGetAttributes

WithAttributes appends the provided attribute names to the request's AttributeName slice and returns the updated ExecGetAttributes instance.

Parameters:

  • names: A variadic list of kmip.AttributeName to be added to the request.

Returns:

  • ExecGetAttributes: An updated ExecGetAttributes instance with the provided attribute names appended.

Errors:

  • No error is returned by this method. If the attribute names are not supported by the server, an error may occur during execution.

type ExecGetUsageAllocation

ExecGetUsageAllocation is a type alias for Executor that operates on GetUsageAllocationRequestPayload and GetUsageAllocationResponsePayload. It is used to execute get usage allocation operations within the KMIP client, handling the request and response payloads specific to the get usage allocation functionality.

Usage:

exec := client.GetUsageAllocation("object-id", 10)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the get usage allocation operation if the object does not exist, or if the server returns an error.

type ExecImport added in v0.7.0

ExecImport represents the execution of an import operation with the KMIP client.

func (ExecImport) WithKeyWrapType added in v0.7.0

func (ex ExecImport) WithKeyWrapType(keyWrapType kmip.KeyWrapType) ExecImport

WithKeyWrapType sets the KeyWrapType in the import request.

func (ExecImport) WithReplaceExisting added in v0.7.0

func (ex ExecImport) WithReplaceExisting(replaceExisting bool) ExecImport

WithReplaceExisting sets the ReplaceExisting flag in the import request.

type ExecLocate

ExecLocate is a specialized executor for handling Locate operations. It embeds the generic AttributeExecutor with request and response payload types specific to the Locate KMIP operation, facilitating the execution and management of locate requests and their responses.

Usage:

exec := client.Locate().WithStorageStatusMask(mask).WithMaxItems(10)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the locate operation if the criteria are invalid, or if the server returns an error.

func (ExecLocate) WithMaxItems

func (ex ExecLocate) WithMaxItems(maximum int32) ExecLocate

WithMaxItems sets the maximum number of items to return in the locate response.

Parameters:

  • maximum: The maximum number of items to return.

Returns:

  • ExecLocate: The updated ExecLocate with the maximum items set.

Errors:

  • No error is returned by this method. If the value is not supported by the server, an error may occur during execution.

func (ExecLocate) WithObjectGroupMember

func (ex ExecLocate) WithObjectGroupMember(groupMember kmip.ObjectGroupMember) ExecLocate

WithObjectGroupMember sets the ObjectGroupMember filter for the locate request.

Parameters:

  • groupMember: The object group member filter to apply.

Returns:

  • ExecLocate: The updated ExecLocate with the ObjectGroupMember set.

Errors:

  • No error is returned by this method. If the value is not supported by the server, an error may occur during execution.

func (ExecLocate) WithOffset

func (ex ExecLocate) WithOffset(offset int32) ExecLocate

WithOffset sets the offset for the locate request, specifying how many items to skip before returning results.

Parameters:

  • offset: The number of items to skip.

Returns:

  • ExecLocate: The updated ExecLocate with the offset set.

Errors:

  • No error is returned by this method. If the value is not supported by the server, an error may occur during execution.

func (ExecLocate) WithStorageStatusMask

func (ex ExecLocate) WithStorageStatusMask(mask kmip.StorageStatusMask) ExecLocate

WithStorageStatusMask sets the StorageStatusMask filter for the locate request. Use this to filter results by storage status (e.g., online, archival).

Parameters:

  • mask: The storage status mask to filter located objects.

Returns:

  • ExecLocate: The updated ExecLocate with the StorageStatusMask set.

Errors:

  • No error is returned by this method. If the mask is not supported by the server, an error may occur during execution.

type ExecModifyAttribute

ExecModifyAttribute is a specialized executor for handling ModifyAttribute operations. It embeds the generic Executor with request and response payload types specific to the ModifyAttribute KMIP operation, facilitating the execution and management of attribute modification requests and their corresponding responses.

Usage:

exec := client.ModifyAttribute("object-id", kmip.AttributeNameCustom, "new-value")
exec = exec.WithIndex(1) // Optional: set attribute index
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the modify attribute operation if the object or attribute does not exist, or if the server returns an error.

func (ExecModifyAttribute) WithIndex

func (ex ExecModifyAttribute) WithIndex(index int32) ExecModifyAttribute

WithIndex sets the AttributeIndex field of the request's Attribute to the provided index value. This is useful when modifying an attribute that supports multiple values and you want to specify the position of the attribute value to modify.

Parameters:

  • index: The index of the attribute value to modify.

Returns:

  • ExecModifyAttribute: The updated ExecModifyAttribute instance to allow for method chaining.

Errors:

  • No error is returned by this method. If the index is not supported by the server or is out of range, an error may occur during execution.

type ExecObtainLease

ExecObtainLease is a type alias for Executor that operates on ObtainLeaseRequestPayload and ObtainLeaseResponsePayload. It is used to execute obtain lease operations within the KMIP client, handling the request and response payloads specific to the obtain lease functionality.

Usage:

exec := client.ObtainLease("object-id")
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the obtain lease operation if the object does not exist, or if the server returns an error.

type ExecQuery

ExecQuery is a specialized executor for handling Query operations. It embeds the generic Executor with request and response payload types specific to the Query KMIP operation, facilitating the execution and management of query requests and their responses.

The following methods add specific QueryFunction values to the request, allowing you to query for supported operations, objects, server information, namespaces, extensions, attestation types, RNGs, validations, profiles, capabilities, and client registration methods. Some methods are only available in specific KMIP protocol versions (see comments).

Usage:

exec := client.Query().Operations().Objects()
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the query operation if the query function is not supported by the server, or if the server returns an error.

func (ExecQuery) All

func (ex ExecQuery) All() ExecQuery

All adds all supported QueryFunction values to the query request, enabling a comprehensive query for all supported operations, objects, server information, namespaces, extensions, attestation types, RNGs, validations, profiles, capabilities, and client registration methods. This is a convenience method for requesting all available information from the KMIP server in a single query.

Usage:

exec := client.Query().All()
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the query operation if any of the query functions are not supported by the server, or if the server returns an error.

func (ExecQuery) ApplicationNamespaces

func (ex ExecQuery) ApplicationNamespaces() ExecQuery

ApplicationNamespaces adds the QueryFunctionApplicationNamespaces to the query request.

func (ExecQuery) AttestationTypes

func (ex ExecQuery) AttestationTypes() ExecQuery

AttestationTypes adds the QueryFunctionAttestationTypes to the query request. KMIP 1.2 and above. If used with an older protocol version, the server may return an error.

func (ExecQuery) Capabilities

func (ex ExecQuery) Capabilities() ExecQuery

Capabilities adds the QueryFunctionCapabilities to the query request. KMIP 1.3 and above. If used with an older protocol version, the server may return an error.

func (ExecQuery) ClientRegistrationMethods

func (ex ExecQuery) ClientRegistrationMethods() ExecQuery

ClientRegistrationMethods adds the QueryFunctionClientRegistrationMethods to the query request. KMIP 1.3 and above. If used with an older protocol version, the server may return an error.

func (ExecQuery) ExtensionList

func (ex ExecQuery) ExtensionList() ExecQuery

ExtensionList adds the QueryFunctionExtensionList to the query request. KMIP 1.1 and above. If used with an older protocol version, the server may return an error.

func (ExecQuery) ExtensionMap

func (ex ExecQuery) ExtensionMap() ExecQuery

ExtensionMap adds the QueryFunctionExtensionMap to the query request. KMIP 1.1 and above. If used with an older protocol version, the server may return an error.

func (ExecQuery) Objects

func (ex ExecQuery) Objects() ExecQuery

Objects adds the QueryFunctionObjects to the query request.

func (ExecQuery) Operations

func (ex ExecQuery) Operations() ExecQuery

Operations adds the QueryFunctionOperations to the query request.

func (ExecQuery) Profiles

func (ex ExecQuery) Profiles() ExecQuery

Profiles adds the QueryFunctionProfiles to the query request. KMIP 1.3 and above. If used with an older protocol version, the server may return an error.

func (ExecQuery) RNGs

func (ex ExecQuery) RNGs() ExecQuery

RNGs adds the QueryFunctionRNGs to the query request. KMIP 1.3 and above. If used with an older protocol version, the server may return an error.

func (ExecQuery) ServerInformation

func (ex ExecQuery) ServerInformation() ExecQuery

ServerInformation adds the QueryFunctionServerInformation to the query request.

func (ExecQuery) Validations

func (ex ExecQuery) Validations() ExecQuery

Validations adds the QueryFunctionValidations to the query request. KMIP 1.3 and above. If used with an older protocol version, the server may return an error.

type ExecRecover

ExecRecover is a type alias for Executor specialized with RecoverRequestPayload and RecoverResponsePayload. It is used to execute KMIP recover operations, handling the request and response payloads for recovery actions.

Usage:

exec := client.Recover("object-id")
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the recover operation if the object does not exist, is not in a state that can be recovered, or if the server returns an error.

type ExecRegister

ExecRegister is a specialized executor for handling KMIP Register operations. It embeds the generic AttributeExecutor with request and response payload types specific to the Register KMIP operation, facilitating the execution and management of register requests and their responses.

Usage:

exec := client.Register().WithKeyFormat(...).Object(...)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the register operation if the object is invalid, the server rejects the operation, or the key format is not supported.

type ExecRegisterWantType

type ExecRegisterWantType struct {
	// contains filtered or unexported fields
}

ExecRegisterWantType represents the desired type for the register operation. It allows setting the key format and specifying the object to register.

func (ExecRegisterWantType) Certificate

func (ex ExecRegisterWantType) Certificate(kind kmip.CertificateType, value []byte) ExecRegister

Certificate registers a certificate as a KMIP Certificate object. Returns an ExecRegister with the specified certificate set.

func (ExecRegisterWantType) EcdsaPrivateKey

func (ex ExecRegisterWantType) EcdsaPrivateKey(key *ecdsa.PrivateKey, usage kmip.CryptographicUsageMask) ExecRegister

EcdsaPrivateKey registers an ECDSA private key. Returns an ExecRegister with the specified ECDSA private key set. Panics if the key format is unexpected or the curve is unsupported.

func (ExecRegisterWantType) EcdsaPublicKey

func (ex ExecRegisterWantType) EcdsaPublicKey(key *ecdsa.PublicKey, usage kmip.CryptographicUsageMask) ExecRegister

EcdsaPublicKey registers an ECDSA public key. Returns an ExecRegister with the specified ECDSA public key set. Panics if the key format is unexpected or the curve is unsupported.

func (ExecRegisterWantType) Object

func (ex ExecRegisterWantType) Object(value kmip.Object) ExecRegister

Object registers a KMIP object and returns an ExecRegister with the specified object set.

func (ExecRegisterWantType) PemCertificate

func (ex ExecRegisterWantType) PemCertificate(data []byte) ExecRegister

PemCertificate registers a PEM encoded certificate. Returns an ExecRegister with the specified PEM certificate set. If the PEM data is invalid or not a certificate, it returns an error.

func (ExecRegisterWantType) PemKey

func (ex ExecRegisterWantType) PemKey(data []byte, usage kmip.CryptographicUsageMask) ExecRegister

PemKey registers a key from PEM data. Returns an ExecRegister with the specified PEM key set. If the PEM data is invalid or unsupported, it returns an error.

func (ExecRegisterWantType) PemPrivateKey added in v0.2.1

func (ex ExecRegisterWantType) PemPrivateKey(data []byte, usage kmip.CryptographicUsageMask) ExecRegister

PemPrivateKey registers a private key from PEM data. Returns an ExecRegister with the specified PEM private key set. If the PEM data is invalid or unsupported, it returns an error.

func (ExecRegisterWantType) PemPublicKey added in v0.2.1

func (ex ExecRegisterWantType) PemPublicKey(data []byte, usage kmip.CryptographicUsageMask) ExecRegister

PemPublicKey registers a public key from PEM data. It also accepts PEM encoded private keys but will register only the public key part of it. Returns an ExecRegister with the specified PEM public key set. If the PEM data is invalid or unsupported, it returns an error.

func (ExecRegisterWantType) Pkcs1PrivateKey

func (ex ExecRegisterWantType) Pkcs1PrivateKey(der []byte, usage kmip.CryptographicUsageMask) ExecRegister

Pkcs1PrivateKey registers a PKCS#1 private key. Returns an ExecRegister with the specified PKCS#1 private key set. If the DER data is invalid, it returns an error.

func (ExecRegisterWantType) Pkcs1PublicKey

func (ex ExecRegisterWantType) Pkcs1PublicKey(der []byte, usage kmip.CryptographicUsageMask) ExecRegister

Pkcs1PublicKey registers a PKCS#1 public key. Returns an ExecRegister with the specified PKCS#1 public key set. If the DER data is invalid, it returns an error.

func (ExecRegisterWantType) Pkcs8PrivateKey

func (ex ExecRegisterWantType) Pkcs8PrivateKey(der []byte, usage kmip.CryptographicUsageMask) ExecRegister

Pkcs8PrivateKey registers a PKCS#8 private key. Returns an ExecRegister with the specified PKCS#8 private key set. If the DER data is invalid or the key type is unsupported, it returns an error.

func (ExecRegisterWantType) PrivateKey

func (ex ExecRegisterWantType) PrivateKey(key crypto.PrivateKey, usage kmip.CryptographicUsageMask) ExecRegister

PrivateKey registers a private key (RSA or ECDSA). Returns an ExecRegister with the specified private key set. If the key type is unsupported, it returns an error.

func (ExecRegisterWantType) PublicKey

func (ex ExecRegisterWantType) PublicKey(key crypto.PublicKey, usage kmip.CryptographicUsageMask) ExecRegister

PublicKey registers a public key (RSA or ECDSA). Returns an ExecRegister with the specified public key set. If the key type is unsupported, it returns an error.

func (ExecRegisterWantType) RsaPrivateKey

func (ex ExecRegisterWantType) RsaPrivateKey(key *rsa.PrivateKey, usage kmip.CryptographicUsageMask) ExecRegister

RsaPrivateKey registers an RSA private key. Returns an ExecRegister with the specified RSA private key set. Panics if the key format is unexpected or the key length is invalid.

func (ExecRegisterWantType) RsaPublicKey

func (ex ExecRegisterWantType) RsaPublicKey(key *rsa.PublicKey, usage kmip.CryptographicUsageMask) ExecRegister

RsaPublicKey registers an RSA public key. Returns an ExecRegister with the specified RSA public key set. Panics if the key format is unexpected or the key length is invalid.

func (ExecRegisterWantType) Sec1PrivateKey

func (ex ExecRegisterWantType) Sec1PrivateKey(der []byte, usage kmip.CryptographicUsageMask) ExecRegister

Sec1PrivateKey registers a SEC1 private key. Returns an ExecRegister with the specified SEC1 private key set. If the DER data is invalid, it returns an error.

func (ExecRegisterWantType) Secret

func (ex ExecRegisterWantType) Secret(kind kmip.SecretDataType, value []byte) ExecRegister

Secret registers a secret as a KMIP SecretData object. Returns an ExecRegister with the specified secret set.

func (ExecRegisterWantType) SecretString

func (ex ExecRegisterWantType) SecretString(kind kmip.SecretDataType, value string) ExecRegister

SecretString registers a secret string as a KMIP SecretData object. Returns an ExecRegister with the specified secret string set.

func (ExecRegisterWantType) SymmetricKey

func (ex ExecRegisterWantType) SymmetricKey(alg kmip.CryptographicAlgorithm, usage kmip.CryptographicUsageMask, value []byte) ExecRegister

SymmetricKey registers a symmetric key. Returns an ExecRegister with the specified symmetric key set. Panics if the key format is unexpected or the key length is invalid.

func (ExecRegisterWantType) WithKeyFormat

func (ex ExecRegisterWantType) WithKeyFormat(format KeyFormat) ExecRegisterWantType

WithKeyFormat sets the key format for the register operation. Returns an ExecRegisterWantType with the specified key format.

func (ExecRegisterWantType) X509Certificate

func (ex ExecRegisterWantType) X509Certificate(cert *x509.Certificate) ExecRegister

X509Certificate registers an X.509 certificate. Returns an ExecRegister with the specified X.509 certificate set.

func (ExecRegisterWantType) X509PublicKey

func (ex ExecRegisterWantType) X509PublicKey(der []byte, usage kmip.CryptographicUsageMask) ExecRegister

X509PublicKey registers an X.509 public key. Returns an ExecRegister with the specified X.509 public key set. If the DER data is invalid or the key type is unsupported, it returns an error.

type ExecRekey

ExecRekey is a specialized executor for handling Rekey operations. It embeds the generic AttributeExecutor with request and response payload types specific to the Rekey KMIP operation, facilitating the execution and management of rekey requests and their responses.

Usage:

exec := client.Rekey("object-id").WithOffset(time.Hour)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the rekey operation if the object does not exist, is not in a state that can be rekeyed, or if the server returns an error.

func (ExecRekey) WithOffset

func (ex ExecRekey) WithOffset(offset time.Duration) ExecRekey

WithOffset sets the Offset field for the rekey request, specifying a time duration to offset the rekey operation.

Parameters:

  • offset: The time.Duration to offset the rekey operation.

Returns:

  • ExecRekey: The updated ExecRekey with the offset set.

Errors:

  • No error is returned by this method. If the value is not supported by the server, an error may occur during execution.

func (ExecRekey) WithTemplate deprecated

func (ex ExecRekey) WithTemplate(name string, nameType kmip.NameType) ExecRekey

Deprecated: Templates have been deprecated in KMIP v1.3.

func (ExecRekey) WithTemplates deprecated

func (ex ExecRekey) WithTemplates(names ...kmip.Name) ExecRekey

Deprecated: Templates have been deprecated in KMIP v1.3.

type ExecRekeyKeyPair added in v0.4.0

type ExecRekeyKeyPair struct {
	AttributeExecutor[*payloads.RekeyKeyPairRequestPayload, *payloads.RekeyKeyPairResponsePayload, ExecRekeyKeyPair]
	// contains filtered or unexported fields
}

ExecRekeyKeyPair is a builder for the RekeyKeyPair KMIP operation. It provides methods to set attributes for the common, private key, and public key template attributes when rekeying a key pair. This type embeds AttributeExecutor to allow attribute chaining and supports backward compatibility for template names.

func (ExecRekeyKeyPair) Common added in v0.4.0

func (ex ExecRekeyKeyPair) Common() ExecRekeyKeyPair

Common selects the common template attribute for setting attributes on the RekeyKeyPair request.

func (ExecRekeyKeyPair) PrivateKey added in v0.4.0

func (ex ExecRekeyKeyPair) PrivateKey() ExecRekeyKeyPair

PrivateKey selects the private key template attribute for setting attributes on the RekeyKeyPair request.

func (ExecRekeyKeyPair) PublicKey added in v0.4.0

func (ex ExecRekeyKeyPair) PublicKey() ExecRekeyKeyPair

PublicKey selects the public key template attribute for setting attributes on the RekeyKeyPair request.

func (ExecRekeyKeyPair) WithOffset added in v0.4.0

func (ex ExecRekeyKeyPair) WithOffset(offset time.Duration) ExecRekeyKeyPair

WithOffset sets the Offset field (activation delay) for the RekeyKeyPair request payload. This allows specifying a time.Duration after which the new key pair becomes active.

Parameters:

  • offset: The duration to set as the offset.

Returns:

  • ExecRekeyKeyPair: The updated builder with the offset set.

type ExecRevoke

ExecRevoke is a specialized executor for handling Revoke operations. It embeds the generic Executor with request and response payload types specific to the Revoke KMIP operation, facilitating the execution and management of revoke requests and their responses.

Usage:

exec := client.Revoke("object-id").WithRevocationReasonCode(...).WithRevocationMessage("reason")
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the revoke operation if the object does not exist, is not in a state that can be revoked, or if the server returns an error.

func (ExecRevoke) WithCompromiseOccurrenceDate

func (ex ExecRevoke) WithCompromiseOccurrenceDate(dt time.Time) ExecRevoke

WithCompromiseOccurrenceDate sets the CompromiseOccurrenceDate for the revoke request.

Parameters:

  • dt: The time of compromise occurrence.

Returns:

  • ExecRevoke: The updated ExecRevoke with the compromise occurrence date set.

Errors:

  • No error is returned by this method. If the value is not supported by the server, an error may occur during execution.

func (ExecRevoke) WithRevocationMessage

func (ex ExecRevoke) WithRevocationMessage(msg string) ExecRevoke

WithRevocationMessage sets the RevocationMessage for the revoke request.

Parameters:

  • msg: The revocation message to set.

Returns:

  • ExecRevoke: The updated ExecRevoke with the message set.

Errors:

  • No error is returned by this method. If the message is not supported by the server, an error may occur during execution.

func (ExecRevoke) WithRevocationReasonCode

func (ex ExecRevoke) WithRevocationReasonCode(code kmip.RevocationReasonCode) ExecRevoke

WithRevocationReasonCode sets the RevocationReasonCode for the revoke request.

Parameters:

  • code: The revocation reason code to set.

Returns:

  • ExecRevoke: The updated ExecRevoke with the reason code set.

Errors:

  • No error is returned by this method. If the code is not supported by the server, an error may occur during execution.

type ExecSign added in v0.2.5

ExecSign is a specialized executor for handling Sign operations. It embeds the generic Executor with request and response payload types specific to the Sign KMIP operation, facilitating the execution and management of sign requests and their responses.

Usage:

exec := client.Sign("key-id").WithCryptographicParameters(...).Data(...)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the sign operation if the key is invalid, the server rejects the operation, or the cryptographic parameters are not supported.

type ExecSignWantsData added in v0.2.5

type ExecSignWantsData struct {
	// contains filtered or unexported fields
}

func (ExecSignWantsData) Data added in v0.2.5

func (ex ExecSignWantsData) Data(data []byte) ExecSign

Data sets the data to be signed in the request and returns an ExecSign instance for executing the sign operation with the provided data.

func (ExecSignWantsData) DigestedData added in v0.2.5

func (ex ExecSignWantsData) DigestedData(data []byte) ExecSign

DigestedData sets the digested (hashed) data to be signed in the request payload. It accepts a byte slice containing the digested data and returns an ExecSign instance for further configuration or execution of the signing operation.

func (ExecSignWantsData) WithCryptographicParameters added in v0.2.5

func (ex ExecSignWantsData) WithCryptographicParameters(params kmip.CryptographicParameters) ExecSignWantsData

WithCryptographicParameters sets the CryptographicParameters field of the request to the provided params. It returns the updated ExecSignWantsData to allow for method chaining.

type ExecSignatureVerify added in v0.2.5

ExecSignatureVerify is a specialized executor for handling SignatureVerify operations. It embeds the generic Executor with request and response payload types specific to the SignatureVerify KMIP operation, facilitating the execution and management of signature verification requests and their responses.

Usage:

exec := client.SignatureVerify("key-id").WithCryptographicParameters(...).Data(...).Signature(...)
resp, err := exec.ExecContext(ctx)

Errors:

  • Errors may be returned when executing the signature verify operation if the key is invalid, the server rejects the operation, or the cryptographic parameters are not supported.

type ExecSignatureVerifyWantsData added in v0.2.5

type ExecSignatureVerifyWantsData struct {
	// contains filtered or unexported fields
}

func (ExecSignatureVerifyWantsData) Data added in v0.2.5

Data sets the data to be verified in the request and returns an ExecSignatureVerifyWantsSignature instance for providing the signature and executing the verification operation.

func (ExecSignatureVerifyWantsData) DigestedData added in v0.2.5

DigestedData sets the digested (hashed) data to be verified in the request payload. Returns an ExecSignatureVerifyWantsSignature instance for providing the signature and executing the verification operation.

func (ExecSignatureVerifyWantsData) Signature added in v0.2.5

Signature sets the signature data to be verified in the request and returns an ExecSignatureVerify instance for executing the signature verification operation.

Parameters:

  • sig ([]byte): The signature data to be verified.

Returns:

  • ExecSignatureVerify: An executor configured with the provided signature data.

func (ExecSignatureVerifyWantsData) WithCryptographicParameters added in v0.2.5

func (ex ExecSignatureVerifyWantsData) WithCryptographicParameters(params kmip.CryptographicParameters) ExecSignatureVerifyWantsData

type ExecSignatureVerifyWantsSignature added in v0.2.5

type ExecSignatureVerifyWantsSignature struct {
	// contains filtered or unexported fields
}

func (ExecSignatureVerifyWantsSignature) Signature added in v0.2.5

Signature sets the signature data to be verified in the request payload and returns an ExecSignatureVerify instance for further execution. The provided sig parameter should contain the signature bytes to be verified.

Parameters:

  • sig: The signature data as a byte slice.

Returns:

  • ExecSignatureVerify: An executor configured with the signature data.
  • error: An error if the key attributes are invalid or if required keys are missing.

type Executor

type Executor[Req, Resp kmip.OperationPayload] struct {
	// contains filtered or unexported fields
}

Executor is a generic type that facilitates the construction and execution of KMIP operations. It holds a reference to a Client, a request payload of type Req, and an error state. Req and Resp are type parameters constrained to kmip.OperationPayload, allowing Executor to be used with various KMIP operation request and response types.

func (Executor[Req, Resp]) Build added in v0.4.0

func (ex Executor[Req, Resp]) Build() (kmip.OperationPayload, error)

Build constructs and returns the KMIP operation payload from the Executor. If there was an error during request initialization, it returns a zero-value request and wraps the original error with additional context.

func (Executor[Req, Resp]) Exec

func (ex Executor[Req, Resp]) Exec() (Resp, error)

Exec sends the request to the remote KMIP server, and returns the parsed response.

It returns an error if the request could not be sent, or if the server replies with KMIP error.

func (Executor[Req, Resp]) ExecContext

func (ex Executor[Req, Resp]) ExecContext(ctx context.Context) (Resp, error)

ExecContext sends the request to the remote KMIP server, and returns the parsed response.

It returns an error if the request could not be sent, or if the server replies with KMIP error.

func (Executor[Req, Resp]) MustExec

func (ex Executor[Req, Resp]) MustExec() Resp

MustExec is like Exec except it panics if the request fails.

func (Executor[Req, Resp]) MustExecContext

func (ex Executor[Req, Resp]) MustExecContext(ctx context.Context) Resp

MustExecContext is like Exec except it panics if the request fails.

func (Executor[Req, Resp]) RequestPayload

func (ex Executor[Req, Resp]) RequestPayload() Req

func (Executor[Req, Resp]) Then added in v0.4.0

func (ex Executor[Req, Resp]) Then(f func(client *Client) PayloadBuilder) BatchExec

Then appends a new operation to the current batch by applying the provided PayloadBuilder function to the client. If an error has already occurred in the Executor, it propagates the error to the BatchExec. Otherwise, it builds the new request and adds it to the batch. Returns a BatchExec containing the updated batch and any error encountered during the build process.

type KeyFormat

type KeyFormat uint8

KeyFormat represents the format of a key for registration operations.

const (
	// Transparent key format.
	Transparent KeyFormat = 1 << iota
	// X509 key format.
	X509
	// PKCS8 key format.
	PKCS8
	// PKCS1 key format.
	PKCS1
	// SEC1 key format.
	SEC1
	// RAW key format.
	RAW
)

type Middleware

type Middleware func(next Next, ctx context.Context, msg *kmip.RequestMessage) (*kmip.ResponseMessage, error)

Middleware defines a function type that wraps the processing of a KMIP request message. It takes the next handler in the chain, a context, and the request message as input, and returns a response message or an error. Middlewares can be used to implement cross-cutting concerns such as logging, authentication, or error handling.

func CorrelationValueMiddleware

func CorrelationValueMiddleware(fn func() string) Middleware

CorrelationValueMiddleware returns a Middleware that sets the ClientCorrelationValue in the KMIP request header if it is empty and the protocol version is 1.4 or higher. The provided fn function is used to generate the correlation value. If fn is nil, the middleware will panic. This is useful for ensuring that requests have a unique correlation value for tracking and debugging purposes in compliant KMIP versions.

Parameters:

  • fn: A function that generates a string to be used as the correlation value.

Returns:

  • Middleware: A middleware function that sets the correlation value in the request header.

Errors:

  • Panics if fn is nil.
  • No error is returned by this middleware directly. If the protocol version is below 1.4 or the value is already set, it does nothing.

func DebugMiddleware

func DebugMiddleware(out io.Writer, marshal func(data any) []byte) Middleware

DebugMiddleware returns a Middleware that logs the KMIP request and response messages to the specified io.Writer. The messages are marshaled using the provided marshal function, or ttlv.MarshalXML if marshal is nil. The middleware also logs the duration taken to receive the response. If the writer supports a Flush() method, it is called after logging is complete.

func TimeoutMiddleware added in v0.2.5

func TimeoutMiddleware(timeout time.Duration) Middleware

TimeoutMiddleware returns a Middleware that applies a timeout to the context of each request. If the provided timeout is zero, the middleware passes the context unchanged. Otherwise, it wraps the context with a timeout, ensuring that the request is canceled if it does not complete within the specified duration.

Parameters:

  • timeout: The duration to wait before timing out the request. If zero, no timeout is applied.

Returns:

  • Middleware: A middleware function that enforces the specified timeout on the request context.

Errors:

  • No error is returned by this middleware directly. If the timeout is reached, the request will be canceled and an error will be returned by the handler.

type Next

type Next func(context.Context, *kmip.RequestMessage) (*kmip.ResponseMessage, error)

Next defines a middleware function signature that processes a KMIP RequestMessage within a given context, and returns a corresponding ResponseMessage or an error. It is typically used to chain middleware handlers in the KMIP client request pipeline.

type Option

type Option func(*opts) error

func EnforceVersion

func EnforceVersion(v kmip.ProtocolVersion) Option

EnforceVersion returns an Option that sets the enforced KMIP protocol version for the client. This ensures that all operations performed by the client will use the specified protocol version.

Parameters:

  • v - The KMIP protocol version to enforce.

Returns:

  • Option - A function that applies the enforced protocol version to the client options.
  • error - An error if the connection or protocol negotiation fails.

func WithClientCert

func WithClientCert(cert tls.Certificate) Option

WithClientCert returns an Option that appends the provided TLS client certificate to the client's certificate list. This is used to configure the client for mutual TLS authentication.

- cert: The tls.Certificate to be added to the client's certificate pool.

Returns an Option that can be used to configure the client.

func WithClientCertFiles

func WithClientCertFiles(certFile, keyFile string) Option

WithClientCertFiles returns an Option that loads a client certificate and key from the specified files and appends them to the client's certificate pool. It returns an error if the certificate or key cannot be loaded.

- certFile: path to the PEM-encoded client certificate file. - keyFile: path to the PEM-encoded private key file.

func WithClientCertPEM

func WithClientCertPEM(certPEMBlock, keyPEMBlock []byte) Option

WithClientCertPEM returns an Option that adds a client certificate to the TLS configuration using the provided PEM-encoded certificate and key blocks. The certificate and key must be in PEM format. If the certificate or key is invalid, an error is returned.

func WithDialerUnsafe added in v0.5.0

func WithDialerUnsafe(dialer func(ctx context.Context, addr string) (net.Conn, error)) Option

WithDialerUnsafe customize the low-level network dialer used to establish the (secured) connection.

When this option is provided, every other TLS related options are be ignored, and it's the dialer responsibility to setup the secured channel using TLS or any other security mechanism.

This option is a low-level escape hatch mainly used for testing or to provide alternative secured channel implementation. Use at your own risks.

func WithKmipVersions

func WithKmipVersions(versions ...kmip.ProtocolVersion) Option

WithKmipVersions returns an Option that sets the supported KMIP protocol versions for the client. It appends the provided versions to the existing list, sorts them in descending order, and removes any duplicate versions. This allows the client to negotiate the highest mutually supported protocol version with the KMIP server.

Parameters:

  • versions - One or more kmip.ProtocolVersion values to be supported by the client.

Returns:

  • Option - A function that applies the protocol versions configuration to the client options.
  • error - An error if the connection or protocol negotiation fails.

func WithMiddlewares

func WithMiddlewares(middlewares ...Middleware) Option

WithMiddlewares returns an Option that appends the provided Middleware(s) to the client's middleware chain. This allows customization of the client's behavior by injecting additional processing steps.

Usage:

client.New(WithMiddlewares(mw1, mw2, ...))

func WithRootCAFile

func WithRootCAFile(path string) Option

WithRootCAFile returns an Option that appends the contents of the specified PEM-encoded root CA file to the client's list of root certificate authorities. If the provided path is empty, no action is taken. If reading the file fails, the returned Option will propagate the error.

func WithRootCAPem

func WithRootCAPem(pem []byte) Option

WithRootCAPem returns an Option that appends the provided PEM-encoded root CA certificate to the client's list of trusted root CAs. This can be used to add custom or additional root certificates for TLS connections.

pem: The PEM-encoded root CA certificate as a byte slice.

Example usage:

client, err := NewClient(WithRootCAPem(myRootCA))

func WithServerName

func WithServerName(name string) Option

WithServerName returns an Option that sets the server name to be used by the client. This can be useful for specifying the expected server name in TLS connections.

Parameters:

  • name: the server name to use.

Returns:

  • Option: a function that sets the server name in the client's options.
  • error - An error if the connection or protocol negotiation fails.

func WithTlsCipherSuiteNames added in v0.3.0

func WithTlsCipherSuiteNames(ciphers ...string) Option

WithTlsCipherSuiteNames returns an Option that configures the TLS cipher suites to use, based on the provided list of cipher suite names. Each name is matched against the list of supported and insecure cipher suites. If a name does not match any known cipher suite, an error is returned. This option allows fine-grained control over the TLS cipher suites used by the client for secure connections.

Example usage:

client, err := NewClient(
    WithTlsCipherSuiteNames("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_RSA_WITH_AES_256_GCM_SHA384"),
)

func WithTlsCipherSuites added in v0.3.0

func WithTlsCipherSuites(ciphers ...uint16) Option

WithTlsCipherSuites returns an Option that appends the provided TLS cipher suite IDs to the client's list of supported cipher suites. The cipher suites should be specified as uint16 values, typically using the constants defined in the crypto/tls package. This allows customization of the TLS handshake to restrict or prioritize certain ciphers.

Example usage:

client := NewClient(WithTlsCipherSuites(tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256))

func WithTlsConfig added in v0.1.0

func WithTlsConfig(cfg *tls.Config) Option

WithTlsConfig returns an Option that sets the TLS configuration for the client. It allows fine-grained customization of the underlying TLS settings used for secure communication.

Parameters:

  • cfg: A pointer to a tls.Config struct containing the desired TLS settings.

Returns:

  • Option: A function that applies the provided TLS configuration to the client options.
  • error - An error if the connection or protocol negotiation fails.

type PayloadBuilder added in v0.4.0

type PayloadBuilder interface {
	Build() (kmip.OperationPayload, error)
}

PayloadBuilder defines an interface for building KMIP operation payloads. Implementations of this interface should provide the Build method, which constructs and returns a kmip.OperationPayload along with any error encountered during the building process.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL