Mengaktifkan versi kunci

Aktifkan versi kunci.

Mempelajari lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Cloud KMS, lihat library klien Cloud KMS.

Untuk melakukan autentikasi ke Cloud KMS, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class EnableKeyVersionSample
{
    public CryptoKeyVersion EnableKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion
        {
            CryptoKeyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId),
            State = CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled,
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "state" },
        };

        // Call the API.
        CryptoKeyVersion result = client.UpdateCryptoKeyVersion(keyVersion, fieldMask);

        // Return the result.
        return result;
    }
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Cloud KMS, lihat library klien Cloud KMS.

Untuk melakukan autentikasi ke Cloud KMS, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	fieldmask "google.golang.org/genproto/protobuf/field_mask"
)

// enableKeyVersion disables the specified key version on Cloud KMS.
func enableKeyVersion(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.UpdateCryptoKeyVersionRequest{
		CryptoKeyVersion: &kmspb.CryptoKeyVersion{
			Name:  name,
			State: kmspb.CryptoKeyVersion_ENABLED,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"state"},
		},
	}

	// Call the API.
	result, err := client.UpdateCryptoKeyVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key version: %w", err)
	}
	fmt.Fprintf(w, "Enabled key version: %s\n", result)
	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Cloud KMS, lihat library klien Cloud KMS.

Untuk melakukan autentikasi ke Cloud KMS, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState;
import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class EnableKeyVersion {

  public void enableKeyVersion() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String keyVersionId = "123";
    enableKeyVersion(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Enable a disabled key version to be used again.
  public void enableKeyVersion(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Build the updated key version, setting it to enabled.
      CryptoKeyVersion keyVersion =
          CryptoKeyVersion.newBuilder()
              .setName(keyVersionName.toString())
              .setState(CryptoKeyVersionState.ENABLED)
              .build();

      // Create a field mask of updated values.
      FieldMask fieldMask = FieldMaskUtil.fromString("state");

      // Enable the key version.
      CryptoKeyVersion response = client.updateCryptoKeyVersion(keyVersion, fieldMask);
      System.out.printf("Enabled key version: %s%n", response.getName());
    }
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Cloud KMS, lihat library klien Cloud KMS.

Untuk melakukan autentikasi ke Cloud KMS, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const versionId = '123';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function enableKeyVersion() {
  const [version] = await client.updateCryptoKeyVersion({
    cryptoKeyVersion: {
      name: versionName,
      state: 'ENABLED',
    },
    updateMask: {
      paths: ['state'],
    },
  });

  console.log(`Enabled key version: ${version.name}`);
  return version;
}

return enableKeyVersion();

PHP

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Cloud KMS, lihat library klien Cloud KMS.

Untuk melakukan autentikasi ke Cloud KMS, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKeyVersion;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionState;
use Google\Cloud\Kms\V1\UpdateCryptoKeyVersionRequest;
use Google\Protobuf\FieldMask;

function enable_key_version(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key',
    string $versionId = '123'
): CryptoKeyVersion {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key version name.
    $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Create the updated version.
    $keyVersion = (new CryptoKeyVersion())
        ->setName($keyVersionName)
        ->setState(CryptoKeyVersionState::ENABLED);

    // Create the field mask.
    $updateMask = (new FieldMask())
        ->setPaths(['state']);

    // Call the API.
    $updateCryptoKeyVersionRequest = (new UpdateCryptoKeyVersionRequest())
        ->setCryptoKeyVersion($keyVersion)
        ->setUpdateMask($updateMask);
    $enabledVersion = $client->updateCryptoKeyVersion($updateCryptoKeyVersionRequest);
    printf('Enabled key version: %s' . PHP_EOL, $enabledVersion->getName());

    return $enabledVersion;
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Cloud KMS, lihat library klien Cloud KMS.

Untuk melakukan autentikasi ke Cloud KMS, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import kms


def enable_key_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.CryptoKeyVersion:
    """
    Enable a key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        version_id (string): ID of the key version to enable (e.g. '1').

    Returns:
        CryptoKeyVersion: The version.

    """
    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    key_version = {
        "name": key_version_name,
        "state": kms.CryptoKeyVersion.CryptoKeyVersionState.ENABLED,
    }

    # Build the update mask.
    update_mask = {"paths": ["state"]}

    # Call the API.
    enabled_version = client.update_crypto_key_version(
        request={"crypto_key_version": key_version, "update_mask": update_mask}
    )
    print(f"Enabled key version: {enabled_version.name}")
    return enabled_version

Ruby

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Cloud KMS, lihat library klien Cloud KMS.

Untuk melakukan autentikasi ke Cloud KMS, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"
# version_id  = "123"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the key version name.
key_version_name = client.crypto_key_version_path project:            project_id,
                                                  location:           location_id,
                                                  key_ring:           key_ring_id,
                                                  crypto_key:         key_id,
                                                  crypto_key_version: version_id

# Create the updated version.
version = {
  name:  key_version_name,
  state: :ENABLED
}

# Create the field mask.
update_mask = { paths: ["state"] }

# Call the API.
enabled_version = client.update_crypto_key_version crypto_key_version: version, update_mask: update_mask
puts "Enabled key version: #{enabled_version.name}"

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.