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

docs

autokey-client.mdcore-types.mdekm-client.mdenums.mdindex.mdinventory-clients.mditerators.mdkey-management-client.mdoperations.mdrequest-response-types.md
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

key-management-client.mddocs/

KeyManagementClient - Core KMS Operations

Overview

The KeyManagementClient is the primary client for interacting with Google Cloud Key Management Service (KMS). It provides comprehensive functionality for managing cryptographic keys and performing cryptographic operations using KeyRing, CryptoKey, CryptoKeyVersion, and ImportJob resources.

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

Thread Safety: Methods (except Close) may be called concurrently by multiple goroutines. Fields must not be modified concurrently with method calls.

Client Creation

NewKeyManagementClient

func NewKeyManagementClient(ctx context.Context, opts ...option.ClientOption) (*KeyManagementClient, error)

Creates a new key management service client based on gRPC. The returned client must be Closed when done being used to clean up its underlying connections.

Example:

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

ctx := context.Background()
client, err := kms.NewKeyManagementClient(ctx)
if err != nil {
    // Handle error
}
defer client.Close()

NewKeyManagementRESTClient

func NewKeyManagementRESTClient(ctx context.Context, opts ...option.ClientOption) (*KeyManagementClient, error)

Creates a new key management service REST client. REST clients may be preferred for specific network configurations.

Client Type

type KeyManagementClient struct {
    // CallOptions contains the retry settings for each method
    CallOptions *KeyManagementCallOptions

    // Has unexported fields
}

Key Ring Management

CreateKeyRing

func (c *KeyManagementClient) CreateKeyRing(ctx context.Context, req *kmspb.CreateKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error)

Create a new KeyRing in a given Project and Location. KeyRings are containers for CryptoKeys and cannot be deleted once created.

Request:

type CreateKeyRingRequest struct {
    Parent    string   // Required: "projects/{project}/locations/{location}"
    KeyRingId string   // Required: Must be unique within location
    KeyRing   *KeyRing // Required: KeyRing with initial field values
}

Example:

req := &kmspb.CreateKeyRingRequest{
    Parent:    "projects/my-project/locations/us-central1",
    KeyRingId: "my-keyring",
    KeyRing:   &kmspb.KeyRing{},
}
keyRing, err := client.CreateKeyRing(ctx, req)

GetKeyRing

func (c *KeyManagementClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error)

Returns metadata for a given KeyRing.

Request:

type GetKeyRingRequest struct {
    Name string // Required: "projects/{project}/locations/{location}/keyRings/{keyRing}"
}

ListKeyRings

func (c *KeyManagementClient) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest, opts ...gax.CallOption) *KeyRingIterator

Lists KeyRings in a location. Returns an iterator for paginated results.

Request:

type ListKeyRingsRequest struct {
    Parent    string // Required: "projects/{project}/locations/{location}"
    PageSize  int32  // Optional: Maximum number of items to return
    PageToken string // Optional: Token from previous ListKeyRingsResponse
    Filter    string // Optional: Filter expression
    OrderBy   string // Optional: Ordering specification
}

Example:

req := &kmspb.ListKeyRingsRequest{
    Parent:   "projects/my-project/locations/us-central1",
    PageSize: 100,
}
it := client.ListKeyRings(ctx, req)
for {
    keyRing, err := it.Next()
    if err == iterator.Done {
        break
    }
    if err != nil {
        // Handle error
    }
    // Use keyRing
}

Crypto Key Management

CreateCryptoKey

func (c *KeyManagementClient) CreateCryptoKey(ctx context.Context, req *kmspb.CreateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)

Create a new CryptoKey within a KeyRing. CryptoKey.purpose and CryptoKey.version_template.algorithm are required.

Request:

type CreateCryptoKeyRequest struct {
    Parent                      string     // Required: KeyRing name
    CryptoKeyId                 string     // Required: CryptoKey ID
    CryptoKey                   *CryptoKey // Required: Initial values
    SkipInitialVersionCreation  bool       // Optional: Skip creating initial version
}

Example:

req := &kmspb.CreateCryptoKeyRequest{
    Parent:      "projects/my-project/locations/us-central1/keyRings/my-keyring",
    CryptoKeyId: "my-encryption-key",
    CryptoKey: &kmspb.CryptoKey{
        Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
        VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
            Algorithm:       kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
            ProtectionLevel: kmspb.ProtectionLevel_SOFTWARE,
        },
    },
}
cryptoKey, err := client.CreateCryptoKey(ctx, req)

GetCryptoKey

func (c *KeyManagementClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)

Returns metadata for a given CryptoKey, as well as its primary CryptoKeyVersion.

Request:

type GetCryptoKeyRequest struct {
    Name string // Required: CryptoKey resource name
}

ListCryptoKeys

func (c *KeyManagementClient) ListCryptoKeys(ctx context.Context, req *kmspb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator

Lists CryptoKeys in a KeyRing.

Request:

type ListCryptoKeysRequest struct {
    Parent      string                                // Required: KeyRing name
    PageSize    int32                                 // Optional: Max items per page
    PageToken   string                                // Optional: Pagination token
    VersionView CryptoKeyVersion_CryptoKeyVersionView // Optional: View for versions
    Filter      string                                // Optional: Filter expression
    OrderBy     string                                // Optional: Ordering specification
}

UpdateCryptoKey

func (c *KeyManagementClient) UpdateCryptoKey(ctx context.Context, req *kmspb.UpdateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)

Update a CryptoKey's metadata (labels, rotation schedule, etc.).

Request:

type UpdateCryptoKeyRequest struct {
    CryptoKey  *CryptoKey             // Required: CryptoKey with updated values
    UpdateMask *fieldmaskpb.FieldMask // Required: Fields to update
}

Example:

import "google.golang.org/protobuf/types/known/durationpb"
import "google.golang.org/protobuf/types/known/fieldmaskpb"

req := &kmspb.UpdateCryptoKeyRequest{
    CryptoKey: &kmspb.CryptoKey{
        Name:           cryptoKeyName,
        RotationPeriod: durationpb.New(30 * 24 * time.Hour), // 30 days
    },
    UpdateMask: &fieldmaskpb.FieldMask{
        Paths: []string{"rotation_period"},
    },
}
cryptoKey, err := client.UpdateCryptoKey(ctx, req)

UpdateCryptoKeyPrimaryVersion

func (c *KeyManagementClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyPrimaryVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error)

Update the version of a CryptoKey that will be used in Encrypt. Returns an error if called on a key whose purpose is not ENCRYPT_DECRYPT.

Request:

type UpdateCryptoKeyPrimaryVersionRequest struct {
    Name               string // Required: CryptoKey resource name
    CryptoKeyVersionId string // Required: ID of version to make primary
}

Crypto Key Version Management

CreateCryptoKeyVersion

func (c *KeyManagementClient) CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)

Create a new CryptoKeyVersion in a CryptoKey. The server will assign the next sequential id. If state is unset, it will be set to ENABLED.

Request:

type CreateCryptoKeyVersionRequest struct {
    Parent           string            // Required: CryptoKey name
    CryptoKeyVersion *CryptoKeyVersion // Required: Initial field values
}

Example:

req := &kmspb.CreateCryptoKeyVersionRequest{
    Parent: "projects/my-project/locations/us-central1/keyRings/my-keyring/cryptoKeys/my-key",
    CryptoKeyVersion: &kmspb.CryptoKeyVersion{
        State: kmspb.CryptoKeyVersion_ENABLED,
    },
}
version, err := client.CreateCryptoKeyVersion(ctx, req)

GetCryptoKeyVersion

func (c *KeyManagementClient) GetCryptoKeyVersion(ctx context.Context, req *kmspb.GetCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)

Returns metadata for a given CryptoKeyVersion.

Request:

type GetCryptoKeyVersionRequest struct {
    Name string // Required: CryptoKeyVersion resource name
}

ListCryptoKeyVersions

func (c *KeyManagementClient) ListCryptoKeyVersions(ctx context.Context, req *kmspb.ListCryptoKeyVersionsRequest, opts ...gax.CallOption) *CryptoKeyVersionIterator

Lists CryptoKeyVersions for a CryptoKey.

Request:

type ListCryptoKeyVersionsRequest struct {
    Parent    string                                // Required: CryptoKey name
    PageSize  int32                                 // Optional: Max items per page
    PageToken string                                // Optional: Pagination token
    View      CryptoKeyVersion_CryptoKeyVersionView // Optional: View specification
    Filter    string                                // Optional: Filter expression
    OrderBy   string                                // Optional: Ordering specification
}

UpdateCryptoKeyVersion

func (c *KeyManagementClient) UpdateCryptoKeyVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)

Update a CryptoKeyVersion's metadata. State may be changed between ENABLED and DISABLED using this method.

Request:

type UpdateCryptoKeyVersionRequest struct {
    CryptoKeyVersion *CryptoKeyVersion      // Required: Updated values
    UpdateMask       *fieldmaskpb.FieldMask // Required: Fields to update
}

DestroyCryptoKeyVersion

func (c *KeyManagementClient) DestroyCryptoKeyVersion(ctx context.Context, req *kmspb.DestroyCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)

Schedule a CryptoKeyVersion for destruction. Upon calling, CryptoKeyVersion.state will be set to DESTROY_SCHEDULED and the key material will be destroyed after the configured destroy scheduled duration.

Request:

type DestroyCryptoKeyVersionRequest struct {
    Name string // Required: CryptoKeyVersion resource name
}

RestoreCryptoKeyVersion

func (c *KeyManagementClient) RestoreCryptoKeyVersion(ctx context.Context, req *kmspb.RestoreCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)

Restore a CryptoKeyVersion in the DESTROY_SCHEDULED state. Upon restoration, state will be set to DISABLED.

Request:

type RestoreCryptoKeyVersionRequest struct {
    Name string // Required: CryptoKeyVersion resource name
}

Symmetric Encryption Operations

Encrypt

func (c *KeyManagementClient) Encrypt(ctx context.Context, req *kmspb.EncryptRequest, opts ...gax.CallOption) (*kmspb.EncryptResponse, error)

Encrypts data so that it can only be recovered by a call to Decrypt. The CryptoKey.purpose must be ENCRYPT_DECRYPT.

Request:

type EncryptRequest struct {
    Name                               string                     // Required: CryptoKey or CryptoKeyVersion name
    Plaintext                          []byte                     // Required: Data to encrypt (≤64KiB)
    AdditionalAuthenticatedData        []byte                     // Optional: AAD for AEAD ciphers
    PlaintextCrc32C                    *wrapperspb.Int64Value     // Optional: CRC32C checksum of plaintext
    AdditionalAuthenticatedDataCrc32C  *wrapperspb.Int64Value     // Optional: CRC32C checksum of AAD
}

Response:

type EncryptResponse struct {
    Name                                       string                 // CryptoKeyVersion used
    Ciphertext                                 []byte                 // Encrypted data
    CiphertextCrc32C                           *wrapperspb.Int64Value // Integrity verification
    VerifiedPlaintextCrc32C                    bool                   // Whether plaintext CRC32C was verified
    VerifiedAdditionalAuthenticatedDataCrc32C  bool                   // Whether AAD CRC32C was verified
    ProtectionLevel                            ProtectionLevel        // Protection level used
}

Example:

req := &kmspb.EncryptRequest{
    Name:      "projects/my-project/locations/us-central1/keyRings/my-keyring/cryptoKeys/my-key",
    Plaintext: []byte("sensitive data"),
}
resp, err := client.Encrypt(ctx, req)
if err != nil {
    // Handle error
}
ciphertext := resp.Ciphertext

Decrypt

func (c *KeyManagementClient) Decrypt(ctx context.Context, req *kmspb.DecryptRequest, opts ...gax.CallOption) (*kmspb.DecryptResponse, error)

Decrypts data that was protected by Encrypt. The CryptoKey.purpose must be ENCRYPT_DECRYPT.

Request:

type DecryptRequest struct {
    Name                               string                     // Required: CryptoKey name
    Ciphertext                         []byte                     // Required: Encrypted data from Encrypt
    AdditionalAuthenticatedData        []byte                     // Optional: AAD (must match Encrypt)
    CiphertextCrc32C                   *wrapperspb.Int64Value     // Optional: CRC32C checksum
    AdditionalAuthenticatedDataCrc32C  *wrapperspb.Int64Value     // Optional: CRC32C checksum
}

Response:

type DecryptResponse struct {
    Plaintext        []byte                 // Decrypted data
    PlaintextCrc32C  *wrapperspb.Int64Value // Integrity verification
    UsedPrimary      bool                   // Whether primary version was used
    ProtectionLevel  ProtectionLevel        // Protection level used
}

Raw Encryption Operations

RawEncrypt

func (c *KeyManagementClient) RawEncrypt(ctx context.Context, req *kmspb.RawEncryptRequest, opts ...gax.CallOption) (*kmspb.RawEncryptResponse, error)

Encrypts data using portable cryptographic primitives. Most users should choose Encrypt and Decrypt rather than their raw counterparts. The CryptoKey.purpose must be RAW_ENCRYPT_DECRYPT.

Request:

type RawEncryptRequest struct {
    Name                               string                     // Required: CryptoKeyVersion name
    Plaintext                          []byte                     // Required: ≤64KiB for AES-GCM, ≤8KiB for AES-CBC/CTR
    AdditionalAuthenticatedData        []byte                     // Optional: AAD (AES-GCM only)
    PlaintextCrc32C                    *wrapperspb.Int64Value     // Optional: CRC32C checksum
    AdditionalAuthenticatedDataCrc32C  *wrapperspb.Int64Value     // Optional: CRC32C checksum
    InitializationVector               []byte                     // Optional: IV (AES-CBC/CTR, exactly 16 bytes)
    InitializationVectorCrc32C         *wrapperspb.Int64Value     // Optional: CRC32C checksum
}

Response:

type RawEncryptResponse struct {
    Ciphertext                                 []byte                 // Encrypted data
    InitializationVector                       []byte                 // IV used
    TagLength                                  int32                  // AEAD tag length
    CiphertextCrc32C                           *wrapperspb.Int64Value // Integrity verification
    InitializationVectorCrc32C                 *wrapperspb.Int64Value // Integrity verification
    VerifiedPlaintextCrc32C                    bool                   // Whether verified
    VerifiedAdditionalAuthenticatedDataCrc32C  bool                   // Whether verified
    VerifiedInitializationVectorCrc32C         bool                   // Whether verified
    Name                                       string                 // CryptoKeyVersion used
    ProtectionLevel                            ProtectionLevel        // Protection level
}

RawDecrypt

func (c *KeyManagementClient) RawDecrypt(ctx context.Context, req *kmspb.RawDecryptRequest, opts ...gax.CallOption) (*kmspb.RawDecryptResponse, error)

Decrypts data that was originally encrypted using a raw cryptographic mechanism. The CryptoKey.purpose must be RAW_ENCRYPT_DECRYPT.

Request:

type RawDecryptRequest struct {
    Name                               string                     // Required: CryptoKeyVersion name
    Ciphertext                         []byte                     // Required: Encrypted data from RawEncrypt
    AdditionalAuthenticatedData        []byte                     // Optional: AAD (AES-GCM only)
    InitializationVector               []byte                     // Required: IV (AES-CBC/CTR)
    TagLength                          int32                      // Required: Auth tag length (AES-GCM)
    CiphertextCrc32C                   *wrapperspb.Int64Value     // Optional: CRC32C checksum
    AdditionalAuthenticatedDataCrc32C  *wrapperspb.Int64Value     // Optional: CRC32C checksum
    InitializationVectorCrc32C         *wrapperspb.Int64Value     // Optional: CRC32C checksum
}

Response:

type RawDecryptResponse struct {
    Plaintext                                  []byte                 // Decrypted data
    PlaintextCrc32C                            *wrapperspb.Int64Value // Integrity verification
    ProtectionLevel                            ProtectionLevel        // Protection level
    VerifiedCiphertextCrc32C                   bool                   // Whether verified
    VerifiedAdditionalAuthenticatedDataCrc32C  bool                   // Whether verified
    VerifiedInitializationVectorCrc32C         bool                   // Whether verified
}

Asymmetric Signing Operations

AsymmetricSign

func (c *KeyManagementClient) AsymmetricSign(ctx context.Context, req *kmspb.AsymmetricSignRequest, opts ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error)

Signs data using a CryptoKeyVersion with CryptoKey.purpose ASYMMETRIC_SIGN, producing a signature that can be verified with the public key retrieved from GetPublicKey.

Request:

type AsymmetricSignRequest struct {
    Name        string                     // Required: CryptoKeyVersion name
    Digest      *Digest                    // Optional: Digest of data to sign
    DigestCrc32C *wrapperspb.Int64Value    // Optional: CRC32C checksum of digest
    Data        []byte                     // Optional: Raw data to sign (Raw PKCS#1 only)
    DataCrc32C  *wrapperspb.Int64Value     // Optional: CRC32C checksum of data
}

Digest Type:

type Digest struct {
    Sha256 []byte // SHA-256 hash (exactly 32 bytes)
    Sha384 []byte // SHA-384 hash (exactly 48 bytes)
    Sha512 []byte // SHA-512 hash (exactly 64 bytes)
}

Response:

type AsymmetricSignResponse struct {
    Signature           []byte                 // Created signature
    SignatureCrc32C     *wrapperspb.Int64Value // Integrity verification
    VerifiedDigestCrc32C bool                  // Whether digest CRC32C was verified
    VerifiedDataCrc32C  bool                   // Whether data CRC32C was verified
    Name                string                 // CryptoKeyVersion used
    ProtectionLevel     ProtectionLevel        // Protection level
}

Example:

import "crypto/sha256"

data := []byte("message to sign")
hash := sha256.Sum256(data)

req := &kmspb.AsymmetricSignRequest{
    Name: versionName,
    Digest: &kmspb.Digest{
        Sha256: hash[:],
    },
}
resp, err := client.AsymmetricSign(ctx, req)
if err != nil {
    // Handle error
}
signature := resp.Signature

GetPublicKey

func (c *KeyManagementClient) GetPublicKey(ctx context.Context, req *kmspb.GetPublicKeyRequest, opts ...gax.CallOption) (*kmspb.PublicKey, error)

Returns the public key for the given CryptoKeyVersion. The CryptoKey.purpose must be ASYMMETRIC_SIGN, ASYMMETRIC_DECRYPT, or KEY_ENCAPSULATION.

Request:

type GetPublicKeyRequest struct {
    Name string // Required: CryptoKeyVersion name
}

Response:

type PublicKey struct {
    Pem               string                                      // PEM-encoded public key
    Algorithm         CryptoKeyVersion_CryptoKeyVersionAlgorithm  // Algorithm
    PemCrc32C         *wrapperspb.Int64Value                      // Integrity verification
    Name              string                                      // CryptoKeyVersion name
    ProtectionLevel   ProtectionLevel                             // Protection level
    Format            PublicKey_PublicKeyFormat                   // Public key format
    EncodedPublicKey  []byte                                      // Public key bytes in specified format
}

Asymmetric Decryption Operations

AsymmetricDecrypt

func (c *KeyManagementClient) AsymmetricDecrypt(ctx context.Context, req *kmspb.AsymmetricDecryptRequest, opts ...gax.CallOption) (*kmspb.AsymmetricDecryptResponse, error)

Decrypts data that was encrypted with a public key retrieved from GetPublicKey corresponding to a CryptoKeyVersion with CryptoKey.purpose ASYMMETRIC_DECRYPT.

Request:

type AsymmetricDecryptRequest struct {
    Name             string                     // Required: CryptoKeyVersion name
    Ciphertext       []byte                     // Required: Data encrypted with public key
    CiphertextCrc32C *wrapperspb.Int64Value     // Optional: CRC32C checksum
}

Response:

type AsymmetricDecryptResponse struct {
    Plaintext                []byte                 // Decrypted data
    PlaintextCrc32C          *wrapperspb.Int64Value // Integrity verification
    VerifiedCiphertextCrc32C bool                   // Whether ciphertext CRC32C was verified
    ProtectionLevel          ProtectionLevel        // Protection level
}

MAC Operations

MacSign

func (c *KeyManagementClient) MacSign(ctx context.Context, req *kmspb.MacSignRequest, opts ...gax.CallOption) (*kmspb.MacSignResponse, error)

Signs data using a CryptoKeyVersion with CryptoKey.purpose MAC, producing a tag that can be verified by another source with the same key.

Request:

type MacSignRequest struct {
    Name        string                     // Required: CryptoKeyVersion name
    Data        []byte                     // Required: Data to sign (≤64KiB)
    DataCrc32C  *wrapperspb.Int64Value     // Optional: CRC32C checksum
}

Response:

type MacSignResponse struct {
    Name                string                 // CryptoKeyVersion used
    Mac                 []byte                 // Generated signature
    MacCrc32C           *wrapperspb.Int64Value // Integrity verification
    VerifiedDataCrc32C  bool                   // Whether data CRC32C was verified
    ProtectionLevel     ProtectionLevel        // Protection level
}

MacVerify

func (c *KeyManagementClient) MacVerify(ctx context.Context, req *kmspb.MacVerifyRequest, opts ...gax.CallOption) (*kmspb.MacVerifyResponse, error)

Verifies MAC tag using a CryptoKeyVersion with CryptoKey.purpose MAC, and returns a response that indicates whether or not the verification was successful.

Request:

type MacVerifyRequest struct {
    Name        string                     // Required: CryptoKeyVersion name
    Data        []byte                     // Required: Data used to generate MAC
    DataCrc32C  *wrapperspb.Int64Value     // Optional: CRC32C checksum
    Mac         []byte                     // Required: Signature to verify
    MacCrc32C   *wrapperspb.Int64Value     // Optional: CRC32C checksum
}

Response:

type MacVerifyResponse struct {
    Name                    string          // CryptoKeyVersion used
    Success                 bool            // Whether MAC is valid
    VerifiedDataCrc32C      bool            // Whether data CRC32C was verified
    VerifiedMacCrc32C       bool            // Whether MAC CRC32C was verified
    VerifiedSuccessIntegrity bool           // Whether success integrity was verified
    ProtectionLevel         ProtectionLevel // Protection level
}

Key Encapsulation Operations

Decapsulate

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

Decapsulates data that was encapsulated with a public key retrieved from GetPublicKey corresponding to a CryptoKeyVersion with CryptoKey.purpose KEY_ENCAPSULATION.

Request:

type DecapsulateRequest struct {
    Name                 string                     // Required: CryptoKeyVersion name
    CiphertextDataCrc32C *wrapperspb.Int64Value     // Optional: CRC32C checksum
}

Response:

type DecapsulateResponse struct {
    Plaintext                []byte                 // Decrypted data
    PlaintextCrc32C          *wrapperspb.Int64Value // Integrity verification
    VerifiedCiphertextCrc32C bool                   // Whether ciphertext CRC32C was verified
    ProtectionLevel          ProtectionLevel        // Protection level
}

Random Number Generation

GenerateRandomBytes

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

Generate random bytes using the Cloud KMS randomness source in the provided location.

Request:

type GenerateRandomBytesRequest struct {
    Location        string          // Required: Project or organization location
    LengthBytes     int32           // Required: Number of bytes (≥1, ≤1024)
    ProtectionLevel ProtectionLevel // Required: Protection level to use
}

Response:

type GenerateRandomBytesResponse struct {
    Data        []byte                 // Generated random bytes
    DataCrc32C  *wrapperspb.Int64Value // Integrity verification
}

Example:

req := &kmspb.GenerateRandomBytesRequest{
    Location:        "projects/my-project/locations/us-central1",
    LengthBytes:     32,
    ProtectionLevel: kmspb.ProtectionLevel_HSM,
}
resp, err := client.GenerateRandomBytes(ctx, req)
if err != nil {
    // Handle error
}
randomBytes := resp.Data

Import Job Management

CreateImportJob

func (c *KeyManagementClient) CreateImportJob(ctx context.Context, req *kmspb.CreateImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error)

Create a new ImportJob within a KeyRing. ImportJob.import_method is required.

Request:

type CreateImportJobRequest struct {
    Parent      string      // Required: KeyRing name
    ImportJobId string      // Required: ImportJob ID
    ImportJob   *ImportJob  // Required: Initial field values
}

GetImportJob

func (c *KeyManagementClient) GetImportJob(ctx context.Context, req *kmspb.GetImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error)

Returns metadata for a given ImportJob.

Request:

type GetImportJobRequest struct {
    Name string // Required: ImportJob resource name
}

ListImportJobs

func (c *KeyManagementClient) ListImportJobs(ctx context.Context, req *kmspb.ListImportJobsRequest, opts ...gax.CallOption) *ImportJobIterator

Lists ImportJobs in a KeyRing.

Request:

type ListImportJobsRequest struct {
    Parent    string // Required: KeyRing name
    PageSize  int32  // Optional: Max items per page
    PageToken string // Optional: Pagination token
    Filter    string // Optional: Filter expression
    OrderBy   string // Optional: Ordering specification
}

ImportCryptoKeyVersion

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

Import wrapped key material into a CryptoKeyVersion.

Request:

type ImportCryptoKeyVersionRequest struct {
    Parent            string                                      // Required: CryptoKey name
    CryptoKeyVersion  string                                      // Optional: Version name (for reimport)
    Algorithm         CryptoKeyVersion_CryptoKeyVersionAlgorithm  // Required: Algorithm of key being imported
    ImportJob         string                                      // Required: ImportJob name
    WrappedKey        []byte                                      // Optional: Wrapped key material
    RsaAesWrappedKey  []byte                                      // Optional: RSA/AES wrapped key material
}

IAM Operations

GetIamPolicy

func (c *KeyManagementClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error)

Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.

SetIamPolicy

func (c *KeyManagementClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error)

Sets the access control policy on the specified resource. Replaces any existing policy.

TestIamPermissions

func (c *KeyManagementClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error)

Returns permissions that a caller has on the specified resource.

ResourceIAM

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

Returns a handle to inspect and change permissions of the resource indicated by the given resource path. The resource path can be a KeyRing, CryptoKey, or ImportJob.

Example:

import "cloud.google.com/go/iam"

handle := client.ResourceIAM("projects/my-project/locations/us-central1/keyRings/my-keyring")
policy, err := handle.Policy(ctx)
if err != nil {
    // Handle error
}
// Modify policy...
err = handle.SetPolicy(ctx, policy)

KeyRingIAM (Deprecated)

func (c *KeyManagementClient) KeyRingIAM(keyRing *kmspb.KeyRing) *iam.Handle

Deprecated: Use ResourceIAM instead.

CryptoKeyIAM (Deprecated)

func (c *KeyManagementClient) CryptoKeyIAM(cryptoKey *kmspb.CryptoKey) *iam.Handle

Deprecated: Use ResourceIAM instead.

Location Operations

GetLocation

func (c *KeyManagementClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error)

Gets information about a location.

ListLocations

func (c *KeyManagementClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator

Lists information about the supported locations for this service.

Utility Methods

Close

func (c *KeyManagementClient) Close() error

Closes the connection to the API service. The user should invoke this when the client is no longer required.

Connection (Deprecated)

func (c *KeyManagementClient) Connection() *grpc.ClientConn

Returns a connection to the API service. Deprecated: Connections are now pooled so this method does not always return the same resource.

GetOperation

func (c *KeyManagementClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error)

Utility method from google.longrunning.Operations.

CallOptions Type

type KeyManagementCallOptions struct {
    ListKeyRings                  []gax.CallOption
    ListCryptoKeys                []gax.CallOption
    ListCryptoKeyVersions         []gax.CallOption
    ListImportJobs                []gax.CallOption
    GetKeyRing                    []gax.CallOption
    GetCryptoKey                  []gax.CallOption
    GetCryptoKeyVersion           []gax.CallOption
    GetPublicKey                  []gax.CallOption
    GetImportJob                  []gax.CallOption
    CreateKeyRing                 []gax.CallOption
    CreateCryptoKey               []gax.CallOption
    CreateCryptoKeyVersion        []gax.CallOption
    ImportCryptoKeyVersion        []gax.CallOption
    CreateImportJob               []gax.CallOption
    UpdateCryptoKey               []gax.CallOption
    UpdateCryptoKeyVersion        []gax.CallOption
    UpdateCryptoKeyPrimaryVersion []gax.CallOption
    DestroyCryptoKeyVersion       []gax.CallOption
    RestoreCryptoKeyVersion       []gax.CallOption
    Encrypt                       []gax.CallOption
    Decrypt                       []gax.CallOption
    RawEncrypt                    []gax.CallOption
    RawDecrypt                    []gax.CallOption
    AsymmetricSign                []gax.CallOption
    AsymmetricDecrypt             []gax.CallOption
    MacSign                       []gax.CallOption
    MacVerify                     []gax.CallOption
    Decapsulate                   []gax.CallOption
    GenerateRandomBytes           []gax.CallOption
    GetLocation                   []gax.CallOption
    ListLocations                 []gax.CallOption
    GetIamPolicy                  []gax.CallOption
    SetIamPolicy                  []gax.CallOption
    TestIamPermissions            []gax.CallOption
    GetOperation                  []gax.CallOption
}

Contains the retry settings for each method of KeyManagementClient. Can be modified to customize retry behavior.

Complete Usage Example

package main

import (
    "context"
    "crypto/sha256"
    "fmt"
    "log"

    kms "cloud.google.com/go/kms/apiv1"
    "cloud.google.com/go/kms/apiv1/kmspb"
    "google.golang.org/api/iterator"
)

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

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

    projectID := "my-project"
    locationID := "us-central1"
    keyRingID := "my-keyring"
    cryptoKeyID := "my-key"

    // Create KeyRing
    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 {
        log.Printf("KeyRing may already exist: %v", err)
    } else {
        fmt.Printf("Created KeyRing: %s\n", keyRing.Name)
    }

    // Create CryptoKey for encryption
    cryptoKey, 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 {
        log.Fatalf("Failed to create CryptoKey: %v", err)
    }
    fmt.Printf("Created CryptoKey: %s\n", cryptoKey.Name)

    // Encrypt data
    plaintext := []byte("Hello, KMS!")
    encResp, err := client.Encrypt(ctx, &kmspb.EncryptRequest{
        Name:      cryptoKey.Name,
        Plaintext: plaintext,
    })
    if err != nil {
        log.Fatalf("Encryption failed: %v", err)
    }
    fmt.Printf("Encrypted %d bytes\n", len(encResp.Ciphertext))

    // Decrypt data
    decResp, err := client.Decrypt(ctx, &kmspb.DecryptRequest{
        Name:       cryptoKey.Name,
        Ciphertext: encResp.Ciphertext,
    })
    if err != nil {
        log.Fatalf("Decryption failed: %v", err)
    }
    fmt.Printf("Decrypted: %s\n", string(decResp.Plaintext))

    // List all CryptoKeys
    it := client.ListCryptoKeys(ctx, &kmspb.ListCryptoKeysRequest{
        Parent: keyRing.Name,
    })
    fmt.Println("CryptoKeys:")
    for {
        key, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            log.Fatalf("Failed to list: %v", err)
        }
        fmt.Printf("  - %s\n", key.Name)
    }
}

See Also

  • Core Types Documentation
  • Enumerations
  • Request/Response Types
  • Iterators