Create a new key version

Create a new version of the given key.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for Cloud KMS, see Cloud KMS client libraries.

To authenticate to Cloud KMS, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Cloud.Kms.V1;

public class CreateKeyVersionSample
{
    public CryptoKeyVersion CreateKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion { };

        // Call the API.
        CryptoKeyVersion result = client.CreateCryptoKeyVersion(keyName, keyVersion);

        // Return the result.
        return result;
    }
}

Go

To learn how to install and use the client library for Cloud KMS, see Cloud KMS client libraries.

To authenticate to Cloud KMS, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// createKeyVersion creates a new key version for the given key.
func createKeyVersion(w io.Writer, parent string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyVersionRequest{
		Parent: parent,
	}

	// Call the API.
	result, err := client.CreateCryptoKeyVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key version: %w", err)
	}
	fmt.Fprintf(w, "Created key version: %s\n", result.Name)
	return nil
}

Java

To learn how to install and use the client library for Cloud KMS, see Cloud KMS client libraries.

To authenticate to Cloud KMS, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class CreateKeyVersion {

  public void createKeyVersion() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    createKeyVersion(projectId, locationId, keyRingId, keyId);
  }

  // Create a new key version.
  public void createKeyVersion(String projectId, String locationId, String keyRingId, String keyId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build the key version to create.
      CryptoKeyVersion keyVersion = CryptoKeyVersion.newBuilder().build();

      // Create the key.
      CryptoKeyVersion createdVersion = client.createCryptoKeyVersion(cryptoKeyName, keyVersion);
      System.out.printf("Created key version %s%n", createdVersion.getName());
    }
  }
}

Node.js

To learn how to install and use the client library for Cloud KMS, see Cloud KMS client libraries.

To authenticate to Cloud KMS, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function createKeyVersion() {
  const [version] = await client.createCryptoKeyVersion({
    parent: keyName,
  });

  console.log(`Created key version: ${version.name}`);
  return version;
}

return createKeyVersion();

PHP

To learn how to install and use the client library for Cloud KMS, see Cloud KMS client libraries.

To authenticate to Cloud KMS, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyVersionRequest;
use Google\Cloud\Kms\V1\CryptoKeyVersion;

function create_key_version(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
): CryptoKeyVersion {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key version.
    $version = new CryptoKeyVersion();

    // Call the API.
    $createCryptoKeyVersionRequest = (new CreateCryptoKeyVersionRequest())
        ->setParent($keyName)
        ->setCryptoKeyVersion($version);
    $createdVersion = $client->createCryptoKeyVersion($createCryptoKeyVersionRequest);
    printf('Created key version: %s' . PHP_EOL, $createdVersion->getName());

    return $createdVersion;
}

Python

To learn how to install and use the client library for Cloud KMS, see Cloud KMS client libraries.

To authenticate to Cloud KMS, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import kms


def create_key_version(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new version of the given key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key for which to create a new version (e.g. 'my-key').

    Returns:
        CryptoKeyVersion: Cloud KMS key version.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # Build the key version.
    version = {}

    # Call the API.
    created_version = client.create_crypto_key_version(
        request={"parent": key_name, "crypto_key_version": version}
    )
    print(f"Created key version: {created_version.name}")
    return created_version

Ruby

To learn how to install and use the client library for Cloud KMS, see Cloud KMS client libraries.

To authenticate to Cloud KMS, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the version.
version = {}

# Call the API.
created_version = client.create_crypto_key_version parent: key_name, crypto_key_version: version
puts "Created key version: #{created_version.name}"

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.