dedicated

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

README

KeyProtect CryptoUnit Go SDK - API

This package provides a simplified, secure Go interface to KeyProtect Dedicated CryptoUnits.

Overview

This is the public API for the KeyProtect Dedicated keyprotect-dedicated Go wrapper. The actual implementation is packaged separately as platform-specific prebuilt artifacts while maintaining ease of use.

Current packaging contract: the public module remains source-only, while the build pipeline publishes standardized platform archives containing redistributed prebuilt Go archive artifacts and vendor libraries for future integration.

Installation

The easiest way to use this package is via go get. The shared libraries are automatically included with the module:

# Install the package (includes embedded shared libraries)
go get github.com/IBM/keyprotect-go-client/dedicated

# Use in your project - NO CGO REQUIRED!
# The libraries are automatically found at runtime

Key Benefits:

  • No CGO required - Pure Go builds for consumers
  • Fast builds - Compiles in seconds, not minutes
  • Easy cross-compilation - Standard Go tooling works
  • Automatic library loading - No manual setup needed
How It Works

The module includes precompiled shared libraries for all supported platforms in internal/lib/:

  • linux-amd64/ibmkmscrypto.so.${VERSION}
  • darwin-arm64/ibmkmscrypto.${VERSION}.dylib
  • windows-amd64/ibmkmscrypto.dll

At runtime, the package automatically finds and loads the correct library for your platform using purego.

Advanced: Custom Library Location

If you need to use a custom library version, set the environment variable:

export KEYPROTECT_LIB_PATH=/path/to/custom/libs

Quick Start

Using the Go API
package main

import (
    "os"
    "fmt"
    "log"

    "github.com/IBM/go-sdk-core/v5/core"
    keyprotect_dedicated "github.com/IBM/keyprotect-go-client/dedicated"
)

func main() {
  iamAPIKey, apiKeyFound := os.LookupEnv("IBMCLOUD_API_KEY")

 // Create client configuration
 config := &keyprotect_dedicated.KeyProtectCryptoUnitAPIOptions{
  URL:         "https://<instance_id>.api.st.<region>.kms.appdomain.cloud",
  Authenticator: &core.IamAuthenticator{
   ApiKey: iamAPIKey,
   URL:    "https://iam.cloud.ibm.com",
  },
 }

 // Create new client
 client, disconnect, err := keyprotect_dedicated.NewKeyProtectCryptoUnitAPI(config)
 if err != nil {
  log.Fatalf("Failed to create client: %v", err)
 }
 defer disconnect ()

 // Initialize all cryptounits
 rootKeySpec, err := keyprotect_dedicated.NewSignatureKeyRequest(
  "signature.key",
  "",
  "ADMIN",
  false,
 )
 if err != nil {
  log.Fatalf("error creating signature key request: %s", err)
 }

 mbkSpec, err := keyprotect_dedicated.NewMasterKeyPartsSpec(
  2,
  "IFHLSM",
  []string{
   "mbk-1.key#abcd12",
   "mbk-2.key#abcd12",
  },
  false,
 )
 if err != nil {
  log.Fatalf("error creating NewMasterKeyPartsSpec  request: %s", err)
 }

 err = client.InitializeCryptoUnits(context.Background(), rootKeySpec, mbkSpec, instanceID)
 if err != nil {
  log.Fatalf("Failed to initialize cryptounits: %v", err)
 }

 // Get crypto units
 fmt.Println("Listing crypto units...")
 units, _, err := client.ListCryptoUnits(defaultSettings)
 if err != nil {
  log.Fatalf("Failed to list crypto units: %v", err)
 }

 fmt.Printf("Found %d crypto units:\n", len(units.CryptoUnits))

 for k, v := range units.CryptoUnits {
  fmt.Printf("index %d crypto units %v:\n", k, v)
 }

 // To connect to the first crypto unit and not initialize
 cryptoUnitID := units.CryptoUnits[0].ID

 err = client.CreateCryptoUnitSession(
  Username: "<username>", // username
  KeyFile: "<>", // key file path
  CryptoUnitID: cryptoUnitID, // crypto unit ID
  Port: 443,          // port (0 = default)
 )
 if err != nil {
  log.Fatalf("Failed to connect to crypto unit: %v", err)
 }

API Reference

Methods (on KeyProtectCryptoUnitAPI)
Factory Functions (Constructors)
  • NewSignatureKeyRequest(filepath, passphrase, owner string, exists bool) (*SignatureKeyRequest, error)
  • NewMasterKeyPartsSpec(K int, keyName string, keysharefiles []string, exists bool) (*MasterKeyPartsSpec, error)
  • NewKeyProtectCryptoUnitAPIOptions(url string) (*KeyProtectCryptoUnitAPIOptions, error)
  • NewKeyProtectCryptoUnitAPI(options KeyProtectCryptoUnitAPIOptions) (serviceKeyProtectCryptoUnitAPI, disconnect func(), err error)
  • NewKeyProtectCryptoUnitAPIUsingExternalConfig(options KeyProtectCryptoUnitAPIOptions) (keyProtectCryptoUnitAPIKeyProtectCryptoUnitAPI, disconnect func(), err error)
Configuration & Setup
  • SetDefaultHeaders(headers http.Header) - Sets default HTTP headers
  • GetServiceURL() string - Gets the service URL
  • SetLogger(logger core.Logger) - Sets the logger
  • GetLogger() core.Logger - Gets the logger
Session Management
  • CreateCryptoUnitSession(loginSpec *LoginSpec) error - Creates a session with a crypto unit
  • GetConnectedCryptoUnits() []string - Gets list of connected crypto units
  • Disconnect(cryptoUnitID string) error - Disconnects from a specific crypto unit
  • DisconnectAll() - Disconnects from all crypto units
  • GetSessionInfo(cryptoUnitID string) (*SessionInfo, error) - Gets session information
  • GetAuthState(cryptoUnitID string) (uint32, error) - Gets authentication state
Crypto Unit Operations
  • ListCryptoUnits() (cryptounits CryptoUnits, response *core.DetailedResponse, err error) - Lists crypto units
  • ListCryptoUnitsWithContext(ctx context.Context) (crytounits CryptoUnits, response *core.DetailedResponse, err error) - Lists crypto units with context
  • ClaimCryptoUnit(cryptoUnitID string, filepath string) error - Claims a crypto unit
  • ClaimCryptoUnitWithContext(ctx context.Context, cryptoUnitID string, filePath string) error - Claims crypto unit with context
  • ZeroizeCryptoUnit(cryptoUnitID string) error - Zeroizes a crypto unit
  • ZeroizeCryptoUnitWithContext(ctx context.Context, cryptoUnitID string) error - Zeroizes crypto unit with context
  • InitializeCryptoUnits(ctx context.Context, skr SignatureKeyRequest, mbkspecMasterKeyPartsSpec, instanceID string) error - Initializes crypto units
User Management
  • ListUsers(cryptoUnitID string) ([]UserInfo, error) - Lists users on a crypto unit
  • AddUser(cryptoUnitID string, req *AddUserRequest) error - Adds a user
  • AddUserWithContext(ctx context.Context, cryptoUnitID string, req *AddUserRequest) error - Adds user with context
  • AddKMSUser(ctx context.Context, cryptoUnitID string) ([]UserInfo, error) - Adds a KMS user
  • DeleteUser(cryptoUnitID string, username string) error - Deletes a user
  • DeleteUserWithContext(ctx context.Context, cryptoUnitID string, username string) error - Deletes user with context
  • Key Management
  • GenerateSignatureKey(instanceID string, req *SignatureKeyRequest) error - Generates a signature key
  • ListMasterKeys(cryptoUnitID string) ([]MasterKeyInfo, error) - Lists master keys
  • ListMasterKeysWithContext(ctx context.Context, cryptoUnitID string) ([]MasterKeyInfo, error) - Lists master keys with context
  • GenerateMasterKey(cryptoUnitID string, mbkSpec *MasterKeyPartsSpec) (string, error) - Generates a master key
  • GenerateMasterKeyWithContext(ctx context.Context, cryptoUnitID string, mbkSpec *MasterKeyPartsSpec) (string, error) - Generates master key with context
  • ImportMasterKey(cryptoUnitID string, mbkSpec *MasterKeyPartsSpec) error - Imports a master key
  • ImportMasterKeyWithContext(ctx context.Context, cryptoUnitID string, request *MasterKeyPartsSpec) error - Imports master key with context
  • ImportMasterKeyToCryptoUnits(ctx context.Context, cryptoUnitIDs []string, request *MasterKeyPartsSpec) error - Imports master key to multiple crypto units
Audit
  • GetAuditLog(cryptoUnitID string) (*AuditLog, error) - Gets audit log

Platform Support

  • Linux (amd64)
  • macOS (Apple Silicon)
  • Windows (amd64)

Requirements

For Consumers (Using the Package)
  • Go 1.21 or later
  • No CGO required - CGO_ENABLED=0 works fine!
  • No C compiler needed - Pure Go builds
For Maintainers (Building the Package)
  • Go 1.21 or later
  • CGO enabled (CGO_ENABLED=1)
  • GCC or compatible C compiler
  • Platform-specific toolchains for cross-compilation
Runtime Dependencies
  • Shared libraries are self-contained (OpenSSL 1.1 statically linked)
  • No external dependencies required

Support

For support, please contact:

License

This software is provided under the IBM license agreement. Refer to the LICENSE file for terms and conditions.

v1.0.0 (2026-04-10)
  • Initial release
  • Support for initializing KeyProtect Dedicated CryptoUnits
  • Pre-compiled binaries for all major platforms

Documentation

Index

Constants

View Source
const (
	SigKeyPassphraseMinLength = 4
	SigKeyPassphraseMaxLength = 255
	SigKeyFilePathMinLength   = 1
	SigKeyFilePathMaxLength   = 255
	SigKeyAlgorithmRSA2048    = "RSA-2048"
)

Signature key validation constants

View Source
const (
	RetFormatHR   = 0x00000001 // Human readable response
	RetFormatHex  = 0x00000002 // HEX Encoded HR response
	RetFormatBin  = 0x00000004 // Byte array (raw response from device)
	RetFormatXML  = 0x00000010 // XML formatted response
	RetFormatJSON = 0x00000020 // JSON formatted response
	RetFormatAlt  = 0x00000040 // Alternate format (command-specific)
)

ReturnFormat flags for response formatting

View Source
const (
	KeyTypeRSA   = 1
	KeyTypeECDSA = 2
)

KeyType constants

View Source
const (
	HSMFsAll   = 0
	HSMFsNVRAM = 1
	HSMFsFlash = 2
)

HSM Filesystem constants

View Source
const DefaultServiceName = "keyprotect-cryptounit-go-sdk"

DefaultServiceName is the default key used to find external configuration information.

View Source
const DefaultServicePort = 443
View Source
const DefaultServiceURL = "https://api.us-south.kms.appdomain.cloud"

DefaultServiceURL is the default URL to make service requests to.

Variables

View Source
var AlternativeServiceURLEnvVars = []string{
	"IBMCLOUD_KP_CRYPTOUNIT_ENDPOINT",
	"KP_TARGET_ADDR",
}

Functions

func GetServiceURLForRegion

func GetServiceURLForRegion(instanceID, region string, private bool) (string, error)

GetServiceURLForRegion returns the service URL to be used for the specified region

func IsAuthError

func IsAuthError(err error) bool

IsAuthError checks if the error is an authentication error

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError checks if the error is a connection error

func IsSessionError

func IsSessionError(err error) bool

IsSessionError checks if the error is a session error

func IsUserError

func IsUserError(err error) bool

IsUserError checks if the error is a user management error

func TranslateErrorCode

func TranslateErrorCode(code uint32) string

TranslateErrorCode converts a numeric error code to a human-readable message This is useful for debugging and logging when you have a raw error code

Types

type AddUserRequest

type AddUserRequest struct {
	Username   string
	Permission uint32
	Mechanism  string // "hmacpwd", "rsasign", or "ecdsa"
	CredHash   string //
	Attributes string // Optional attributes
	Token      string // Authentication token
}

AddUserRequest contains parameters for adding a new user

type AuditEntry

type AuditEntry struct {
	Timestamp string
	User      string
	Action    string
	Result    string
	Details   string
}

AuditEntry represents a single audit log entry

type AuditLog

type AuditLog struct {
	Entries []AuditEntry
	Raw     string
}

AuditLog represents the HSM audit log

type CryptoUnit

type CryptoUnit struct {
	ID         string          `json:"id"`
	InstanceID string          `json:"instanceId"`
	State      CryptoUnitState `json:"state"`
}

type CryptoUnitAPIError

type CryptoUnitAPIError struct {
	Code    uint32
	Message string
}

CryptoUnitAPIError represents an error from the API

func NewError

func NewError(code uint32, message string) *CryptoUnitAPIError

NewError creates a new APIError

func (*CryptoUnitAPIError) Error

func (e *CryptoUnitAPIError) Error() string

Error implements the error interface

type CryptoUnitClaimBody

type CryptoUnitClaimBody struct {
	PublicKey string `json:"certificate"`
}

CryptoUnitClaimBody contains the public key for claiming a crypto unit (internal use)

type CryptoUnitClaimRequest

type CryptoUnitClaimRequest struct {
	// SignatureKeyPath is the path to the signature key file generated by GenerateSignatureKey
	// The file should contain MOD and PEXP values in hexadecimal format
	SignatureKeyPath string

	// CryptoUnitIDs is an optional list of specific crypto unit IDs to claim
	// If nil or empty, all crypto units in the instance will be claimed
	CryptoUnitIDs []string
}

CryptoUnitClaimRequest contains parameters for claiming a crypto unit

type CryptoUnitState

type CryptoUnitState string

CryptoUnitState represents the state of a crypto unit

const (
	CryptoUnitStateAvailable      CryptoUnitState = "available"
	CryptoUnitStateReserved       CryptoUnitState = "reserved"
	CryptoUnitStateClaimed        CryptoUnitState = "claimed"
	CryptoUnitStateKMSAuthorized  CryptoUnitState = "kms-authorized"
	CryptoUnitStateInitialized    CryptoUnitState = "initialized"
	CryptoUnitStateKMSInitialized CryptoUnitState = "kms-initialized"
	CryptoUnitStateMarkedForDel   CryptoUnitState = "marked-for-del"
	CryptoUnitStateZeroized       CryptoUnitState = "zeroized"
	CryptoUnitStateMaintenance    CryptoUnitState = "maintenance"
)

CryptoUnit state constants

type CryptoUnits

type CryptoUnits struct {
	CryptoUnits []CryptoUnit `json:"crypto_units,omitempty"`
}

func (*CryptoUnits) IDs

func (cus *CryptoUnits) IDs() []string

type CryptoUserMetadata

type CryptoUserMetadata struct {
	Username  string `json:"user_name"`
	PublicKey string `json:"public_key"`
	SlotID    int    `json:"slot_id"`
}

CryptoUserMetadata represents metadata for a KMS crypto user

type GenerateKeyRequest

type GenerateKeyRequest struct {
	KeySpec     string // Key specification (file path or smart card identifier)
	KeySizeBits uint32 // Key size in bits (e.g., 2048, 3072, 4096)
	Owner       string // Key owner identifier
}

GenerateKeyRequest contains parameters for key generation

type ImportMasterKeyResult

type ImportMasterKeyResult struct {
	CryptoUnitID string
	Error        error
}

ImportMasterKeyResult represents the result of importing an MBK to a crypto unit

type InitStep added in v0.17.2

type InitStep int

InitStep identifies each resumable stage of the initialization pipeline. The values are intentionally monotonically increasing so that a simple integer comparison determines whether a stage needs to run.

const (
	StepListUnits      InitStep = 1 // ListCryptoUnitsWithContext → determines per-unit resume point
	StepGenerateSKR    InitStep = 2 // generate the admin signature key (local)
	StepClaimUnits     InitStep = 3 // ClaimCryptoUnitWithContext → state: claimed
	StepCreateSessions InitStep = 4 // createSessions (HSM login)
	StepAddKMSUser     InitStep = 5 // AddKMSUser → state: kms-authorized
	StepGenerateMBK    InitStep = 6 // GenerateMasterKeyWithContext (local-to-one-unit)
	StepImportMBK      InitStep = 7 // ImportMasterKeyToCryptoUnits → state: initialized
)

type KeyProtectCryptoUnitAPI

type KeyProtectCryptoUnitAPI struct {
	Service *core.BaseService
	// contains filtered or unexported fields
}

func NewKeyProtectCryptoUnitAPI

func NewKeyProtectCryptoUnitAPI(options *KeyProtectCryptoUnitAPIOptions) (service *KeyProtectCryptoUnitAPI, disconnect func(), err error)

NewKeyProtectCryptoUnitAPI creates a KeyProtectCryptoUnitAPI instance. Always call disconnect() when done.

func NewKeyProtectCryptoUnitAPIUsingExternalConfig

func NewKeyProtectCryptoUnitAPIUsingExternalConfig(options *KeyProtectCryptoUnitAPIOptions) (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI, disconnect func(), err error)

func (*KeyProtectCryptoUnitAPI) AddKMSUser

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) AddKMSUser(ctx context.Context, cryptoUnitID string) ([]UserInfo, error)

AddKMSUser retrieves crypto user metadata from the Key Protect API and adds the user to the specified crypto unit. This replicates the behavior of the CLI command: user add --type kmsCryptoUser

The function: 1. Fetches crypto user metadata (username, public key, slot ID) from the Key Protect management API 2. Converts the PEM-formatted RSA public key to HSM format (MOD/PEXP) 3. Creates a temporary file with the converted key 4. Adds the user to the HSM with basic permissions and slot-specific attributes 5. Returns the updated list of users

func (*KeyProtectCryptoUnitAPI) AddUser

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) AddUser(cryptoUnitID string, req *AddUserRequest) error

AddUser adds a new user to a specific crypto unit

func (*KeyProtectCryptoUnitAPI) AddUserWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) AddUserWithContext(ctx context.Context, cryptoUnitID string, req *AddUserRequest) error

AddUserWithContext adds a new user to a specific crypto unit with context

func (*KeyProtectCryptoUnitAPI) ClaimCryptoUnit

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ClaimCryptoUnit(cryptoUnitID string, filepath string) error

ClaimCryptoUnit claims a specific cryptounit using a signature key file The signatureKeyPath should point to a file generated by GenerateSignatureKey

func (*KeyProtectCryptoUnitAPI) ClaimCryptoUnitWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ClaimCryptoUnitWithContext(ctx context.Context, cryptoUnitID string, filePath string) error

ClaimCryptoUnitWithContext claims a specific cryptounit with context

func (*KeyProtectCryptoUnitAPI) CreateCryptoUnitSession

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) CreateCryptoUnitSession(loginSpec *LoginSpec) error

CreateCryptoUnitSession establishes a connection to a specific crypto unit and creates a session. Multiple crypto units can be connected simultaneously. Each connection is tracked by cryptoUnitID.

func (*KeyProtectCryptoUnitAPI) DeleteUser

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) DeleteUser(cryptoUnitID string, username string) error

DeleteUser removes a user from a specific crypto unit

func (*KeyProtectCryptoUnitAPI) DeleteUserWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) DeleteUserWithContext(ctx context.Context, cryptoUnitID string, username string) error

DeleteUserWithContext removes a user from a specific crypto unit with context

func (*KeyProtectCryptoUnitAPI) Disconnect

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) Disconnect(cryptoUnitID string) error

Disconnect closes the connection to a specific crypto unit.

func (*KeyProtectCryptoUnitAPI) DisconnectAll

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) DisconnectAll()

Disconnect closes the connection to a specific crypto unit.

func (*KeyProtectCryptoUnitAPI) GenerateMasterKey

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GenerateMasterKey(cryptoUnitID string, mbkSpec *MasterKeyPartsSpec) (string, error)

GenerateMasterKey generates a Master Backup Key for a specific crypto unit

func (*KeyProtectCryptoUnitAPI) GenerateMasterKeyWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GenerateMasterKeyWithContext(ctx context.Context, cryptoUnitID string, mbkSpec *MasterKeyPartsSpec) (string, error)

GenerateMasterKeyWithContext generates a Master Backup Key for a specific crypto unit This function creates a new Master Key with the specified parameters including threshold (N/K) scheme

func (*KeyProtectCryptoUnitAPI) GenerateSignatureKey

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GenerateSignatureKey(instanceID string, req *SignatureKeyRequest) error

GenerateSignatureKey generates an RSA signature key and saves it to a file.

IMPORTANT: This is a LOCAL operation that does NOT require a connected session. The key is generated locally by the library and saved to the specified file path. This operation does not communicate with the HSM server.

Parameters:

  • instanceID: The ID of the Key Protect instance (not the crypto unit ID)
  • req: Request containing file path, optional passphrase, and algorithm

Returns:

  • error: nil on success, error describing the failure otherwise

Example:

// Generate signature key (no connection required)
req := &GenerateSignatureKeyRequest{
    FilePath:   "signature.key",
    Passphrase: "",
    Algorithm:  SigKeyAlgorithmRSA2048,
    Owner:      "admin",
}
err = client.GenerateSignatureKey(instanceID, req)

func (*KeyProtectCryptoUnitAPI) GetAuditLog

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GetAuditLog(cryptoUnitID string) (*AuditLog, error)

GetAuditLog retrieves the audit log for a specific crypto unit

func (*KeyProtectCryptoUnitAPI) GetAuthState

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GetAuthState(cryptoUnitID string) (uint32, error)

GetAuthState retrieves the authentication state for a specific crypto unit

func (*KeyProtectCryptoUnitAPI) GetConnectedCryptoUnits

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GetConnectedCryptoUnits() []string

GetConnectedCryptoUnits returns a list of crypto unit IDs that are currently connected.

func (*KeyProtectCryptoUnitAPI) GetLogger

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GetLogger() core.Logger

GetLogger returns the current logger

func (*KeyProtectCryptoUnitAPI) GetServiceURL

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GetServiceURL() string

GetServiceURL returns the service URL

func (*KeyProtectCryptoUnitAPI) GetSessionInfo

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) GetSessionInfo(cryptoUnitID string) (*SessionInfo, error)

GetSessionInfo retrieves the current state of the HSM Session for a specific cryptounit

func (*KeyProtectCryptoUnitAPI) ImportMasterKey

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ImportMasterKey(cryptoUnitID string, mbkSpec *MasterKeyPartsSpec) error

ImportMasterKey is a convenience wrapper around ImportMasterKeyWithContext)

func (*KeyProtectCryptoUnitAPI) ImportMasterKeyToCryptoUnits

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ImportMasterKeyToCryptoUnits(ctx context.Context, cryptoUnitIDs []string, request *MasterKeyPartsSpec) error

ImportMasterKeyToCryptoUnits imports an Master Key to multiple crypto units concurrently using goroutines and returns the results for each crypto unit. This function is useful when you need to import the same MasterKeyPartsSpec configuration to multiple crypto units in parallel.

Parameters:

  • cryptoUnitIDs: List of crypto unit IDs to import the Master Key to
  • request: The ImportMaster KeyRequest containing the Master Key configuration

Returns:

  • []ImportMaster KeyResult: A slice containing the result for each crypto unit, including any errors

Example:

cryptoUnitIDs := []string{"cu-1", "cu-2", "cu-3"}
request := &ImportMaster KeyRequest{
    KeyShareFiles: []string{"key1.key#pass1", "key2.key#pass2"},
    SlotNo: 3,
}
results := client.ImportMasterKeyToCryptoUnits(cryptoUnitIDs, request)
for _, result := range results {
    if result.Error != nil {
        fmt.Printf("Failed to import Master Key to %s: %v\n", result.CryptoUnitID, result.Error)
    } else {
        fmt.Printf("Successfully imported Master Key to %s: %s\n", result.CryptoUnitID, result.Result)
    }
}

func (*KeyProtectCryptoUnitAPI) ImportMasterKeyWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ImportMasterKeyWithContext(ctx context.Context, cryptoUnitID string, request *MasterKeyPartsSpec) error

ImportMasterKeyWithContext is the context-aware version of ImportMaster Key It allows for better control over timeouts and cancellation Parameters:

  • ctx: Context for controlling timeouts and cancellation
  • cryptoUnitID: The ID of the crypto unit to import the Master Key to
  • request: ImportMaster KeyRequest containing the key specifications and slot number

Returns:

  • string: Response data from the import operation
  • error: Any error that occurred during the import

Example:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
result, err := client.ImportMasterKeyWithContext(ctx, cryptoUnitID, importRequest)

func (*KeyProtectCryptoUnitAPI) InitializeCryptoUnits

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) InitializeCryptoUnits(ctx context.Context, skr *SignatureKeyRequest, mbkspec *MasterKeyPartsSpec, instanceID string) error

InitializeCryptoUnits provisions every crypto unit belonging to instanceID through the full 7-step initialization pipeline.

Each step is guarded by the live CryptoUnitState returned from ListCryptoUnitsWithContext, so the function is safe to call after a partial failure: it will resume from wherever each individual unit was left off, and it will bring lagging units up to the same state as the most-advanced units (catch-up).

Step ordering and the states they produce:

  1. ListCryptoUnitsWithContext → determines per-unit resume point
  2. GenerateSignatureKey → local file (skipped when skr.Exists)
  3. ClaimCryptoUnitWithContext → state: claimed
  4. createSessions (HSM login)
  5. AddKMSUser → state: kms-authorized
  6. GenerateMasterKeyWithContext → local file (skipped when mbkspec.Exists)
  7. ImportMasterKeyToCryptoUnits → state: initialized / kms-initialized

func (*KeyProtectCryptoUnitAPI) ListCryptoUnits

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ListCryptoUnits() (cryptounits CryptoUnits, response *core.DetailedResponse, err error)

func (*KeyProtectCryptoUnitAPI) ListCryptoUnitsWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ListCryptoUnitsWithContext(ctx context.Context) (crytounits CryptoUnits, response *core.DetailedResponse, err error)

ListCryptoUnitsWithContext Retrieve the cryptounits available to the instance

func (*KeyProtectCryptoUnitAPI) ListMasterKeys

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ListMasterKeys(cryptoUnitID string) ([]MasterKeyInfo, error)

ListMasterKeys lists the Master Backup Keys for a specific crypto unit

func (*KeyProtectCryptoUnitAPI) ListMasterKeysWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ListMasterKeysWithContext(ctx context.Context, cryptoUnitID string) ([]MasterKeyInfo, error)

ListMasterKeysWithContext lists the Master Backup Keys for a specific crypto unit

func (*KeyProtectCryptoUnitAPI) ListUsers

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ListUsers(cryptoUnitID string) ([]UserInfo, error)

ListUsers retrieves the list of users for a specific crypto unit

func (*KeyProtectCryptoUnitAPI) SetDefaultHeaders

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) SetDefaultHeaders(headers http.Header)

SetDefaultHeaders sets HTTP headers to be sent in every request

func (*KeyProtectCryptoUnitAPI) SetLogger

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) SetLogger(logger core.Logger)

SetLogger allows clients to set a custom logger

func (*KeyProtectCryptoUnitAPI) ZeroizeCryptoUnit

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ZeroizeCryptoUnit(cryptoUnitID string) error

ZeroizeCryptoUnit will erase all data for a specific crypto unit

func (*KeyProtectCryptoUnitAPI) ZeroizeCryptoUnitWithContext

func (keyProtectCryptoUnitAPI *KeyProtectCryptoUnitAPI) ZeroizeCryptoUnitWithContext(ctx context.Context, cryptoUnitID string) error

type KeyProtectCryptoUnitAPIOptions

type KeyProtectCryptoUnitAPIOptions struct {
	// Name to call the client
	ServiceName string
	// URL is the full URL of Key Protect instance
	URL string
	// Region of the KMS instance
	Region string
	// ID of the service instance
	InstanceID string
	// Type of endpoint to communicate with the instance
	UsePrivate bool

	Authenticator core.Authenticator
}

func NewKeyProtectCryptoUnitAPIOptions

func NewKeyProtectCryptoUnitAPIOptions(url string) (*KeyProtectCryptoUnitAPIOptions, error)

type LoginSpec

type LoginSpec struct {
	// KeyFile is a key file specification with a passphrase, separated with a '#'
	// Format: "filepath_0.key#passphrase"
	KeyFile string `json:"-"`

	// The unique id given for a cryptounit
	CryptoUnitID string `json:"cryptounit_id"`

	// The port to connect to a cryptounit
	Port int `json:"port"`

	// The username to identify as
	Username string `json:"username"`
}

LoginSpec represents the login specification for a cryptounit

type MasterKeyInfo

type MasterKeyInfo struct {
	Slot           string // Slot number where the MBK is stored
	Name           string // Name of the MBK
	Len            string // Length of the key in bytes
	Algo           string // Algorithm (e.g., "AES")
	Type           string // Type (e.g., "SHARE")
	K              string // Threshold parameter (minimum shares needed)
	GenerationDate string // Date when the key was generated
	KeyCheckValue  string // Key check value for verification
}

MasterKeyInfo represents information about a Master Backup Key

type MasterKeyPartsSpec

type MasterKeyPartsSpec struct {
	// K is the threshold parameter (minimum number of key parts required)
	K uint8

	// KeyName is the name/identifier for the generated MBK
	KeyName string

	// KeyShareFiles is a slice of MBK key part file specifications with passphrases
	// Format: []string{"filepath_0.key#passphrase", "filepath_1.key#passphrase"}
	// This will be converted to comma-separated string
	KeyShareFiles []string

	// SlotNo is the slot number where the MBK will be imported (0-based)
	SlotNo int

	// Exists determines if the master key parts files in KeyShareFiles are existing files.
	Exists bool
}

MasterKeyPartsSpec represents a key specification for generating a Master Key as parts

func NewMasterKeyPartsSpec

func NewMasterKeyPartsSpec(k int, keyName string, keysharefiles []string, exists bool) (*MasterKeyPartsSpec, error)

NewMasterKeyPartsSpec creates a NewMasterKeyPartsSpec for the client

k is the threshold parameter (minimum number of key parts required)

keyName is the name/identifier for the generated MBK

keyShareFiles is a slice of MBK key part file specifications with passphrases Format: []string{"filepath_0.key#passphrase", "filepath_1.key#passphrase"}

shouldGen is a bool to determine to use the existing files specified in the keysharefiles field

type MasterKeyRequest

type MasterKeyRequest struct {
	// KeySpec specifies the key specification (e.g., file path or identifier)
	KeySpec string

	// KeyType specifies the type of key (e.g., "RSA", "AES")
	KeyType string

	// KeyLength specifies the key length in bits
	KeyLength int

	// N is the threshold parameter (minimum number of key parts required)
	N uint8

	// K is the total number of key parts to generate
	K uint8

	// KeyName is the name/identifier for the generated MBK
	KeyName string
}

MasterKeyRequest contains parameters for generating a Master Backup Key

type SessionInfo

type SessionInfo struct {
	CryptoUnitID string
	UserName     string
	AuthState    uint32
}

StateInfo represents the current state of the HSM

func (*SessionInfo) String

func (s *SessionInfo) String() string

type SessionPool

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

SessionPool holds all the cryptounits sessions created

func (*SessionPool) GetConnectedCryptoUnits

func (p *SessionPool) GetConnectedCryptoUnits() []string

GetConnectedCryptoUnits will return a list of all connected crypto units

type SignatureKeyRequest

type SignatureKeyRequest struct {
	// FilePath is the path where the signature key file will be saved
	// Must be 1-255 characters and point to an existing directory
	FilePath string

	// Passphrase is optional encryption for the key file
	// If provided, must be 4-255 characters
	// Empty string means no passphrase
	Passphrase string

	// Algorithm specifies the key algorithm
	// Currently only "RSA-2048" is supported
	Algorithm string

	// Owner is the optional key owner identifier passed to the underlying key generation call
	Owner string

	// Exists dictates if the signature key is an existing file from the FilePath
	Exists bool
}

SignatureKeyRequest contains parameters for signature key generation

func NewSignatureKeyRequest

func NewSignatureKeyRequest(filepath, passphrase, owner string, exists bool) (*SignatureKeyRequest, error)

type UserAttributes

type UserAttributes struct {
	// A[] - Application-depending attributes (e.g., CXI_GROUP=SLOT_0007)
	ApplicationAttrs map[string]string

	// H[] - Non-default hash algorithms (e.g., SHA-256)
	HashAlgorithm string

	// Z[] - Counter for consecutively failed authentication attempts
	FailedAuthCount int

	// L[] - PKCS#11 slot label
	SlotLabel string

	// I[] - User authentication state (0=can perform commands, 1=must change password)
	AuthState int

	// Raw - Original unparsed attribute string
	Raw string
}

UserAttributes represents parsed HSM user attributes

type UserInfo

type UserInfo struct {
	Username    string
	Permissions uint32
	Mechanism   string
	Attributes  UserAttributes
}

UserInfo represents information about an HSM user

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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