创建新的密钥版本

创建给定密钥的新版本。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库

如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库

如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库

如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库

如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

//
// 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

如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库

如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库

如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库

如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器