or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/cloud.google.com/go/kms@v1.24.0
tile.json

tessl/golang-cloud-google-com--go--kms

tessl install tessl/golang-cloud-google-com--go--kms@1.24.0

Go Client Library for Google Cloud Key Management Service (KMS) API for managing cryptographic keys and performing cryptographic operations

index.mddocs/

Google Cloud Key Management Service (KMS) - Go Client Library

Overview

The Google Cloud Key Management Service (KMS) Go client library provides comprehensive functionality for managing cryptographic keys and performing cryptographic operations in Google Cloud Platform. This library enables developers to centrally manage encryption keys, perform cryptographic operations, and integrate with other Google Cloud services for Customer Managed Encryption Keys (CMEK).

KMS is designed for applications requiring secure key management, data encryption at rest and in transit, digital signing, regulatory compliance (FIPS 140-2, etc.), and integration with external key managers.

Package Information

Package Name: cloud.google.com/go/kms

Version: v1.24.0

Language: Go

License: Apache-2.0

Installation:

go get cloud.google.com/go/kms/apiv1@v1.24.0

Documentation: https://cloud.google.com/kms/docs

Core Imports

The library is organized into four main packages:

import (
    kms "cloud.google.com/go/kms/apiv1"
    "cloud.google.com/go/kms/apiv1/kmspb"
    inventory "cloud.google.com/go/kms/inventory/apiv1"
    "cloud.google.com/go/kms/inventory/apiv1/inventorypb"
)
  • cloud.google.com/go/kms/apiv1 - Main client package with KeyManagementClient, AutokeyClient, AutokeyAdminClient, and EkmClient
  • cloud.google.com/go/kms/apiv1/kmspb - Protocol buffer types for KMS resources, requests, responses, and enums
  • cloud.google.com/go/kms/inventory/apiv1 - Inventory clients for cross-project key visibility (KeyDashboardClient, KeyTrackingClient)
  • cloud.google.com/go/kms/inventory/apiv1/inventorypb - Protocol buffer types for inventory operations

Basic Usage

Creating a Client

All KMS operations start by creating a client. Clients are thread-safe and should be reused:

package main

import (
    "context"
    "log"

    kms "cloud.google.com/go/kms/apiv1"
)

func main() {
    ctx := context.Background()

    // Create gRPC client (recommended for performance)
    client, err := kms.NewKeyManagementClient(ctx)
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }
    defer client.Close()

    // Client is ready to use
}

Encrypting Data

import (
    "cloud.google.com/go/kms/apiv1/kmspb"
)

func encryptData(client *kms.KeyManagementClient, cryptoKeyName string, plaintext []byte) ([]byte, error) {
    ctx := context.Background()

    req := &kmspb.EncryptRequest{
        Name:      cryptoKeyName, // e.g., "projects/my-project/locations/us-central1/keyRings/my-keyring/cryptoKeys/my-key"
        Plaintext: plaintext,
    }

    resp, err := client.Encrypt(ctx, req)
    if err != nil {
        return nil, err
    }

    return resp.Ciphertext, nil
}

Decrypting Data

func decryptData(client *kms.KeyManagementClient, cryptoKeyName string, ciphertext []byte) ([]byte, error) {
    ctx := context.Background()

    req := &kmspb.DecryptRequest{
        Name:       cryptoKeyName,
        Ciphertext: ciphertext,
    }

    resp, err := client.Decrypt(ctx, req)
    if err != nil {
        return nil, err
    }

    return resp.Plaintext, nil
}

Creating a Key Ring and Crypto Key

func createKeyRingAndKey(client *kms.KeyManagementClient, projectID, locationID, keyRingID, cryptoKeyID string) error {
    ctx := context.Background()

    // Create Key Ring
    parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
    keyRing, err := client.CreateKeyRing(ctx, &kmspb.CreateKeyRingRequest{
        Parent:    parent,
        KeyRingId: keyRingID,
        KeyRing:   &kmspb.KeyRing{},
    })
    if err != nil {
        return fmt.Errorf("create key ring: %w", err)
    }

    // Create Crypto Key for encryption/decryption
    _, err = client.CreateCryptoKey(ctx, &kmspb.CreateCryptoKeyRequest{
        Parent:      keyRing.Name,
        CryptoKeyId: cryptoKeyID,
        CryptoKey: &kmspb.CryptoKey{
            Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
            VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
                Algorithm:       kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
                ProtectionLevel: kmspb.ProtectionLevel_SOFTWARE,
            },
        },
    })
    if err != nil {
        return fmt.Errorf("create crypto key: %w", err)
    }

    return nil
}

Architecture

Client Hierarchy

The KMS Go library provides six specialized clients organized by functionality:

Core KMS Operations:

  • KeyManagementClient - Primary client for key and cryptographic operations (40+ methods)

Automated Key Provisioning:

  • AutokeyClient - Creates KeyHandles to trigger automatic CryptoKey provisioning
  • AutokeyAdminClient - Manages Autokey folder-level configurations

External Key Management:

  • EkmClient - Manages external key manager connections and operations

Cross-Project Inventory:

  • KeyDashboardClient - Aggregated views of KMS keys across organizations
  • KeyTrackingClient - Tracks resources protected by KMS keys

Resource Model

KMS organizes resources in a hierarchical structure:

projects/{project}/locations/{location}/
└── keyRings/{keyRing}/
    ├── cryptoKeys/{cryptoKey}/
    │   └── cryptoKeyVersions/{version}
    └── importJobs/{importJob}

KeyRing - Logical grouping of CryptoKeys (cannot be deleted once created)

CryptoKey - Logical key with a specific purpose (ENCRYPT_DECRYPT, ASYMMETRIC_SIGN, MAC, etc.)

CryptoKeyVersion - Individual cryptographic key material (keys can have multiple versions for rotation)

ImportJob - Facilitates importing externally-generated key material

Capabilities

1. Key Management Operations

Create, retrieve, update, and manage cryptographic keys and key rings across your GCP projects.

Key APIs:

// Key Ring Management
func (c *KeyManagementClient) CreateKeyRing(ctx context.Context, req *kmspb.CreateKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error)
func (c *KeyManagementClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error)
func (c *KeyManagementClient) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest, opts ...gax.CallOption) *KeyRingIterator

// Crypto Key Management
func (c *KeyManagementClient) CreateCryptoKey(ctx context.Context, req *kmspb.CreateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)
func (c *KeyManagementClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)
func (c *KeyManagementClient) UpdateCryptoKey(ctx context.Context, req *kmspb.UpdateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)
func (c *KeyManagementClient) ListCryptoKeys(ctx context.Context, req *kmspb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator

// Key Version Management
func (c *KeyManagementClient) CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)
func (c *KeyManagementClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyPrimaryVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)
func (c *KeyManagementClient) DestroyCryptoKeyVersion(ctx context.Context, req *kmspb.DestroyCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)
func (c *KeyManagementClient) RestoreCryptoKeyVersion(ctx context.Context, req *kmspb.RestoreCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)

Complete Key Management Client Documentation

2. Cryptographic Operations

Perform encryption, decryption, signing, MAC operations, and key encapsulation using managed keys.

Key APIs:

// Symmetric Encryption/Decryption
func (c *KeyManagementClient) Encrypt(ctx context.Context, req *kmspb.EncryptRequest, opts ...gax.CallOption) (*kmspb.EncryptResponse, error)
func (c *KeyManagementClient) Decrypt(ctx context.Context, req *kmspb.DecryptRequest, opts ...gax.CallOption) (*kmspb.DecryptResponse, error)

// Raw Symmetric Operations (portable cryptographic primitives)
func (c *KeyManagementClient) RawEncrypt(ctx context.Context, req *kmspb.RawEncryptRequest, opts ...gax.CallOption) (*kmspb.RawEncryptResponse, error)
func (c *KeyManagementClient) RawDecrypt(ctx context.Context, req *kmspb.RawDecryptRequest, opts ...gax.CallOption) (*kmspb.RawDecryptResponse, error)

// Asymmetric Operations
func (c *KeyManagementClient) AsymmetricSign(ctx context.Context, req *kmspb.AsymmetricSignRequest, opts ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error)
func (c *KeyManagementClient) AsymmetricDecrypt(ctx context.Context, req *kmspb.AsymmetricDecryptRequest, opts ...gax.CallOption) (*kmspb.AsymmetricDecryptResponse, error)
func (c *KeyManagementClient) GetPublicKey(ctx context.Context, req *kmspb.GetPublicKeyRequest, opts ...gax.CallOption) (*kmspb.PublicKey, error)

// MAC Operations
func (c *KeyManagementClient) MacSign(ctx context.Context, req *kmspb.MacSignRequest, opts ...gax.CallOption) (*kmspb.MacSignResponse, error)
func (c *KeyManagementClient) MacVerify(ctx context.Context, req *kmspb.MacVerifyRequest, opts ...gax.CallOption) (*kmspb.MacVerifyResponse, error)

// Key Encapsulation
func (c *KeyManagementClient) Decapsulate(ctx context.Context, req *kmspb.DecapsulateRequest, opts ...gax.CallOption) (*kmspb.DecapsulateResponse, error)

// Random Number Generation
func (c *KeyManagementClient) GenerateRandomBytes(ctx context.Context, req *kmspb.GenerateRandomBytesRequest, opts ...gax.CallOption) (*kmspb.GenerateRandomBytesResponse, error)

Complete Key Management Client Documentation

3. Automated Key Provisioning (Autokey)

Automate CryptoKey provisioning on-demand for Customer Managed Encryption Key (CMEK) use cases.

Key APIs:

// AutokeyClient - Create and manage KeyHandles
func (c *AutokeyClient) CreateKeyHandle(ctx context.Context, req *kmspb.CreateKeyHandleRequest, opts ...gax.CallOption) (*CreateKeyHandleOperation, error)
func (c *AutokeyClient) GetKeyHandle(ctx context.Context, req *kmspb.GetKeyHandleRequest, opts ...gax.CallOption) (*kmspb.KeyHandle, error)
func (c *AutokeyClient) ListKeyHandles(ctx context.Context, req *kmspb.ListKeyHandlesRequest, opts ...gax.CallOption) *KeyHandleIterator

// AutokeyAdminClient - Configure Autokey at folder level
func (c *AutokeyAdminClient) UpdateAutokeyConfig(ctx context.Context, req *kmspb.UpdateAutokeyConfigRequest, opts ...gax.CallOption) (*kmspb.AutokeyConfig, error)
func (c *AutokeyAdminClient) GetAutokeyConfig(ctx context.Context, req *kmspb.GetAutokeyConfigRequest, opts ...gax.CallOption) (*kmspb.AutokeyConfig, error)
func (c *AutokeyAdminClient) ShowEffectiveAutokeyConfig(ctx context.Context, req *kmspb.ShowEffectiveAutokeyConfigRequest, opts ...gax.CallOption) (*kmspb.ShowEffectiveAutokeyConfigResponse, error)

Autokey Client Documentation

4. External Key Manager (EKM)

Manage connections to external key managers and use externally-managed cryptographic keys.

Key APIs:

// EKM Connection Management
func (c *EkmClient) CreateEkmConnection(ctx context.Context, req *kmspb.CreateEkmConnectionRequest, opts ...gax.CallOption) (*kmspb.EkmConnection, error)
func (c *EkmClient) GetEkmConnection(ctx context.Context, req *kmspb.GetEkmConnectionRequest, opts ...gax.CallOption) (*kmspb.EkmConnection, error)
func (c *EkmClient) UpdateEkmConnection(ctx context.Context, req *kmspb.UpdateEkmConnectionRequest, opts ...gax.CallOption) (*kmspb.EkmConnection, error)
func (c *EkmClient) ListEkmConnections(ctx context.Context, req *kmspb.ListEkmConnectionsRequest, opts ...gax.CallOption) *EkmConnectionIterator

// EKM Configuration
func (c *EkmClient) GetEkmConfig(ctx context.Context, req *kmspb.GetEkmConfigRequest, opts ...gax.CallOption) (*kmspb.EkmConfig, error)
func (c *EkmClient) UpdateEkmConfig(ctx context.Context, req *kmspb.UpdateEkmConfigRequest, opts ...gax.CallOption) (*kmspb.EkmConfig, error)
func (c *EkmClient) VerifyConnectivity(ctx context.Context, req *kmspb.VerifyConnectivityRequest, opts ...gax.CallOption) (*kmspb.VerifyConnectivityResponse, error)

EKM Client Documentation

5. Key Import/Export

Import externally-generated key material or export public keys for use outside GCP.

Key APIs:

// Import Job Management
func (c *KeyManagementClient) CreateImportJob(ctx context.Context, req *kmspb.CreateImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error)
func (c *KeyManagementClient) GetImportJob(ctx context.Context, req *kmspb.GetImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error)
func (c *KeyManagementClient) ListImportJobs(ctx context.Context, req *kmspb.ListImportJobsRequest, opts ...gax.CallOption) *ImportJobIterator

// Import Key Material
func (c *KeyManagementClient) ImportCryptoKeyVersion(ctx context.Context, req *kmspb.ImportCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)

Complete Key Management Client Documentation

6. Cross-Project Key Inventory

Track and monitor KMS keys and protected resources across your entire GCP organization.

Key APIs:

// KeyDashboardClient - Aggregated key views
func (c *KeyDashboardClient) ListCryptoKeys(ctx context.Context, req *inventorypb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator

// KeyTrackingClient - Track protected resources
func (c *KeyTrackingClient) GetProtectedResourcesSummary(ctx context.Context, req *inventorypb.GetProtectedResourcesSummaryRequest, opts ...gax.CallOption) (*inventorypb.ProtectedResourcesSummary, error)
func (c *KeyTrackingClient) SearchProtectedResources(ctx context.Context, req *inventorypb.SearchProtectedResourcesRequest, opts ...gax.CallOption) *ProtectedResourceIterator

Inventory Clients Documentation

7. IAM and Access Control

Manage Identity and Access Management policies for KMS resources.

Key APIs:

// IAM Policy Management (available on all clients)
func (c *KeyManagementClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error)
func (c *KeyManagementClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error)
func (c *KeyManagementClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error)

// Convenience IAM Handle
func (c *KeyManagementClient) ResourceIAM(resourcePath string) *iam.Handle

Complete Key Management Client Documentation

Core Type Reference

Resource Types

The library defines comprehensive protocol buffer types for all KMS resources:

Primary Resources:

  • KeyRing - Logical grouping of CryptoKeys
  • CryptoKey - Logical key with specific cryptographic purpose
  • CryptoKeyVersion - Individual key material instance
  • PublicKey - Public key component for asymmetric keys
  • ImportJob - Configuration for importing external key material

Autokey Resources:

  • AutokeyConfig - Folder-level Autokey configuration
  • KeyHandle - Resource triggering automatic key provisioning

EKM Resources:

  • EkmConnection - Connection to external key manager
  • EkmConfig - Project-level EKM configuration
  • Certificate - X.509 certificate for EKM authentication

Inventory Resources:

  • ProtectedResource - Resource protected by a KMS key
  • ProtectedResourcesSummary - Aggregate protection statistics

Core Types Documentation

Request and Response Types

The library provides 60+ request and response message types for all operations:

Operation Categories:

  • Key Ring operations (Create, Get, List)
  • Crypto Key operations (Create, Get, Update, List)
  • Crypto Key Version operations (Create, Get, Update, Destroy, Restore, Import, List)
  • Cryptographic operations (Encrypt, Decrypt, Sign, Verify, MAC)
  • Import Job operations (Create, Get, List)
  • EKM operations (Connection and config management)
  • Autokey operations (KeyHandle and config management)
  • Inventory operations (List keys, search protected resources)

Request/Response Types Documentation

Enumerations

The library defines comprehensive enum types for algorithms, purposes, states, and protection levels:

Key Enums:

  • CryptoKey_CryptoKeyPurpose - ENCRYPT_DECRYPT, ASYMMETRIC_SIGN, ASYMMETRIC_DECRYPT, MAC, RAW_ENCRYPT_DECRYPT, KEY_ENCAPSULATION
  • CryptoKeyVersion_CryptoKeyVersionAlgorithm - 20+ encryption, signing, and MAC algorithms
  • CryptoKeyVersion_CryptoKeyVersionState - PENDING_GENERATION, ENABLED, DISABLED, DESTROYED, etc.
  • ProtectionLevel - SOFTWARE, HSM, EXTERNAL, EXTERNAL_VPC
  • ImportJob_ImportMethod - RSA_OAEP_3072_SHA1_AES_256, RSA_OAEP_4096_SHA1_AES_256, etc.

Enums Documentation

Iterators and Pagination

All list operations return iterator types for efficient pagination:

Iterator Types:

  • CryptoKeyIterator
  • CryptoKeyVersionIterator
  • KeyRingIterator
  • ImportJobIterator
  • KeyHandleIterator
  • EkmConnectionIterator
  • LocationIterator
  • ProtectedResourceIterator

Iterators Documentation

Long-Running Operations

Some operations return long-running operation handles:

Operation Types:

  • CreateKeyHandleOperation - Tracks asynchronous KeyHandle creation

Operations Documentation

Error Handling

All client methods return errors that should be checked:

import (
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)

func handleKMSError(err error) {
    if err == nil {
        return
    }

    // Extract gRPC status
    st, ok := status.FromError(err)
    if !ok {
        // Not a gRPC error
        log.Printf("Non-gRPC error: %v", err)
        return
    }

    // Handle specific error codes
    switch st.Code() {
    case codes.NotFound:
        log.Printf("Resource not found: %v", st.Message())
    case codes.PermissionDenied:
        log.Printf("Permission denied: %v", st.Message())
    case codes.AlreadyExists:
        log.Printf("Resource already exists: %v", st.Message())
    case codes.FailedPrecondition:
        log.Printf("Failed precondition: %v", st.Message())
    default:
        log.Printf("KMS error [%v]: %v", st.Code(), st.Message())
    }
}

Common Error Codes:

  • NotFound - Resource doesn't exist
  • AlreadyExists - Resource already exists
  • PermissionDenied - Insufficient permissions
  • InvalidArgument - Invalid request parameters
  • FailedPrecondition - Operation not allowed in current state
  • ResourceExhausted - Quota exceeded

Context and Timeouts

Use context for timeout and cancellation control:

import "time"

func encryptWithTimeout(client *kms.KeyManagementClient, keyName string, data []byte) ([]byte, error) {
    // Create context with 10-second timeout
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    req := &kmspb.EncryptRequest{
        Name:      keyName,
        Plaintext: data,
    }

    resp, err := client.Encrypt(ctx, req)
    if err != nil {
        return nil, err
    }

    return resp.Ciphertext, nil
}

Resource Naming

KMS uses hierarchical resource names following GCP conventions:

Format Examples:

projects/{project}/locations/{location}/keyRings/{keyRing}
projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}
projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}/cryptoKeyVersions/{version}
projects/{project}/locations/{location}/keyRings/{keyRing}/importJobs/{importJob}
projects/{project}/locations/{location}/ekmConnections/{ekmConnection}
projects/{project}/locations/{location}/keyHandles/{keyHandle}
folders/{folder}/autokeyConfig
organizations/{organization}

Authentication and Authorization

The library uses Application Default Credentials (ADC):

// Default authentication (uses ADC)
client, err := kms.NewKeyManagementClient(ctx)

// Explicit credentials
import "google.golang.org/api/option"

client, err := kms.NewKeyManagementClient(ctx,
    option.WithCredentialsFile("/path/to/service-account-key.json"))

Required OAuth Scopes:

scopes := kms.DefaultAuthScopes()
// Returns: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloudkms"]

IAM Permissions:

  • cloudkms.keyRings.create - Create key rings
  • cloudkms.cryptoKeys.create - Create crypto keys
  • cloudkms.cryptoKeyVersions.useToEncrypt - Encrypt data
  • cloudkms.cryptoKeyVersions.useToDecrypt - Decrypt data
  • cloudkms.cryptoKeyVersions.useToSign - Sign data
  • And many more... (see IAM documentation)

Thread Safety

All clients are safe for concurrent use by multiple goroutines. However, client fields (like CallOptions) must not be modified concurrently with method calls.

// Safe: Multiple goroutines can use the same client
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(data []byte) {
        defer wg.Done()
        _, err := client.Encrypt(ctx, &kmspb.EncryptRequest{
            Name:      keyName,
            Plaintext: data,
        })
        // handle err...
    }(dataToEncrypt)
}
wg.Wait()

Client Lifecycle

Always close clients when done to release resources:

client, err := kms.NewKeyManagementClient(ctx)
if err != nil {
    return err
}
defer client.Close() // Always close the client

// Use client...

Complete Documentation

Client Documentation

Type Documentation

Additional Resources

Version Information

This documentation covers version v1.24.0 of the Cloud KMS Go client library, compatible with the Cloud KMS API v1.