対称鍵の作成

Cloud Key Management Service は、鍵が鍵リングに属するといったように特定のロケーションに配置されたオブジェクト階層を使用します。

鍵リングの作成

鍵リングはロケーションと名前によって定義します。

Console

  1. GCP Console で [暗号鍵] ページに移動します。
    [暗号鍵] ページに移動

  2. [キーリングを作成] をクリックします。

  3. [キーリング名] フィールドに、鍵リングの名前を入力します。

  4. [ロケーション] プルダウンからロケーションを選択します。
    [キーリングの作成] ページは次のようになります。

    鍵を作成する

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

コマンドライン

ロケーション [LOCATION][KEYRING_NAME] という名前の新しい鍵リングを作成します。

gcloud kms keyrings create [KEYRING_NAME] --location [LOCATION]

C#

      public static void CreateKeyRing(string projectId, string locationId, string keyRingId)
      {
          KeyManagementServiceClient client = KeyManagementServiceClient.Create();

          // The location in which to create the key ring.
          LocationName locationName = new LocationName(projectId, locationId);

          // Initial values for the KeyRing (currently unused).
          KeyRing keyRing = new KeyRing();

          KeyRing result = client.CreateKeyRing(locationName, keyRingId, keyRing);
          Console.Write($"Created Key Ring: {result.Name}");
      }

Go

import (
	"context"
	"fmt"
	"io"

	cloudkms "cloud.google.com/go/kms/apiv1"
	kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

// createKeyRing creates a new ring to store keys on KMS.
func createKeyRing(w io.Writer, parent, keyRingID string) error {
	// parent := "projects/PROJECT_ID/locations/global/"
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("cloudkms.NewKeyManagementClient: %v", err)
	}
	// Build the request.
	req := &kmspb.CreateKeyRingRequest{
		Parent:    parent,
		KeyRingId: keyRingID,
	}
	// Call the API.
	result, err := client.CreateKeyRing(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateKeyRing: %v", err)
	}
	fmt.Fprintf(w, "Created key ring: %s", result)
	return nil
}

Java


/**
 * Creates a new key ring with the given id.
 */
public static KeyRing createKeyRing(String projectId, String locationId, String keyRingId)
    throws IOException {
  // Create the Cloud KMS client.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the location associated with the KeyRing.
    String parent = LocationName.format(projectId, locationId);

    // Create the KeyRing for your project.
    KeyRing keyRing = client.createKeyRing(parent, keyRingId, KeyRing.newBuilder().build());

    return keyRing;
  }
}

Node.js

async function createKeyRing(
  projectId = 'YOUR_PROJECT_ID', // Your GCP projectId
  keyRingId = 'my-new-key-ring' // Name of the new key ring
) {
  // The location of the new key ring, e.g. "global"
  const locationId = 'global';

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // Get the full path to the parent
  const parent = client.locationPath(projectId, locationId);

  // Creates a new key ring
  const [result] = await client.createKeyRing({parent, keyRingId});
  console.log(`Key ring ${result.name} created.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\KeyRing;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';

$kms = new KeyManagementServiceClient();

// The resource name of the KeyRing.
$locationName = $kms->locationName($projectId, $locationId);

$keyRing = new KeyRing();

// Create the CryptoKey for your project.
$newKeyRing = $kms->createKeyRing(
    $locationName,
    $keyRingId,
    $keyRing
);

printf('Created keyRing %s' . PHP_EOL, $keyRingId);

Python

def create_key_ring(project_id, location_id, key_ring_id):
    """Creates a KeyRing in the given location (e.g. global)."""

    from google.cloud import kms_v1

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the location associated with the KeyRing.
    parent = client.location_path(project_id, location_id)

    # The keyring object template
    keyring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    keyring = {'name': keyring_name}

    # Create a KeyRing
    response = client.create_key_ring(parent, key_ring_id, keyring)

    print('Created KeyRing {}.'.format(response.name))
    return response

Ruby

# project_id  = "Your Google Cloud project ID"
# key_ring_id = "The ID of the new key ring"
# location_id = "The location of the new key ring"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The location associated with the key ring
location = CloudKMS::KeyManagementServiceClient.location_path project_id, location_id

# KeyRing creation parameters (currently unused)
key_ring_spec = CloudKMS::KeyRing.new

# Create a key ring for your project
key_ring = client.create_key_ring location, key_ring_id, key_ring_spec

puts "Created key ring #{key_ring_id}"

鍵を作成する

鍵は鍵リング内に作成する必要があります。

Console

  1. GCP Console で [暗号鍵] ページに移動します。
    [暗号鍵] ページに移動

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

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

  4. [鍵名] フィールドに、鍵の名前を入力します。

  5. [ローテーション期間] と [開始日] に鍵のローテーション期間と開始時間を設定します。デフォルト値をそのまま使用することもできます。

  6. (省略可)鍵にラベルを追加するには、[ラベル] フィールドで [ラベルを追加] をクリックします。
    [鍵の作成] ページは次のようになります。

    鍵を作成する

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

コマンドライン

鍵リング [KEYRING_NAME] に新しい鍵 [KEY_NAME] を作成します。

gcloud kms keys create [KEY_NAME] --location [LOCATION] \
  --keyring [KEYRING_NAME] --purpose encryption

C#

      public static void CreateCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId)
      {
          KeyManagementServiceClient client = KeyManagementServiceClient.Create();

          // The KeyRing in which to create the CryptoKey.
          KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

          CryptoKey cryptoKeyToCreate = new CryptoKey();
          cryptoKeyToCreate.Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt;

          CryptoKey result = client.CreateCryptoKey(keyRingName, cryptoKeyId, cryptoKeyToCreate);
          Console.Write($"Created Crypto Key: {result.Name}");
      }

Go

import (
	"context"
	"fmt"
	"io"

	cloudkms "cloud.google.com/go/kms/apiv1"
	kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

// createCryptoKey creates a new symmetric encrypt/decrypt key on KMS.
func createCryptoKey(w io.Writer, keyRingName, keyID string) error {
	// keyRingName := "projects/PROJECT_ID/locations/global/keyRings/RING_ID"
	// keyID := "key-" + strconv.Itoa(int(time.Now().Unix()))
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("cloudkms.NewKeyManagementClient: %v", err)
	}

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      keyRingName,
		CryptoKeyId: keyID,
		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("CreateCryptoKey: %v", err)
	}
	fmt.Fprintf(w, "Created crypto key. %s", result)
	return nil
}

Java


/**
 * Creates a new crypto key with the given id.
 */
public static CryptoKey createCryptoKey(String projectId, String locationId, String keyRingId,
    String cryptoKeyId)
    throws IOException {

  // Create the Cloud KMS client.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // The resource name of the location associated with the KeyRing.
    String parent = KeyRingName.format(projectId, locationId, keyRingId);

    // This will allow the API access to the key for encryption and decryption.
    CryptoKey cryptoKey = CryptoKey.newBuilder()
        .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
        .build();

    // Create the CryptoKey for your project.
    CryptoKey createdKey = client.createCryptoKey(parent, cryptoKeyId, cryptoKey);

    return createdKey;
  }
}

Node.js

async function createCryptoKey(
  projectId = 'your-project-id', // Your GCP Project Id
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key' // Name of the crypto key
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the new crypto key's key ring, e.g. "global"
  const locationId = 'global';

  const parent = client.keyRingPath(projectId, locationId, keyRingId);

  // Creates a new key ring
  const [cryptoKey] = await client.createCryptoKey({
    parent,
    cryptoKeyId,
    cryptoKey: {
      // This will allow the API access to the key for encryption and decryption
      purpose: 'ENCRYPT_DECRYPT',
    },
  });
  console.log(`Key ${cryptoKey.name} created.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';
// $cryptoKeyId = 'The KMS key ID';

$kms = new KeyManagementServiceClient();

// The resource name of the KeyRing.
$keyRingName = $kms->keyRingName($projectId, $locationId, $keyRingId);

$cryptoKey = new CryptoKey();
// This will allow the API access to the key for encryption and decryption.
$cryptoKey->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT);

// Create the CryptoKey for your project.
$newKey = $kms->createCryptoKey(
    $keyRingName,
    $cryptoKeyId,
    $cryptoKey
);

printf('Created cryptoKey %s in keyRing %s' . PHP_EOL, $cryptoKeyId, $keyRingId);

Python

def create_crypto_key(project_id, location_id, key_ring_id, crypto_key_id):
    """Creates a CryptoKey within a KeyRing in the given location."""

    from google.cloud import kms_v1
    from google.cloud.kms_v1 import enums

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the KeyRing associated with the CryptoKey.
    parent = client.key_ring_path(project_id, location_id, key_ring_id)

    # Create the CryptoKey object template
    purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    crypto_key = {'purpose': purpose}

    # Create a CryptoKey for the given KeyRing.
    response = client.create_crypto_key(parent, crypto_key_id, crypto_key)

    print('Created CryptoKey {}.'.format(response.name))
    return response

Ruby

# project_id    = "Your Google Cloud project ID"
# location_id   = "The location of the key ring"
# key_ring_id   = "The ID of the key ring"
# crypto_key_id = "The ID of the new crypto key"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The key ring to use
key_ring =
  CloudKMS::KeyManagementServiceClient.key_ring_path project_id, location_id, key_ring_id

# CryptoKey creation parameters
crypto_key_spec = CloudKMS::CryptoKey.new
crypto_key_spec.purpose = CloudKMS::CryptoKey::CryptoKeyPurpose::ENCRYPT_DECRYPT

# Create a crypto key in the key ring
crypto_key = client.create_crypto_key key_ring, crypto_key_id, crypto_key_spec

puts "Created crypto key #{crypto_key_id}"

鍵のローテーション期間と開始時間を設定する

鍵はローテーション期間を指定して作成できます。この期間は、新しい鍵バージョンが自動的に生成される時間の間隔です。鍵は、次のローテーション時間を指定して作成することもできます。

Console

Google Cloud Platform Console を使用して鍵を作成するときに独自のローテーション期間と次のローテーション時間を指定しなかった場合、Cloud KMS は鍵のローテーション期間と次のローテーション時間を自動的に設定します。

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

  1. [ローテーション期間] プルダウンをクリックし、ローテーション期間の値を選択します。
  2. [開始日] フィールドで日付をクリックし、次のローテーションの日付を選択します。

コマンドライン

gcloud kms keys create [KEY_NAME] --location [LOCATION] \
  --keyring [KEYRING_NAME] \
  --purpose encryption \
  --rotation-period [ROTATION_PERIOD] \
  --next-rotation-time [NEXT_ROTATION_TIME]

Windows cmd.exe

gcloud kms keys create [KEY_NAME] --location [LOCATION] ^
  --keyring [KEYRING_NAME] ^
  --purpose encryption  ^
  --rotation-period [ROTATION_PERIOD] ^
  --next-rotation-time [NEXT_ROTATION_TIME]

PowerShell

gcloud kms keys create [KEY_NAME] --location [LOCATION] `
  --keyring [KEYRING_NAME] `
  --purpose encryption `
  --rotation-period [ROTATION_PERIOD] `
  --next-rotation-time [NEXT_ROTATION_TIME]

手動で新しい鍵バージョンを作成する

自動ローテーションに加えて、手動で鍵のローテーションを行うことができます。詳細については、鍵のローテーションをご覧ください。

このページは役立ちましたか?評価をお願いいたします。

フィードバックを送信...

Cloud KMS ドキュメント