Creating KeyRings and CryptoKeys

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

Create a KeyRing

A KeyRing is defined by its location and name.

Console

  1. Go to the Encryption keys page in the Cloud Platform Console.
    Go to the Encryption 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 KeyRing with name KEYRING_NAME in location LOCATION.

gcloud kms keyrings create KEYRING_NAME --location LOCATION

C#

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

      public static object CreateKeyRing(string projectId, string locationId, string keyRingId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for creating key rings.
          var parent = $"projects/{projectId}/locations/{locationId}";
          KeyRing keyRingToCreate = new KeyRing();
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CreateRequest(
              cloudKms, keyRingToCreate, parent);
          request.KeyRingId = keyRingId;
          var result = request.Execute();
          Console.Write($"Created Key Ring: {result.Name}");
          return 0;
      }

Go

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

func createKeyring(project, name string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s", project, location)

	_, err = client.Projects.Locations.KeyRings.Create(
		parent, &cloudkms.KeyRing{}).KeyRingId(name).Do()
	if err != nil {
		return err
	}
	log.Print("Created key ring.")

	return nil
}

Java

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

/**
 * 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.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the location associated with the KeyRing.
  String parent = String.format("projects/%s/locations/%s", projectId, locationId);
  // Create the KeyRing for your project.
  KeyRing keyring = kms.projects().locations().keyRings()
      .create(parent, new KeyRing())
      .setKeyRingId(keyRingId)
      .execute();

  System.out.println(keyring);
  return keyring;
}

Node.js

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

// Your Google Cloud Platform project ID
// const projectId = 'YOUR_PROJECT_ID';

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

// The name of the new key ring, e.g. "my-new-key-ring"
// const keyRingId = 'my-new-key-ring';

// Builds and authorizes a Cloud KMS client
buildAndAuthorizeService((err, cloudkms) => {
  if (err) {
    console.log(err);
    return;
  }

  const request = {
    // This will be a path parameter in the request URL
    parent: `projects/${projectId}/locations/${locationId}`,
    // This will be a path parameter in the request URL
    keyRingId: keyRingId
  };

  // Creates a new key ring
  cloudkms.projects.locations.keyRings.create(request, (err, keyRing) => {
    if (err) {
      console.log(err);
      return;
    }

    console.log(`Key ring ${keyRing.name} created.`);
  });
});

function buildAndAuthorizeService (callback) {
  // Imports the Google APIs client library
  const google = require('googleapis');

  // Acquires credentials
  google.auth.getApplicationDefault((err, authClient) => {
    if (err) {
      callback(err);
      return;
    }

    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
      authClient = authClient.createScoped([
        'https://www.googleapis.com/auth/cloud-platform'
      ]);
    }

    // Instantiates an authorized client
    const cloudkms = google.cloudkms({
      version: 'v1',
      auth: authClient
    });

    callback(null, cloudkms);
  });
}

PHP

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

/**
 * Create a KeyRing.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $locationId [optional]
 * @return null
 */
function create_keyring($projectId, $keyRingId, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the location associated with the KeyRing.
    $parent = sprintf('projects/%s/locations/%s',
        $projectId,
        $locationId
    );

    // Create the KeyRing for your project.
    $keyRing = new Google_Service_CloudKMS_KeyRing();
    $kms->projects_locations_keyRings->create(
        $parent,
        $keyRing,
        ['keyRingId' => $keyRingId]
    );

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

Python

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the location associated with the KeyRing.
    parent = 'projects/{}/locations/{}'.format(project_id, location_id)

    # Create KeyRing
    request = kms_client.projects().locations().keyRings().create(
        parent=parent, body={}, keyRingId=key_ring_id)
    response = request.execute()

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

Ruby

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

# 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/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the location associated with the key ring
resource = "projects/#{project_id}/locations/#{location_id}"

# Create a key ring for your project
key_ring = kms_client.create_project_location_key_ring(
  resource,
  Cloudkms::KeyRing.new,
  key_ring_id: key_ring_id
)

puts "Created key ring #{key_ring_id}"

Create a CryptoKey

A CryptoKey must be created in a KeyRing.

Console

  1. Go to the Encryption keys page in the Cloud Platform Console.
    Go to the Encryption keys page

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

  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 CryptoKey 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 CryptoKey.
    Your Create key page should look similar to:

    Create a key

  7. Click Create.

Command-line

Create a new CryptoKey CRYPTOKEY_NAME for the KeyRing KEYRING_NAME.

gcloud kms keys create CRYPTOKEY_NAME --location LOCATION --keyring KEYRING_NAME --purpose encryption

C#

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

      public static object CreateCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for creating the crypto key.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}";
          CryptoKey cryptoKeyToCreate = new CryptoKey();
          cryptoKeyToCreate.Purpose = "ENCRYPT_DECRYPT";
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource.CreateRequest(
              cloudKms, cryptoKeyToCreate, parent);
          request.CryptoKeyId = cryptoKeyId;
          var result = request.Execute();
          Console.Write($"Created Crypto Key: {result.Name}");
          return 0;
      }

Go

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

func createCryptoKey(project, keyRing, key string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s", project, location, keyRing)
	purpose := "ENCRYPT_DECRYPT"

	_, err = client.Projects.Locations.KeyRings.CryptoKeys.Create(
		parent, &cloudkms.CryptoKey{
			Purpose: purpose,
		}).CryptoKeyId(key).Do()
	if err != nil {
		return err
	}
	log.Print("Created crypto key.")

	return nil
}

Java

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

/**
 * 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.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the location associated with the KeyRing.
  String parent = String.format(
      "projects/%s/locations/%s/keyRings/%s", projectId, locationId, keyRingId);

  // This will allow the API access to the key for encryption and decryption.
  String purpose = "ENCRYPT_DECRYPT";
  CryptoKey cryptoKey = new CryptoKey();
  cryptoKey.setPurpose(purpose);

  // Create the CryptoKey for your project.
  CryptoKey createdKey = kms.projects().locations().keyRings().cryptoKeys()
      .create(parent, cryptoKey)
      .setCryptoKeyId(cryptoKeyId)
      .execute();

  System.out.println(createdKey);
  return createdKey;
}

Node.js

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

// Your Google Cloud Platform project ID
// const projectId = 'YOUR_PROJECT_ID';

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

// The name of the new crypto key's key ring, e.g. "my-key-ring"
// const keyRingId = 'my-key-ring';

// The name for the new crypto key, e.g. "my-key"
// const cryptoKeyId = 'my-key';

// Builds and authorizes a Cloud KMS client
buildAndAuthorizeService((err, cloudkms) => {
  if (err) {
    console.log(err);
    return;
  }

  const request = {
    // This will be a path parameter in the request URL
    parent: `projects/${projectId}/locations/${locationId}/keyRings/${keyRingId}`,
    // This will be a path parameter in the request URL
    cryptoKeyId: cryptoKeyId,

    resource: {
      // This will allow the API access to the key for encryption and decryption
      purpose: 'ENCRYPT_DECRYPT'
    }
  };

  // Creates a new key ring
  cloudkms.projects.locations.keyRings.cryptoKeys.create(request, (err, cryptoKey) => {
    if (err) {
      console.log(err);
      return;
    }

    console.log(`Key ${cryptoKey.name} created.`);
  });
});

function buildAndAuthorizeService (callback) {
  // Imports the Google APIs client library
  const google = require('googleapis');

  // Acquires credentials
  google.auth.getApplicationDefault((err, authClient) => {
    if (err) {
      callback(err);
      return;
    }

    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
      authClient = authClient.createScoped([
        'https://www.googleapis.com/auth/cloud-platform'
      ]);
    }

    // Instantiates an authorized client
    const cloudkms = google.cloudkms({
      version: 'v1',
      auth: authClient
    });

    callback(null, cloudkms);
  });
}

PHP

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

/**
 * Create a CryptoKey.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $locationId [optional]
 * @return Google_Service_CloudKMS_CryptoKey
 */
function create_cryptokey($projectId, $keyRingId, $cryptoKeyId, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // This will allow the API access to the key for encryption and decryption.
    $purpose = 'ENCRYPT_DECRYPT';

    // The resource name of the KeyRing associated with the CryptoKey.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s',
        $projectId,
        $locationId,
        $keyRingId
    );

    $cryptoKey = new Google_Service_CloudKMS_CryptoKey();
    $cryptoKey->setPurpose($purpose);

    // Create the CryptoKey for your project.
    $newKey = $kms->projects_locations_keyRings_cryptoKeys->create(
        $parent,
        $cryptoKey,
        ['cryptoKeyId' => $cryptoKeyId]
    );

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

Python

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

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

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the KeyRing associated with the CryptoKey.
    parent = 'projects/{}/locations/{}/keyRings/{}'.format(
        project_id, location_id, key_ring_id)

    # Create a CryptoKey for the given KeyRing.
    request = kms_client.projects().locations().keyRings().cryptoKeys().create(
        parent=parent, body={'purpose': 'ENCRYPT_DECRYPT'},
        cryptoKeyId=crypto_key_id)
    response = request.execute()

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

Ruby

For more on installing and creating a Cloud KMS client, refer to Cloud KMS Client Libraries.

# 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/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the key ring
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}"

# Create a crypto key in the key ring
new_crypto_key = kms_client.create_project_location_key_ring_crypto_key(
  resource,
  Cloudkms::CryptoKey.new(purpose: "ENCRYPT_DECRYPT"),
  crypto_key_id: crypto_key_id
)

puts "Created crypto key #{crypto_key_id}"

Set a CryptoKey rotation period and starting time

A CryptoKey can be created with a specified rotation period, which is the time between when new key versions are generated automatically. A CryptoKey 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 CRYPTOKEY_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 CRYPTOKEY_NAME --location LOCATION ^
    --keyring KEYRING_NAME ^
    --purpose encryption  ^
    --rotation-period ROTATION_PERIOD ^
    --next-rotation-time NEXT_ROTATION_TIME

Powershell

gcloud kms keys create CRYPTOKEY_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 CryptoKeys. For more details, see Rotating keys.

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud KMS Documentation