Creating symmetric keys

Cloud Key Management Service uses an object hierarchy, such that a key belongs to a key ring, which resides in a particular location.

Create a key ring

A key ring is defined by its location and name.

Console

  1. Go to the Cryptographic Keys page in the GCP Console.
    Go to the Cryptographic Keys page

  2. Click Create key ring.

  3. In the Key ring name field, enter the name for your key ring.

  4. From the Location dropdown, select a location.
    Your Create key ring page should look similar to:

    Create a key

  5. Click Create.

Command-line

Create a new key ring with name [KEYRING_NAME] in location [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

// createKeyRing creates a new ring to store keys on KMS.
// example parentName: "projects/PROJECT_ID/locations/global/"
func createKeyRing(w io.Writer, parentName, keyRingID string) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return err
	}
	// Build the request.
	req := &kmspb.CreateKeyRingRequest{
		Parent:    parentName,
		KeyRingId: keyRingID,
	}
	// Call the API.
	result, err := client.CreateKeyRing(ctx, req)
	if err != nil {
		return 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}"

Create a key

A key must be created in a key ring.

Console

  1. Go to the Cryptographic Keys page in the GCP Console.
    Go to the Cryptographic Keys page

  2. Click the name of the key ring for which you will create a key.

  3. Click Create key.

  4. In the Key name field, enter the name for your key.

  5. Accept the default values for Rotation period and Starting on, or set a key rotation period and starting time if you want to use different values.

  6. [Optional] In the Labels field, click Add label if you want to add labels to your key.
    Your Create key page should look similar to:

    Create a key

  7. Click Create.

Command-line

Create a new key [KEY_NAME] for the key ring [KEYRING_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

// createCryptoKey creates a new symmetric encrypt/decrypt key on KMS.
// example keyRingName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID"
func createCryptoKey(w io.Writer, keyRingName, keyID string) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return 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 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}"

Set a key rotation period and starting time

A key can be created with a specified rotation period, which is the time between when new key versions are generated automatically. A key can also be created with a specified next rotation time.

Console

When you use the Google Cloud Platform Console to create a key, if you don't specify your own rotation period and next rotation time, Cloud KMS will set the key's rotation period and next rotation time automatically.

To specify a different rotation period and starting time, when you are creating your key, but before you click the Create button:

  1. Click the Rotation period dropdown and then select a value for the rotation period.
  2. Click the date in the Starting on field and then select a date for the next rotation.

Command-line

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]

Manually create new key versions

In addition to automatic rotation, you can manually rotate keys. For more details, see Rotating keys.

Оцените, насколько информация на этой странице была вам полезна:

Оставить отзыв о...

Текущей странице