Creating KeyRings and CryptoKeys

Cloud KMS 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.

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 location, string keyRing)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for creating key rings.
          var parent = $"projects/{projectId}/locations/{location}";
          KeyRing keyRingToCreate = new KeyRing();
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CreateRequest(
              cloudKms, keyRingToCreate, parent);
          request.KeyRingId = keyRing;
          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 keyring.")

	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 ringId) throws IOException {
  String location = "global";
  // 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, location);
  // Create the KeyRing for your project.
  KeyRing keyring = kms.projects().locations().keyRings()
      .create(parent, new KeyRing())
      .setKeyRingId(ringId)
      .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 location = 'global';

// The name of the new key ring, e.g. "my-new-key-ring"
// const keyRingName = '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/${location}`,
    // This will be a path parameter in the request URL
    keyRingId: keyRingName
  };

  // 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 $ring
 * @param string $location [optional]
 * @return null
 */
function create_keyring($projectId, $ring, $location = '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,
        $location
    );

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

    printf('Created keyring %s' . PHP_EOL, $ring);
}

Python

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

def create_keyring(project_id, location, keyring):
    """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)

    # Create KeyRing
    request = kms_client.projects().locations().keyRings().create(
        parent=parent, body={}, keyRingId=keyring)
    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    = "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}"

# 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.

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 location, string keyRing, string cryptoKey)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for creating the crypto key.
          var parent = $"projects/{projectId}/locations/{location}/keyRings/{keyRing}";
          CryptoKey cryptoKeyToCreate = new CryptoKey();
          cryptoKeyToCreate.Purpose = "ENCRYPT_DECRYPT";
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource.CreateRequest(
              cloudKms, cryptoKeyToCreate, parent);
          request.CryptoKeyId = cryptoKey;
          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, ring, 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/keyRings/%s", project, location, ring)
	purpose := "ENCRYPT_DECRYPT"

	_, err = client.Projects.Locations.KeyRings.CryptoKeys.Create(
		parent, &cloudkms.CryptoKey{
			Purpose: purpose,
		}).CryptoKeyId(name).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 ringId, String keyId)
    throws IOException {
  String location = "global";
  // 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, location, ringId);

  // 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(keyId)
      .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 location = 'global';

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

// The name for the new crypto key, e.g. "my-key"
// const keyName = '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/${location}/keyRings/${keyRingName}`,
    // This will be a path parameter in the request URL
    cryptoKeyId: keyName,

    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 $ring
 * @param string $key
 * @param string $location [optional]
 * @return Google_Service_CloudKMS_CryptoKey
 */
function create_cryptokey($projectId, $ring, $key, $location = '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,
        $location,
        $ring
    );

    $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' => $key]
    );

    printf('Created key %s in keyring %s' . PHP_EOL, $key, $ring);
}

Python

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

def create_cryptokey(project_id, location, keyring, cryptokey):
    """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, keyring)

    # Create a CryptoKey for the given KeyRing.
    request = kms_client.projects().locations().keyRings().cryptoKeys().create(
        parent=parent, body={'purpose': 'ENCRYPT_DECRYPT'},
        cryptoKeyId=cryptokey)
    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"
# key_ring_id = "The ID of the new key ring"
# crypto_key  = "Name of the crypto key"
# location    = "The location of the 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}/" +
           "keyRings/#{key_ring_id}"

# Create a crypto key for your project 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
)

puts "Created crypto key #{crypto_key}"

A CryptoKey can also be created with a specified rotation period.

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

Send feedback about...

Cloud KMS Documentation