kp

package module
Version: v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2021 License: Apache-2.0 Imports: 27 Imported by: 5

README

keyprotect-go-client

Build Status GoDoc

keyprotect-go-client is a Go client library for interacting with the IBM KeyProtect service.

Questions / Support

There are many channels for asking questions about KeyProtect and this client.

  • Ask a question on Stackoverflow and tag it with key-protect and ibm-cloud
  • Open a Github Issue
  • If you work at IBM and have access to the internal Slack, you can join the #key-protect channel and ask there.

Usage

This client expects that you have an existing IBM Cloud Key Protect Service Instance. To get started, visit the IBM KeyProtect Catalog Page.

Build a client with ClientConfig and New, then use the client to do some operations.

import "github.com/IBM/keyprotect-go-client"

// Use your IAM API Key and your KeyProtect Service Instance GUID/UUID to create a ClientConfig
cc := kp.ClientConfig{
	BaseURL:       kp.DefaultBaseURL,
	APIKey:        "......",
	InstanceID:    "1234abcd-906d-438a-8a68-deadbeef1a2b3",
}

// Build a new client from the config
client := kp.New(cc, kp.DefaultTransport())

// List keys in your KeyProtect instance
keys, err := client.GetKeys(context.Background(), 0, 0)
Migrating

For users of the original key-protect-client that is now deprecated, this library is a drop in replacement. Updating the package reference to github.com/IBM/keyprotect-go-client should be the only change needed. If you are worried about new incompatible changes, version v0.3.1 of key-protect-client is equivalent to version v0.3.3 of keyprotect-go-client, so pinning v0.3.3 of the new library should be sufficient to pull from the new repo with no new functional changes.

Authentication

The KeyProtect client requires a valid IAM API Key that is passed via the APIKey field in the ClientConfig. The client will call IAM to get an access token for that API key, caches the access token, and reuses that token on subsequent calls. If the access token is expired, the client will call IAM to get a new access token.

Alternatively, you may also inject your own tokens during runtime. When using your own tokens, it's the responsibilty of the caller to ensure the access token is valid and is not expired. You can specify the access token in either the ClientConfig structure or on the context (see below.)

To specify authorization token on the context:

// Create a ClientConfig and Client like before, but without an APIKey
cc := kp.ClientConfig{
	BaseURL:       kp.DefaultBaseURL,
	InstanceID:    "1234abcd-906d-438a-8a68-deadbeef1a2b3",
}
client := kp.New(cc, kp.DefaultTransport())

// Use NewContextWithAuth to add your token into the context
ctx := context.Background()
ctx = kp.NewContextWithAuth(ctx, "Bearer ABCDEF123456....")

// List keys with our injected token via the context
keys, err := api.GetKeys(ctx, 0, 0)

For information on IAM API Keys and tokens please refer to the IAM docs

Finding a KeyProtect Service Instance's UUID

The client requires a valid UUID that identifies your KeyProtect Service Instance to be able to interact with your key data in the instance. An instance is somewhat like a folder or directory of keys; you can have many of them per account, but the keys they contain are separate and cannot be shared between instances.

The IBM Cloud CLI can be used to find the UUID for your KeyProtect instance.

$ ic resource service-instances
OK
Name                                                              Location   State    Type
Key Protect-private                                               us-south   active   service_instance
Key Protect-abc123                                                us-east    active   service_instance

Find the name of your KeyProtect instance as you created it, and the use the client to get its details. The Instance ID is the GUID field, or if you do not see GUID, it will be the last part of the CRN. For example:

$ ic resource service-instance "Key Protect-private"
OK

Name:                  Key Protect-private
ID:                    crn:v1:bluemix:public:kms:us-south:a/.......:1234abcd-906d-438a-8a68-deadbeef1a2b3::
GUID:                  1234abcd-906d-438a-8a68-deadbeef1a2b3

Examples

Generating a root key (CRK)
// Create a root key named MyRootKey with no expiration
key, err := client.CreateRootKey(ctx, "MyRootKey", nil)
if err != nil {
    fmt.Println(err)
}
fmt.Println(key.ID, key.Name)

crkID := key.ID
Wrapping and Unwrapping a DEK using a specific Root Key.
myDEK := []byte{"thisisadataencryptionkey"}
// Do some encryption with myDEK
// Wrap the DEK so we can safely store it
wrappedDEK, err := client.Wrap(ctx, crkID, myDEK, nil)


// Unwrap the DEK
dek, err := client.Unwrap(ctx, crkID, wrappedDEK, nil)
// Do some encryption/decryption using the DEK
// Discard the DEK
dek = nil

Note you can also pass additional authentication data (AAD) to wrap and unwrap calls to provide another level of protection for your DEK. The AAD is a string array with each element up to 255 chars. For example:

myAAD := []string{"First aad string", "second aad string", "third aad string"}
myDEK := []byte{"thisisadataencryptionkey"}
// Do some encryption with myDEK
// Wrap the DEK so we can safely store it
wrappedDEK, err := client.Wrap(ctx, crkID, myDEK, &myAAD)


// Unwrap the DEK
dek, err := client.Unwrap(ctx, crkID, wrappedDEK, &myAAD)
// Do some encryption/decryption using the DEK
// Discard the DEK
dek = nil

Have key protect create a DEK for you:

dek, wrappedDek, err := client.WrapCreateDEK(ctx, crkID, nil)
// Do some encrypt/decrypt with the dek
// Discard the DEK
dek = nil

// Save the wrapped DEK for later.  Use Unwrap to use it.

Can also specify AAD:

myAAD := []string{"First aad string", "second aad string", "third aad string"}
dek, wrappedDek, err := client.WrapCreateDEK(ctx, crkID, &myAAD)
// Do some encrypt/decrypt with the dek
// Discard the DEK
dek = nil

// Save the wrapped DEK for later.  Call Unwrap to use it, make
// sure to specify the same AAD.

Documentation

Overview

keyprotect-go-client is a Go client library for interacting with the IBM KeyProtect service.

Example
package main

import (
	"context"
	"fmt"
	"os"

	kp "github.com/IBM/keyprotect-go-client"
)

func NewClient() (*kp.Client, error) {
	instanceId, ok := os.LookupEnv("KP_INSTANCE_ID")
	if !ok {
		panic("Must set KP_INSTANCE_ID")
	}

	apiKey, ok := os.LookupEnv("IBMCLOUD_API_KEY")
	if !ok {
		panic("Must set IBMCLOUD_API_KEY")
	}
	if apiKey == "" {
		panic("IBMCLOUD_API_KEY was empty")
	}

	cc := kp.ClientConfig{
		BaseURL:    "https://us-south.kms.cloud.ibm.com",
		APIKey:     apiKey,
		InstanceID: instanceId,
	}

	return kp.New(cc, kp.DefaultTransport())
}

func main() {
	c, _ := NewClient()

	ctx := context.Background()

	// List keys in the current instance
	keys, err := c.GetKeys(ctx, 0, 0)
	if err != nil {
		panic(err)
	}
	for _, key := range keys.Keys {
		fmt.Printf("%+v\n", key)
	}

	// Create a new non-exportable key
	crk, err := c.CreateKey(ctx, "kp-go-example-crk", nil, false)
	if err != nil {
		panic(err)
	}
	fmt.Printf("CRK created successfully: id=%s\n", crk.ID)

	// Create a new DEK and WDEK pair, using the root key from above.
	// The DEK is a piece of secret information that is used for encrypt/decrypt.
	// The WDEK (or wrapped DEK) is used to retrieve the DEK when you need it again.
	ptDek, wdek, err := c.WrapCreateDEK(ctx, crk.ID, nil)
	if err != nil {
		panic(err)
	}

	// Unwrap our WDEK, getting back the corresponding DEK
	unwrapped, _, err := c.UnwrapV2(ctx, crk.ID, wdek, nil)

	if string(unwrapped) != string(ptDek) {
		panic("Unwrapped DEK did not match DEK from Wrap!")
	}

	// Delete the root key in KeyProtect.
	// Any WDEKs created with the root key will no longer be able to be unwrapped.
	// If you didn't store your DEKs elsewhere, all the data encrypted by those DEKs
	// is now crypto-erased.
	//
	// For some this is a feature. For others it might be a nightmare.
	// Make very sure that the key should be deleted.
	_, err = c.DeleteKey(ctx, crk.ID, 0)
	if err != nil {
		panic(fmt.Sprintf("Error deleting key: %s\n", err))
	}
	fmt.Printf("Key deleted: id=%s\n", crk.ID)
}
Output:

Index

Examples

Constants

View Source
const (
	// DualAuthDelete defines the policy type as dual auth delete
	DualAuthDelete = "dualAuthDelete"

	// AllowedNetwork defines the policy type as allowed network
	AllowedNetwork = "allowedNetwork"

	// AllowedIP defines the policy type as allowed ip that are whitelisted
	AllowedIP = "allowedIP"

	// Metrics defines the policy type as metrics
	Metrics = "metrics"
	// KeyAccess defines the policy type as key create import access
	KeyCreateImportAccess = "keyCreateImportAccess"

	// KeyAccess policy attributes
	CreateRootKey     = "CreateRootKey"
	CreateStandardKey = "CreateStandardKey"
	ImportRootKey     = "ImportRootKey"
	ImportStandardKey = "ImportStandardKey"
	EnforceToken      = "EnforceToken"
)
View Source
const (
	// DefaultBaseURL ...
	DefaultBaseURL = "https://us-south.kms.cloud.ibm.com"
	// DefaultTokenURL ..
	DefaultTokenURL = iam.IAMTokenURL

	// VerboseNone ...
	VerboseNone = 0
	// VerboseBodyOnly ...
	VerboseBodyOnly = 1
	// VerboseAll ...
	VerboseAll = 2
	// VerboseFailOnly ...
	VerboseFailOnly = 3
	// VerboseAllNoRedact ...
	VerboseAllNoRedact = 4
)
View Source
const (
	RotationPolicy = "rotation"
)

Variables

View Source
var (
	// RetryWaitMax is the maximum time to wait between HTTP retries
	RetryWaitMax = 30 * time.Second

	// RetryMax is the max number of attempts to retry for failed HTTP requests
	RetryMax = 4
)

Functions

func DefaultTransport

func DefaultTransport() http.RoundTripper

DefaultTransport ...

func EncryptKey

func EncryptKey(key, pubkey string) (string, error)

EncryptKey will encrypt the user key-material with the public key from key protect

func EncryptKeyWithSHA1 added in v0.5.0

func EncryptKeyWithSHA1(key, pubKey string) (string, error)

EncryptKeyWithSHA1 uses sha1 to encrypt the key

func EncryptNonce

func EncryptNonce(key, value, iv string) (string, string, error)

EncryptNonce will wrap the KP generated nonce with the users key-material

func EncryptNonceWithCBCPAD added in v0.5.0

func EncryptNonceWithCBCPAD(key, value, iv string) (string, string, error)

EncryptNonceWithCBCPAD encrypts the nonce using the user's key-material with CBC encrypter. It will also pad the nonce using pkcs7. This is needed for Hyper Protect Crypto Services, since it supports only CBC Encryption.

func GetCorrelationID added in v0.5.4

func GetCorrelationID(ctx context.Context) *uuid.UUID

GetCorrelationID returns the correlation ID from the context

func NewContextWithAuth

func NewContextWithAuth(parent context.Context, auth string) context.Context

NewContextWithAuth ...

func NewContextWithCorrelationID added in v0.5.4

func NewContextWithCorrelationID(ctx context.Context, uuid *uuid.UUID) context.Context

NewContextWithCorrelationID retuns a context containing the UUID

Types

type API

type API = Client

API is deprecated. Use Client instead.

type AliasesMetadata added in v0.6.0

type AliasesMetadata struct {
	CollectionType  string `json:"collectionType"`
	NumberOfAliases int    `json:"collectionTotal"`
}

AliasesMetadata represents the metadata of a collection of aliases

type AllowedIPPolicyData added in v0.6.0

type AllowedIPPolicyData struct {
	Enabled     bool
	IPAddresses IPAddresses
}

AllowedIPPolicyData defines the attribute input for the Allowed IP instance policy

type AllowedNetworkPolicyData added in v0.6.0

type AllowedNetworkPolicyData struct {
	Enabled bool
	Network string
}

AllowedNetworkPolicyData defines the attribute input for the Allowed Network instance policy

type Attributes added in v0.5.0

type Attributes struct {
	AllowedNetwork    *string     `json:"allowed_network,omitempty"`
	AllowedIP         IPAddresses `json:"allowed_ip,omitempty"`
	CreateRootKey     *bool       `json:"create_root_key,omitempty"`
	CreateStandardKey *bool       `json:"create_standard_key,omitempty"`
	ImportRootKey     *bool       `json:"import_root_key,omitempty"`
	ImportStandardKey *bool       `json:"import_standard_key,omitempty"`
	EnforceToken      *bool       `json:"enforce_token,omitempty"`
}

Attributes contains the detals of allowed network policy type

type BasicPolicyData added in v0.6.0

type BasicPolicyData struct {
	Enabled bool
}

BasicPolicyData defines the attribute input for the policy that supports only enabled parameter

type CallOpt added in v0.3.5

type CallOpt interface{}

type Client

type Client struct {
	URL        *url.URL
	HttpClient http.Client
	Dump       Dump
	Config     ClientConfig
	Logger     Logger
	// contains filtered or unexported fields
}

Client holds configuration and auth information to interact with KeyProtect. It is expected that one of these is created per KeyProtect service instance/credential pair.

func New

func New(config ClientConfig, transport http.RoundTripper) (*Client, error)

New creates and returns a Client without logging.

func NewWithLogger

func NewWithLogger(config ClientConfig, transport http.RoundTripper, logger Logger) (*Client, error)

NewWithLogger creates and returns a Client with logging. The error value will be non-nil if the config is invalid.

func (*Client) CancelDualAuthDelete added in v0.5.0

func (c *Client) CancelDualAuthDelete(ctx context.Context, id string) error

CancelDualAuthDelete unsets the key for deletion. If a key is set for deletion, it can be prevented from getting deleted by unsetting the key for deletion. For more information refer to the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-delete-dual-auth-keys#unset-key-deletion-api

func (*Client) CreateImportToken

func (c *Client) CreateImportToken(ctx context.Context, expiration, maxAllowedRetrievals int) (*ImportTokenMetadata, error)

CreateImportToken creates a key ImportToken.

func (*Client) CreateImportedKey

func (c *Client) CreateImportedKey(ctx context.Context, name string, expiration *time.Time, payload, encryptedNonce, iv string, extractable bool) (*Key, error)

CreateImportedKey creates a new KP key from the given key material.

func (*Client) CreateImportedKeyWithAliases added in v0.6.0

func (c *Client) CreateImportedKeyWithAliases(ctx context.Context, name string, expiration *time.Time, payload, encryptedNonce, iv string, extractable bool, aliases []string) (*Key, error)

CreateImportedKeyWithAliases creates a new key with alias name and provided key material. A key can have a maximum of 5 alias names When importing root keys with import-token encryptedNonce and iv need to passed along with payload. Standard Keys cannot be imported with an import token hence only payload is required. For more information please refer to the links below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-import-root-keys#import-root-key-api https://cloud.ibm.com/docs/key-protect?topic=key-protect-import-standard-keys#import-standard-key-gui

func (*Client) CreateImportedRootKey

func (c *Client) CreateImportedRootKey(ctx context.Context, name string, expiration *time.Time, payload, encryptedNonce, iv string) (*Key, error)

CreateImportedRootKey creates a new, non-extractable key resource with the given key material.

func (*Client) CreateImportedStandardKey

func (c *Client) CreateImportedStandardKey(ctx context.Context, name string, expiration *time.Time, payload string) (*Key, error)

CreateStandardKey creates a new, extractable key resource with the given key material.

func (*Client) CreateKey

func (c *Client) CreateKey(ctx context.Context, name string, expiration *time.Time, extractable bool) (*Key, error)

CreateKey creates a new KP key.

func (*Client) CreateKeyAlias added in v0.6.0

func (c *Client) CreateKeyAlias(ctx context.Context, aliasName, keyID string) (*KeyAlias, error)

CreateKeyAlias creates an alias name for a key. An alias name acts as an identifier just like key ID For more information please refer to the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-create-key-alias#create-key-alias-api

func (*Client) CreateKeyRing added in v0.6.0

func (c *Client) CreateKeyRing(ctx context.Context, id string) error

CreateRing method creates a key ring in the instance with the provided name For information please refer to the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-managing-key-rings#create-key-ring-api

func (*Client) CreateKeyWithAliases added in v0.6.0

func (c *Client) CreateKeyWithAliases(ctx context.Context, name string, expiration *time.Time, extractable bool, aliases []string) (*Key, error)

CreateKeyWithAliaes creats a new key with alias names. A key can have a maximum of 5 alias names. For more information please refer to the links below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-create-root-keys#create-root-key-api https://cloud.ibm.com/docs/key-protect?topic=key-protect-create-standard-keys#create-standard-key-api

func (*Client) CreateRootKey

func (c *Client) CreateRootKey(ctx context.Context, name string, expiration *time.Time) (*Key, error)

CreateRootKey creates a new, non-extractable key resource without key material.

Example
package main

import (
	"context"
	"fmt"

	kp "github.com/IBM/keyprotect-go-client"
)

func main() {
	client, _ := kp.New(
		kp.ClientConfig{
			BaseURL:    "https://us-south.kms.cloud.ibm.com",
			APIKey:     "notARealApiKey",
			InstanceID: "a6493c3a-5b29-4ac3-9eaa-deadbeef3bfd",
		},
		kp.DefaultTransport(),
	)
	ctx := context.Background()

	rootkey, err := client.CreateRootKey(ctx, "mynewrootkey", nil)
	if err != nil {
		fmt.Println("Error while creating root key: ", err)
	} else {
		fmt.Println("New key created: ", *rootkey)
	}
}
Output:

func (*Client) CreateStandardKey

func (c *Client) CreateStandardKey(ctx context.Context, name string, expiration *time.Time) (*Key, error)

CreateStandardKey creates a new, extractable key resource without key material.

Example
package main

import (
	"context"
	"fmt"

	kp "github.com/IBM/keyprotect-go-client"
)

func main() {
	client, _ := kp.New(
		kp.ClientConfig{
			BaseURL:    "https://us-south.kms.cloud.ibm.com",
			APIKey:     "notARealApiKey",
			InstanceID: "a6493c3a-5b29-4ac3-9eaa-deadbeef3bfd",
		},
		kp.DefaultTransport(),
	)

	fmt.Println("Creating standard key")
	rootkey, err := client.CreateStandardKey(context.Background(), "mynewstandardkey", nil)
	if err != nil {
		fmt.Println("Error while creating standard key: ", err)
	} else {
		fmt.Println("New key created: ", *rootkey)
	}
}
Output:

func (*Client) DeleteKey

func (c *Client) DeleteKey(ctx context.Context, id string, prefer PreferReturn, callOpts ...CallOpt) (*Key, error)

DeleteKey deletes a key resource by specifying the ID of the key.

Example
package main

import (
	"context"
	"fmt"

	kp "github.com/IBM/keyprotect-go-client"
)

func main() {
	client, _ := kp.New(
		kp.ClientConfig{
			BaseURL:    "https://us-south.kms.cloud.ibm.com",
			APIKey:     "notARealApiKey",
			InstanceID: "a6493c3a-5b29-4ac3-9eaa-deadbeef3bfd",
		},
		kp.DefaultTransport(),
	)
	keyId := "1234abcd-abcd-asdf-9eaa-deadbeefabcd"

	fmt.Println("Deleting standard key")
	delKey, err := client.DeleteKey(context.Background(), keyId, kp.ReturnRepresentation)
	if err != nil {
		fmt.Println("Error while deleting: ", err)
	} else {
		fmt.Println("Deleted key: ", delKey)
	}
}
Output:

func (*Client) DeleteKeyAlias added in v0.6.0

func (c *Client) DeleteKeyAlias(ctx context.Context, aliasName, keyID string) error

DeleteKeyAlias deletes an alias name associated with a key For more information please refer to the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-create-key-alias#delete-key-alias

func (*Client) DeleteKeyRing added in v0.6.0

func (c *Client) DeleteKeyRing(ctx context.Context, id string) error

DeleteRing method deletes the key ring with the provided name in the instance For information please refer to the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-managing-key-rings#delete-key-ring-api

func (*Client) DisableKey added in v0.5.0

func (c *Client) DisableKey(ctx context.Context, id string) error

Disable a key. The key will not be deleted but it will not be active and key operations cannot be performed on a disabled key. For more information can refer to the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-disable-keys

func (*Client) EnableKey added in v0.5.0

func (c *Client) EnableKey(ctx context.Context, id string) error

Enable a key. Only disabled keys can be enabled. After enable the key becomes active and key operations can be performed on it. Note: This does not recover Deleted keys. For more information can refer to the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-disable-keys#enable-api

func (*Client) GetAllowedIPInstancePolicy added in v0.6.0

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

GetAllowedIPInstancePolicy retrieves the allowed IP instance policy details associated with the instance. For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-allowed-ip

func (*Client) GetAllowedIPPrivateNetworkPort added in v0.6.0

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

GetAllowedIPPrivateNetworkPort retrieves the private endpoint port assigned to allowed ip policy.

func (*Client) GetAllowedNetworkInstancePolicy added in v0.5.0

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

GetAllowedNetworkInstancePolicy retrieves the allowed network policy details associated with the instance. For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-managing-network-access-policies

func (*Client) GetDualAuthDeletePolicy added in v0.5.0

func (c *Client) GetDualAuthDeletePolicy(ctx context.Context, id string) (*Policy, error)

GetDualAuthDeletePolicy method retrieves dual auth delete policy details of a key For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-set-dual-auth-key-policy#view-dual-auth-key-policy-api

func (*Client) GetDualAuthInstancePolicy added in v0.5.0

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

GetDualAuthInstancePolicy retrieves the dual auth delete policy details associated with the instance For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-dual-auth

func (*Client) GetImportTokenTransportKey

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

GetImportTokenTransportKey retrieves the ImportToken transport key.

func (*Client) GetInstancePolicies added in v0.4.0

func (c *Client) GetInstancePolicies(ctx context.Context) ([]InstancePolicy, error)

GetInstancePolicies retrieves all policies of an Instance.

func (*Client) GetKey

func (c *Client) GetKey(ctx context.Context, idOrAlias string) (*Key, error)

GetKey retrieves a key by ID or alias name. For more information on Key Alias please refer to the link below https://cloud.ibm.com/docs/key-protect?topic=key-protect-retrieve-key

Example
package main

import (
	"context"
	"fmt"

	kp "github.com/IBM/keyprotect-go-client"
)

func main() {
	client, _ := kp.New(
		kp.ClientConfig{
			BaseURL:    "https://us-south.kms.cloud.ibm.com",
			APIKey:     "notARealApiKey",
			InstanceID: "a6493c3a-5b29-4ac3-9eaa-deadbeef3bfd",
		},
		kp.DefaultTransport(),
	)
	keyId := "1234abcd-abcd-asdf-9eaa-deadbeefabcd"

	fmt.Println("Getting standard key")
	key, err := client.GetKey(context.Background(), keyId)
	if err != nil {
		fmt.Println("Get Key failed with error: ", err)
	} else {
		fmt.Printf("Key: %v\n", *key)
	}
}
Output:

func (*Client) GetKeyCreateImportAccessInstancePolicy added in v0.6.0

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

GetKeyCreateImportAccessInstancePolicy retrieves the key create import access policy details associated with the instance. For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-keyCreateImportAccess

func (*Client) GetKeyMetadata added in v0.5.0

func (c *Client) GetKeyMetadata(ctx context.Context, idOrAlias string) (*Key, error)

GetKeyMetadata retrieves the metadata of a Key by ID or alias name. Note that the "/api/v2/keys/{id}/metadata" API does not return the payload, therefore the payload attribute in the Key pointer will always be empty. If you need the payload, you need to use the GetKey() function with the correct service access role. https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-access#service-access-roles

func (*Client) GetKeyRings added in v0.6.0

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

GetRings method retrieves all the key rings associated with the instance For information please refer to the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-managing-key-rings#list-key-ring-api

func (*Client) GetKeys

func (c *Client) GetKeys(ctx context.Context, limit int, offset int) (*Keys, error)

GetKeys retrieves a collection of keys that can be paged through.

func (*Client) GetMetricsInstancePolicy added in v0.6.0

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

GetMetricsInstancePolicy retrieves the metrics policy details associated with the instance For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-sysdig-metrics

func (*Client) GetPolicies added in v0.5.0

func (c *Client) GetPolicies(ctx context.Context, id string) ([]Policy, error)

GetPolicies retrieves all policies details associated with a Key ID.

func (*Client) GetPolicy

func (c *Client) GetPolicy(ctx context.Context, id string) (*Policy, error)

GetPolicy retrieves a policy by Key ID. This function is deprecated, as it only returns one policy and does not let you select which policy set it will return. It is kept for backward compatibility on keys with only one rotation policy. Please update to use the new GetPolicies or Get<type>Policy functions.

func (*Client) GetRotationPolicy added in v0.5.0

func (c *Client) GetRotationPolicy(ctx context.Context, id string) (*Policy, error)

GetRotationPolivy method retrieves rotation policy details of a key For more information can refet the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-set-rotation-policy#view-rotation-policy-api

func (*Client) InitiateDualAuthDelete added in v0.5.0

func (c *Client) InitiateDualAuthDelete(ctx context.Context, id string) error

InitiateDualAuthDelete sets a key for deletion. The key must be configured with a DualAuthDelete policy. After the key is set to deletion it can be deleted by another user who has Manager access. For more information refer to the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-delete-dual-auth-keys#set-key-deletion-api

func (*Client) ListRegistrations added in v0.5.0

func (c *Client) ListRegistrations(ctx context.Context, keyId, crn string) (*registrations, error)

ListRegistrations retrieves a collection of registrations

func (*Client) RestoreKey added in v0.5.0

func (c *Client) RestoreKey(ctx context.Context, id string) (*Key, error)

RestoreKey method reverts a delete key status to active key This method performs restore of any key from deleted state to active state. For more information please refer to the link below: https://cloud.ibm.com/dowcs/key-protect?topic=key-protect-restore-keys

func (*Client) Rotate

func (c *Client) Rotate(ctx context.Context, id, payload string) error

Rotate rotates a CRK.

func (*Client) SetAllowedIPInstancePolicy added in v0.6.0

func (c *Client) SetAllowedIPInstancePolicy(ctx context.Context, enable bool, allowedIPs []string) error

SetAllowedIPInstancePolices updates the allowed IP instance policy details associated with an instance. For more information can refet to the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-allowed-ip

func (*Client) SetAllowedNetworkInstancePolicy added in v0.5.0

func (c *Client) SetAllowedNetworkInstancePolicy(ctx context.Context, enable bool, networkType string) error

SetAllowedNetWorkInstancePolicy updates the allowed network policy details associated with an instance For more information can refer to the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-managing-network-access-policies

func (*Client) SetDualAuthDeletePolicy added in v0.5.0

func (c *Client) SetDualAuthDeletePolicy(ctx context.Context, id string, enabled bool) (*Policy, error)

SetDualAuthDeletePolicy updates the dual auth delete policy by passing the key ID and enable detail For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-set-dual-auth-key-policy#create-dual-auth-key-policy-api

func (*Client) SetDualAuthInstancePolicy added in v0.5.0

func (c *Client) SetDualAuthInstancePolicy(ctx context.Context, enable bool) error

SetDualAuthInstancePolicy updates the dual auth delete policy details associated with an instance For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-dual-auth

func (*Client) SetInstancePolicies added in v0.4.0

func (c *Client) SetInstancePolicies(ctx context.Context, policies MultiplePolicies) error

SetInstancePolicies updates single or multiple policy details of an instance.

func (*Client) SetKeyCreateImportAccessInstancePolicy added in v0.6.0

func (c *Client) SetKeyCreateImportAccessInstancePolicy(ctx context.Context, enable bool, attributes map[string]bool) error

SetKeyCreateImportAccessInstancePolicy updates the key create import access policy details associated with an instance. For more information, please refer to the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-keyCreateImportAccess

func (*Client) SetMetricsInstancePolicy added in v0.6.0

func (c *Client) SetMetricsInstancePolicy(ctx context.Context, enable bool) error

SetMetricsInstancePolicy updates the metrics policy details associated with an instance For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-sysdig-metrics

func (*Client) SetPolicies added in v0.5.0

func (c *Client) SetPolicies(ctx context.Context, id string, setRotationPolicy bool, rotationInterval int, setDualAuthDeletePolicy, dualAuthEnable bool) ([]Policy, error)

SetPolicies updates all policies of the key or a single policy by passing key ID. To set rotation policy for the key pass the setRotationPolicy parameter as true and set the rotationInterval detail. To set dual auth delete policy for the key pass the setDualAuthDeletePolicy parameter as true and set the dualAuthEnable detail. Both the policies can be set or either of the policies can be set.

func (*Client) SetPolicy

func (c *Client) SetPolicy(ctx context.Context, id string, prefer PreferReturn, rotationInterval int) (*Policy, error)

SetPolicy updates a policy resource by specifying the ID of the key and the rotation interval needed. This function is deprecated as it will only let you set key rotation policies. To set dual auth and other newer policies on a key, please use the new SetPolicies of Set<type>Policy functions.

func (*Client) SetRotationPolicy added in v0.5.0

func (c *Client) SetRotationPolicy(ctx context.Context, id string, rotationInterval int) (*Policy, error)

SetRotationPolicy updates the rotation policy associated with a key by specifying key ID and rotation interval. For more information can refer the Key Protect docs in the link below: https://cloud.ibm.com/docs/key-protect?topic=key-protect-set-rotation-policy#update-rotation-policy-api

func (*Client) Unwrap

func (c *Client) Unwrap(ctx context.Context, id string, cipherText []byte, additionalAuthData *[]string) ([]byte, error)

Unwrap is deprecated since it returns only plaintext and doesn't know how to handle rotation.

func (*Client) UnwrapV2

func (c *Client) UnwrapV2(ctx context.Context, id string, cipherText []byte, additionalAuthData *[]string) ([]byte, []byte, error)

Unwrap with rotation support.

Example
package main

import (
	"context"
	"fmt"

	kp "github.com/IBM/keyprotect-go-client"
)

func main() {
	client, _ := kp.New(
		kp.ClientConfig{
			BaseURL:    "https://us-south.kms.cloud.ibm.com",
			APIKey:     "notARealApiKey",
			InstanceID: "a6493c3a-5b29-4ac3-9eaa-deadbeef3bfd",
		},
		kp.DefaultTransport(),
	)

	keyId := "1234abcd-abcd-asdf-9eaa-deadbeefabcd"
	wrappedDek := []byte("dGhpcyBpc24ndCBhIHJlYWwgcGF5bG9hZAo=")
	aad := []string{
		"AAD can be pretty much any string value.",
		"This entire array of strings is the AAD.",
		"It has to be the same on wrap and unwrap, however",
		"This can be useful, if the DEK should be bound to an application name",
		"or possibly a hostname, IP address, or even email address.",
		"For example",
		"appname=golang-examples;",
		"It is not secret though, so don't put anything sensitive here",
	}

	ctx := context.Background()

	dek, rewrapped, err := client.UnwrapV2(ctx, keyId, wrappedDek, &aad)
	if err != nil {
		fmt.Println("Error while unwrapping DEK: ", err)
	} else {
		fmt.Println("Unwrapped key successfully")
	}

	if len(dek) != 32 {
		fmt.Println("DEK length was not 32 bytes (not a 256 bit key)")
	}

	// dek is your plaintext DEK, use it for encrypt/decrypt then throw it away
	// rewrapped is POSSIBLY a new WDEK, if it is not empty, store that and use it on next Unwrap

	if len(rewrapped) > 0 {
		fmt.Printf("Your DEK was rewrapped with a new key version. Your new WDEK is %v\n", rewrapped)

		// store new WDEK
		wrappedDek = rewrapped
	}

}
Output:

func (*Client) Wrap

func (c *Client) Wrap(ctx context.Context, id string, plainText []byte, additionalAuthData *[]string) ([]byte, error)

Wrap calls the wrap action with the given plain text.

func (*Client) WrapCreateDEK

func (c *Client) WrapCreateDEK(ctx context.Context, id string, additionalAuthData *[]string) ([]byte, []byte, error)

WrapCreateDEK calls the wrap action without plain text.

Example
package main

import (
	"context"
	"fmt"

	kp "github.com/IBM/keyprotect-go-client"
)

func main() {
	client, _ := kp.New(
		kp.ClientConfig{
			BaseURL:    "https://us-south.kms.cloud.ibm.com",
			APIKey:     "notARealApiKey",
			InstanceID: "a6493c3a-5b29-4ac3-9eaa-deadbeef3bfd",
		},
		kp.DefaultTransport(),
	)

	keyId := "1234abcd-abcd-asdf-9eaa-deadbeefabcd"
	aad := []string{
		"AAD can be pretty much any string value.",
		"This entire array of strings is the AAD.",
		"It has to be the same on wrap and unwrap, however",
		"This can be useful, if the DEK should be bound to an application name",
		"or possibly a hostname, IP address, or even email address.",
		"For example",
		"appname=golang-examples;",
		"It is not secret though, so don't put anything sensitive here",
	}

	ctx := context.Background()

	dek, wrappedDek, err := client.WrapCreateDEK(ctx, keyId, &aad)
	if err != nil {
		fmt.Println("Error while creating a DEK: ", err)
	} else {
		fmt.Println("Created new random DEK")
	}

	if len(dek) != 32 {
		fmt.Println("DEK length was not 32 bytes (not a 256 bit key)")
	}

	fmt.Printf("Your WDEK is: %v\n", wrappedDek)

	// dek is your plaintext DEK, use it for encrypt/decrypt and throw it away
	// wrappedDek is your WDEK, keep this and pass it to Unwrap to get back your DEK when you need it again
}
Output:

type ClientConfig

type ClientConfig struct {
	BaseURL       string
	Authorization string  // The IBM Cloud (Bluemix) access token
	APIKey        string  // Service ID API key, can be used instead of an access token
	TokenURL      string  // The URL used to get an access token from the API key
	InstanceID    string  // The IBM Cloud (Bluemix) instance ID that identifies your Key Protect service instance.
	KeyRing       string  // The ID of the target Key Ring the key is associated with. It is optional but recommended for better performance.
	Verbose       int     // See verbose values above
	Timeout       float64 // KP request timeout in seconds.
}

ClientConfig ...

type ContextKey

type ContextKey int

ContextKey provides a type to auth context keys.

type DualAuth added in v0.5.0

type DualAuth struct {
	Enabled *bool `json:"enabled,omitempty"`
}

type Dump

type Dump func(*http.Request, *http.Response, []byte, []byte, Logger, []string)

Dump writes various parts of an HTTP request and an HTTP response.

type Error

type Error struct {
	URL           string   // URL of request that resulted in this error
	StatusCode    int      // HTTP error code from KeyProtect service
	Message       string   // error message from KeyProtect service
	BodyContent   []byte   // raw body content if more inspection is needed
	CorrelationID string   // string value of a UUID that uniquely identifies the request to KeyProtect
	Reasons       []reason // collection of reason types containing detailed error messages
}

func (Error) Error

func (e Error) Error() string

Error returns correlation id and error message string

type ForceOpt added in v0.3.5

type ForceOpt struct {
	Force bool
}

type IPAddresses added in v0.6.0

type IPAddresses []string

IPAddresses ...

type ImportTokenCreateRequest

type ImportTokenCreateRequest struct {
	MaxAllowedRetrievals int `json:"maxAllowedRetrievals,omitempty"`
	ExpiresInSeconds     int `json:"expiration,omitempty"`
}

ImportTokenCreateRequest represents request parameters for creating a ImportToken.

type ImportTokenKeyResponse

type ImportTokenKeyResponse struct {
	ID             string     `json:"id"`
	CreationDate   *time.Time `json:"creationDate"`
	ExpirationDate *time.Time `json:"expirationDate"`
	Payload        string     `json:"payload"`
	Nonce          string     `json:"nonce"`
}

ImportTokenKeyResponse represents the response body for various ImportToken API calls.

type ImportTokenMetadata

type ImportTokenMetadata struct {
	ID                   string     `json:"id"`
	CreationDate         *time.Time `json:"creationDate"`
	ExpirationDate       *time.Time `json:"expirationDate"`
	MaxAllowedRetrievals int        `json:"maxAllowedRetrievals"`
	RemainingRetrievals  int        `json:"remainingRetrievals"`
}

ImportTokenMetadata represents the metadata of a ImportToken.

type InstancePolicies added in v0.4.0

type InstancePolicies struct {
	Metadata PoliciesMetadata `json:"metadata"`
	Policies []InstancePolicy `json:"resources"`
}

InstancePolicies represents a collection of Policies associated with Key Protect instances.

type InstancePolicy added in v0.4.0

type InstancePolicy struct {
	CreatedBy  string     `json:"createdBy,omitempty"`
	CreatedAt  *time.Time `json:"creationDate,omitempty"`
	UpdatedAt  *time.Time `json:"lastUpdated,omitempty"`
	UpdatedBy  string     `json:"updatedBy,omitempty"`
	PolicyType string     `json:"policy_type,omitempty"`
	PolicyData PolicyData `json:"policy_data,omitempty" mapstructure:"policyData"`
}

InstancePolicy represents a instance-level policy of a key as returned by the KP API. this policy enables dual authorization for deleting a key

type Key

type Key struct {
	ID                  string      `json:"id,omitempty"`
	Name                string      `json:"name,omitempty"`
	Description         string      `json:"description,omitempty"`
	Type                string      `json:"type,omitempty"`
	Tags                []string    `json:"Tags,omitempty"`
	Aliases             []string    `json:"aliases,omitempty"`
	AlgorithmType       string      `json:"algorithmType,omitempty"`
	CreatedBy           string      `json:"createdBy,omitempty"`
	CreationDate        *time.Time  `json:"creationDate,omitempty"`
	LastUpdateDate      *time.Time  `json:"lastUpdateDate,omitempty"`
	LastRotateDate      *time.Time  `json:"lastRotateDate,omitempty"`
	KeyVersion          *KeyVersion `json:"keyVersion,omitempty" mapstructure:keyVersion`
	KeyRingID           string      `json:"keyRingID,omitempty"`
	Extractable         bool        `json:"extractable"`
	Expiration          *time.Time  `json:"expirationDate,omitempty"`
	Imported            bool        `json:"imported,omitempty"`
	Payload             string      `json:"payload,omitempty"`
	State               int         `json:"state,omitempty"`
	EncryptionAlgorithm string      `json:"encryptionAlgorithm,omitempty"`
	CRN                 string      `json:"crn,omitempty"`
	EncryptedNonce      string      `json:"encryptedNonce,omitempty"`
	IV                  string      `json:"iv,omitempty"`
	Deleted             *bool       `json:"deleted,omitempty"`
	DeletedBy           *string     `json:"deletedBy,omitempty"`
	DeletionDate        *time.Time  `json:"deletionDate,omitempty"`
	DualAuthDelete      *DualAuth   `json:"dualAuthDelete,omitempty"`
}

Key represents a key as returned by the KP API.

type KeyAlias added in v0.6.0

type KeyAlias struct {
	KeyID        string     `json:"keyId,omitempty"`
	Alias        string     `json:"alias,omitempty"`
	CreatedBy    string     `json:"createdBy,omitempty"`
	CreationDate *time.Time `json:"creationDate,omitempty"`
}

KeyAlias represents an Alias details of a key as returned by KP API

type KeyAliases added in v0.6.0

type KeyAliases struct {
	Metadata   AliasesMetadata `json:"metadata"`
	KeyAliases []KeyAlias      `json:"resources"`
}

type KeyCreateImportAccessInstancePolicy added in v0.6.0

type KeyCreateImportAccessInstancePolicy struct {
	Enabled           bool
	CreateRootKey     bool
	CreateStandardKey bool
	ImportRootKey     bool
	ImportStandardKey bool
	EnforceToken      bool
}

KeyAccessInstancePolicyData defines the attribute input for the Key Create Import Access instance policy

type KeyRing added in v0.6.0

type KeyRing struct {
	ID           string     `json:"id,omitempty"`
	CreationDate *time.Time `json:"creationDate,omitempty"`
	CreatedBy    string     `json:"createdBy,omitempty"`
}

type KeyRings added in v0.6.0

type KeyRings struct {
	Metadata KeysMetadata `json:"metadata"`
	KeyRings []KeyRing    `json:"resources"`
}

type KeyVersion added in v0.5.0

type KeyVersion struct {
	ID           string     `json:"id,omitempty"`
	CreationDate *time.Time `json:"creationDate,omitempty"`
}

type Keys

type Keys struct {
	Metadata KeysMetadata `json:"metadata"`
	Keys     []Key        `json:"resources"`
}

Keys represents a collection of Keys.

type KeysActionRequest

type KeysActionRequest struct {
	PlainText  string   `json:"plaintext,omitempty"`
	AAD        []string `json:"aad,omitempty"`
	CipherText string   `json:"ciphertext,omitempty"`
	Payload    string   `json:"payload,omitempty"`
}

KeysActionRequest represents request parameters for a key action API call.

type KeysMetadata

type KeysMetadata struct {
	CollectionType string `json:"collectionType"`
	NumberOfKeys   int    `json:"collectionTotal"`
}

KeysMetadata represents the metadata of a collection of keys.

type Logger

type Logger interface {
	Info(...interface{})
}

Logger writes when called.

func NewLogger

func NewLogger(writer func(...interface{})) Logger

type MultiplePolicies added in v0.6.0

type MultiplePolicies struct {
	DualAuthDelete        *BasicPolicyData
	AllowedNetwork        *AllowedNetworkPolicyData
	AllowedIP             *AllowedIPPolicyData
	Metrics               *BasicPolicyData
	KeyCreateImportAccess *KeyCreateImportAccessInstancePolicy
}

MultiplePolicies defines the input for the SetInstancPolicies method that can hold multiple policy details

type Policies

type Policies struct {
	Metadata PoliciesMetadata `json:"metadata"`
	Policies []Policy         `json:"resources"`
}

Policies represents a collection of Policies.

type PoliciesMetadata

type PoliciesMetadata struct {
	CollectionType   string `json:"collectionType"`
	NumberOfPolicies int    `json:"collectionTotal"`
}

PoliciesMetadata represents the metadata of a collection of keys.

type Policy

type Policy struct {
	Type      string     `json:"type,omitempty"`
	CreatedBy string     `json:"createdBy,omitempty"`
	CreatedAt *time.Time `json:"creationDate,omitempty"`
	CRN       string     `json:"crn,omitempty"`
	UpdatedAt *time.Time `json:"lastUpdateDate,omitempty"`
	UpdatedBy string     `json:"updatedBy,omitempty"`
	Rotation  *Rotation  `json:"rotation,omitempty"`
	DualAuth  *DualAuth  `json:"dualAuthDelete,omitempty"`
}

Policy represents a policy as returned by the KP API.

type PolicyData added in v0.5.0

type PolicyData struct {
	Enabled    *bool       `json:"enabled,omitempty"`
	Attributes *Attributes `json:"attributes,omitempty"`
}

PolicyData contains the details of the policy type

type PreferReturn

type PreferReturn int

PreferReturn designates the value for the "Prefer" header.

const (
	ReturnMinimal        PreferReturn = 0
	ReturnRepresentation PreferReturn = 1
)

type Redact

type Redact func(string, []string) string

Redact replaces various pieces of output.

type Registration added in v0.5.0

type Registration struct {
	KeyID              string     `json:"keyId,omitempty"`
	ResourceCrn        string     `json:"resourceCrn,omitempty"`
	CreatedBy          string     `json:"createdBy,omitempty"`
	CreationDate       *time.Time `json:"creationDate,omitempty"`
	UpdatedBy          string     `json:"updatedBy,omitempty"`
	LastUpdateDate     *time.Time `json:"lastUpdated,omitempty"`
	Description        string     `json:"description,omitempty"`
	PreventKeyDeletion bool       `json:"preventKeyDeletion,omitempty"`
	KeyVersion         KeyVersion `json:"keyVersion,omitempty"`
}

Registration represents the registration as returned by KP API

type Rotation added in v0.5.0

type Rotation struct {
	Interval int `json:"interval_month,omitempty"`
}

type URLError

type URLError struct {
	Err           error
	CorrelationID string
}

URLError wraps an error from client.do() calls with a correlation ID from KeyProtect

func (URLError) Error

func (e URLError) Error() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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