キーを作成

このページでは、Cloud KMS で鍵を作成する方法について説明します。鍵には、対称または非対称鍵、非対称署名鍵、MAC 署名鍵があります。

鍵を作成するときは、その鍵を特定の Cloud KMS のロケーションのキーリングに追加します。新規のキーリングを作成するか、既存のものを使用できます。 このページでは、新しい Cloud KMS 鍵または Cloud HSM 鍵を生成し、既存のキーリングに追加します。 Cloud EKM 鍵を作成するには、外部鍵を作成するをご覧ください。Cloud KMS 鍵または Cloud HSM 鍵をインポートするには、鍵をインポートするをご覧ください。

始める前に

このページで説明するタスクの前に、次のことを行っておく必要があります。

  1. Cloud KMS リソースを含める Google Cloud プロジェクト リソース。Cloud KMS リソースには、他の Google Cloud リソースを含まない別のプロジェクトを使用することをおすすめします。
  2. 鍵を作成するキーリングの名前と場所。 他のリソースの近くにあり、選択した保護レベルをサポートしているロケーションのキーリングを選択します。 使用可能なロケーションとサポートされる保護レベルを確認するには、Cloud KMS のロケーションをご覧ください。 キーリングを作成するには、キーリングを作成するをご覧ください。
  3. 省略可: gcloud CLI を使用するには、環境を準備します。

    Google Cloud コンソールで Cloud Shell をアクティブにします。

    Cloud Shell をアクティブにする

必要なロール

鍵の作成に必要な権限を取得するには、プロジェクトまたは親リソースに対する次の IAM ロールを付与するよう管理者に依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

これらの事前定義ロールには、鍵の作成に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

鍵を作成するには、次の権限が必要です。

  • cloudkms.cryptoKeys.create
  • cloudkms.cryptoKeys.get
  • cloudkms.cryptoKeys.list
  • cloudkms.cryptoKeyVersions.create
  • cloudkms.cryptoKeyVersions.get
  • cloudkms.cryptoKeyVersions.list
  • cloudkms.keyRings.get
  • cloudkms.keyRings.list
  • cloudkms.locations.get
  • cloudkms.locations.list
  • resourcemanager.projects.get
  • 公開鍵を取得するには: cloudkms.cryptoKeyVersions.viewPublicKey
  • 単一テナント HSM 鍵を作成するには:
    • cloudkms.singleTenantHsmInstances.get
    • cloudkms.singleTenantHsmInstances.use

カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

対称暗号鍵を作成する

コンソール

  1. Google Cloud コンソールで、[鍵管理] ページに移動します。

    Key Management に移動

  2. 鍵を作成するキーリングの名前をクリックします。

  3. [鍵を作成] をクリックします。

  4. [鍵名] に鍵の名前を入力します。

  5. [保護レベル] で、[ソフトウェア]、[HSM]、[シングルテナント HSM] のいずれかを選択します。

  6. [単一テナント HSM] を選択した場合は、鍵を作成する単一テナント HSM インスタンスを選択します。

  7. [鍵マテリアル] では、[生成された鍵] を選択します。

  8. [目的] として [Symmetric encrypt/decrypt] を選択します。

  9. [ローテーション期間] と [開始日] はデフォルト値のままにします。

  10. [作成] をクリックします。

gcloud

コマンドラインで Cloud KMS を使用するには、まず Google Cloud CLI の最新バージョンをインストールまたはアップグレードします

ソフトウェアまたはマルチテナント Cloud HSM 鍵を作成するには、kms keys create コマンドを使用します。

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --protection-level "PROTECTION_LEVEL"

次のように置き換えます。

  • KEY_NAME: 鍵の名前
  • KEY_RING: 鍵を含むキーリングの名前。
  • LOCATION: キーリングの Cloud KMS のロケーション
  • PROTECTION_LEVEL: 鍵に使用する保護レベル(softwarehsm など)。software 鍵では --protection-level フラグを省略できます。

すべてのフラグと有効な値については、--help フラグを指定してコマンドを実行してください。

単一テナント Cloud HSM 鍵を作成するには、kms keys create コマンドに --crypto-key-backend フラグを追加します。

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --protection-level "hsm-single-tenant" \
    --crypto-key-backend="projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"

次のように置き換えます。

  • INSTANCE_PROJECT: シングルテナント Cloud HSM インスタンスが存在するプロジェクトの識別子。
  • INSTANCE_NAME: 鍵を作成するシングルテナント Cloud HSM インスタンスの名前。単一テナント Cloud HSM インスタンスの詳細については、単一テナント Cloud HSM インスタンスの作成と管理をご覧ください。

すべてのフラグと有効な値については、--help フラグを指定してコマンドを実行してください。

C#

このコードを実行するには、まず C# 開発環境を設定し、Cloud KMS C# SDK をインストールします。


using Google.Cloud.Kms.V1;

public class CreateKeySymmetricEncryptDecryptSample
{
    public CryptoKey CreateKeySymmetricEncryptDecrypt(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-symmetric-encryption-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Cloud KMS Go SDK をインストールします。

import (
	"context"
	"fmt"
	"io"

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

// createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
// on Cloud KMS.
func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-symmetric-encryption-key"

	// 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.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},
		},
	}

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

Java

このコードを実行するには、まず Java 開発環境を設定し、Cloud KMS Java SDK をインストールします。

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import java.io.IOException;

public class CreateKeySymmetricEncryptDecrypt {

  public void createKeySymmetricEncryptDecrypt() 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 id = "my-key";
    createKeySymmetricEncryptDecrypt(projectId, locationId, keyRingId, id);
  }

  // Create a new key that is used for symmetric encryption and decryption.
  public void createKeySymmetricEncryptDecrypt(
      String projectId, String locationId, String keyRingId, String id) 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 parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Build the symmetric key to create.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created symmetric key %s%n", createdKey.getName());
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Cloud KMS Node.js SDK をインストールします。

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

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

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

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeySymmetricEncryptDecrypt() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
      },
    },
  });

  console.log(`Created symmetric key: ${key.name}`);
  return key;
}

return createKeySymmetricEncryptDecrypt();

PHP

このコードを実行するには、まず Google Cloudでの PHP の使用について学び、Cloud KMS PHP SDK をインストールします。

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;

function create_key_symmetric_encrypt_decrypt(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-symmetric-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
        );

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Cloud KMS Python SDK をインストールします。

from google.cloud import kms


def create_key_symmetric_encrypt_decrypt(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new symmetric encryption/decryption key in Cloud KMS.

    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 create (e.g. 'my-symmetric-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

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

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    algorithm = (
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
    )
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created symmetric key: {created_key.name}")
    return created_key

Ruby

このコードを実行するには、まず Ruby 開発環境を設定し、Cloud KMS Ruby SDK をインストールします。

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

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

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

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:          :ENCRYPT_DECRYPT,
  version_template: {
    algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created symmetric key: #{created_key.name}"

API

これらの例では、HTTP クライアントとして curl を使用して API の使用例を示しています。アクセス制御の詳細については、Cloud KMS API へのアクセスをご覧ください。

ソフトウェアまたはマルチテナント Cloud HSM 鍵を作成するには、CryptoKey.create メソッドを使用します。

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'

次のように置き換えます。

  • PROJECT_ID: キーリングを含むプロジェクトの ID。
  • LOCATION: キーリングの Cloud KMS のロケーション
  • KEY_RING: 鍵を含むキーリングの名前。
  • KEY_NAME: 鍵の名前。
  • PROTECTION_LEVEL: 鍵の保護レベル(例: SOFTWAREHSM)。
  • ALGORITHM: HMAC 署名アルゴリズム(例: HMAC_SHA256)。サポートされているすべての HMAC アルゴリズムを確認するには、HMAC 署名アルゴリズムをご覧ください。
単一テナント Cloud HSM 鍵を作成するには、PROTECTION_LEVELHSM_SINGLE_TENANT に設定し、kms keys create コマンドに --crypto-key-backend フラグを追加します。

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "HSM_SINGLE_TENANT",
        "algorithm": "ALGORITHM",
        "crypto-key-backend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME" }}'

次のように置き換えます。

  • INSTANCE_PROJECT: シングルテナント Cloud HSM インスタンスが存在するプロジェクトの識別子。
  • INSTANCE_NAME: 鍵を作成するシングルテナント Cloud HSM インスタンスの名前。単一テナント Cloud HSM インスタンスの詳細については、単一テナント Cloud HSM インスタンスの作成と管理をご覧ください。

すべてのフラグと有効な値については、--help フラグを指定してコマンドを実行してください。

カスタム自動ローテーションの対称暗号鍵を作成する

鍵を作成するときに、ローテーション期間を指定できます。これは、新しい鍵バージョンが自動的に作成される時点間の時間です。次のローテーション時間を個別に指定して、次のローテーションが今から 1 ローテーション期間前または後に行われるようにすることもできます。

コンソール

Google Cloud コンソールを使用して鍵を作成すると、Cloud KMS は自動的にローテーション期間と次のローテーション時間を設定します。デフォルト値を使用するか、別の値を指定できます。

異なるローテーション期間と開始時間を指定する場合は、鍵の作成時に次の操作を行ってから、[作成] ボタンをクリックします。

  1. [鍵のローテーション期間] で、オプションを選択します。

  2. [開始日] で、最初の自動ローテーションを行う日付を選択します。[開始日] をデフォルト値のままにして、鍵を作成してから 1 回の鍵のローテーション期間が経過した後に最初の自動ローテーションを開始できます。

gcloud

コマンドラインで Cloud KMS を使用するには、まず Google Cloud CLI の最新バージョンをインストールまたはアップグレードします

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_ROTATION_TIME

以下を置き換えます。

  • KEY_NAME: 鍵の名前
  • KEY_RING: 鍵を含むキーリングの名前。
  • LOCATION: キーリングの Cloud KMS のロケーション
  • ROTATION_PERIOD: 鍵をローテーションする間隔。たとえば、30d は 30 日ごとに鍵をローテーションします。ローテーション期間は 1 日~100 年にする必要があります。詳細については、CryptoKey.rotationPeriod をご覧ください。
  • NEXT_ROTATION_TIME: 最初のローテーションが完了する時点のタイムスタンプ(例: 2023-01-01T01:02:03)。--next-rotation-time を省略すると、最初のローテーションをコマンドの実行時から 1 回のローテーション期間にスケジュール設定できます。詳細については、CryptoKey.nextRotationTime をご覧ください。

すべてのフラグと有効な値については、--help フラグを指定してコマンドを実行してください。

C#

このコードを実行するには、まず C# 開発環境を設定し、Cloud KMS C# SDK をインストールします。


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

public class CreateKeyRotationScheduleSample
{
    public CryptoKey CreateKeyRotationSchedule(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-key-with-rotation-schedule")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            },

            // Rotate the key every 30 days.
            RotationPeriod = new Duration
            {
                Seconds = 60 * 60 * 24 * 30, // 30 days
            },

            // Start the first rotation in 24 hours.
            NextRotationTime = new Timestamp
            {
                Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Cloud KMS Go SDK をインストールします。

import (
	"context"
	"fmt"
	"io"
	"time"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// createKeyRotationSchedule creates a key with a rotation schedule.
func createKeyRotationSchedule(w io.Writer, parent, id string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-key-with-rotation-schedule"

	// 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.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},

			// Rotate the key every 30 days
			RotationSchedule: &kmspb.CryptoKey_RotationPeriod{
				RotationPeriod: &durationpb.Duration{
					Seconds: int64(60 * 60 * 24 * 30), // 30 days
				},
			},

			// Start the first rotation in 24 hours
			NextRotationTime: &timestamppb.Timestamp{
				Seconds: time.Now().Add(24 * time.Hour).Unix(),
			},
		},
	}

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

Java

このコードを実行するには、まず Java 開発環境を設定し、Cloud KMS Java SDK をインストールします。

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.time.temporal.ChronoUnit;

public class CreateKeyRotationSchedule {

  public void createKeyRotationSchedule() 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 id = "my-key";
    createKeyRotationSchedule(projectId, locationId, keyRingId, id);
  }

  // Create a new key that automatically rotates on a schedule.
  public void createKeyRotationSchedule(
      String projectId, String locationId, String keyRingId, String id) 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 parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Calculate the date 24 hours from now (this is used below).
      long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

      // Build the key to create with a rotation schedule.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))

              // Rotate every 30 days.
              .setRotationPeriod(
                  Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))

              // Start the first rotation in 24 hours.
              .setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created key with rotation schedule %s%n", createdKey.getName());
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Cloud KMS Node.js SDK をインストールします。

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

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

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

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyRotationSchedule() {
  const [key]