Symmetrische Schlüssel erstellen

Cloud Key Management Service verwendet eine Objekthierarchie, in der beispielsweise ein Schlüssel zu einem Schlüsselbund gehört, der sich in einer bestimmten Zone befindet.

Schlüsselbund erstellen

Ein Schlüsselbund wird durch seine Zone und seinen Namen definiert.

Console

  1. Rufen Sie in der Cloud Console die Seite Cryptographic Keys (Kryptografische Schlüssel) auf.
    Zur Seite "Kryptografische Schlüssel"

  2. Klicken Sie auf KeyRing erstellen.

  3. Geben Sie im Feld Schlüsselbundname einen Namen für den Schlüsselbund ein.

  4. Wählen Sie im Drop-down Standort einen Standort aus.
    Die Seite Schlüsselbund erstellen sollte etwa so aussehen:

    Schlüssel erstellen

  5. Klicken Sie auf Erstellen.

Befehlszeile

Erstellen Sie einen neuen Schlüsselbund mit dem Namen keyring-name am Standort location.

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}"

Schlüssel erstellen

Ein Schlüssel muss in einem Schlüsselbund erstellt werden.

Console

  1. Rufen Sie in der Cloud Console die Seite Cryptographic Keys (Kryptografische Schlüssel) auf.
    Zur Seite "Kryptografische Schlüssel"

  2. Klicken Sie auf den Namen des Schlüsselbunds, für den Sie einen Schlüssel erstellen.

  3. Klicken Sie auf Schlüssel erstellen.

  4. Geben Sie im Feld Schlüsselname einen Namen für den Schlüssel ein.

  5. Akzeptieren Sie die Standardwerte für Rotation period (Rotationszeitraum) und Starting on (Ab dem) oder legen Sie einen Schlüsselrotationszeitraum und einen Beginn fest, wenn Sie andere Werte verwenden möchten. Der Standardzeitraum für die Rotation beträgt 90 Tage und das Standarddatum für die erste Rotation ist in 90 Tagen ab dem heutigen Datum.

  6. [Optional] Klicken Sie im Feld Labels auf Add label (Label hinzufügen), wenn Sie Ihren Schlüssel mit Labels versehenmöchten.
    Die Seite Create key (Schlüssel erstellen) sollte etwa so aussehen:

    Schlüssel erstellen

  7. Klicken Sie auf Erstellen.

Befehlszeile

Erstellen Sie für den Schlüsselbund keyring-name einen neuen Schlüssel namens 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}"

Schlüsselrotationszeitraum und Startzeit festlegen

Ein Schlüssel kann mit einem festgelegten Rotationszeitraum erstellt werden, was dem Zeitraum zwischen der automatischen Generierung neuer Schlüsselversionen entspricht. Ein Schlüssel kann auch mit einer angegebenen nächsten Rotationszeit erstellt werden.

Console

Wenn Sie die Google Cloud Console zum Erstellen eines Schlüssels verwenden, legt Cloud KMS den Rotationszeitraum und die nächste Rotationszeit des Schlüssels automatisch fest, wenn Sie nicht Ihren eigenen Rotationszeitraum und die nächste Rotationszeit angeben.

So können Sie beim Erstellen Ihres Schlüssels einen anderen Rotationszeitraum und einen anderen Beginn angeben, bevor Sie auf die Schaltfläche Erstellen klicken:

  1. Klicken Sie auf das Dropdown-Menü Rotationszeitraum und wählen Sie einen Wert für den Rotationszeitraum aus.
  2. Klicken Sie im Feld Ab dem auf das Datum und wählen Sie dann ein Datum für die nächste Drehung aus.

Befehlszeile

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

Neue Schlüsselversionen manuell erstellen

Neben der automatischen Rotation können Sie Schlüssel manuell rotieren. Weitere Informationen finden Sie unter Schlüssel rotieren.