本页面介绍如何创建用于加密的对称密钥。
您还可以创建非对称密钥、Cloud HSM 密钥或 Cloud External Key Manager 密钥。
概览
创建密钥时,您将其添加到给定 Google Cloud 位置中的密钥环。您可以创建新的密钥环,也可以使用现有的密钥环。在本主题中,您将创建一个新的密钥环,并向其添加新密钥。
创建密钥环
请按照以下步骤为新密钥创建密钥环。如果希望改用现有密钥环,则可以创建密钥。
网页界面
转到 Cloud Console 中的加密密钥页面。
点击创建密钥环。
在密钥环名称字段中,输入所需的密钥环名称。
在密钥环位置下拉列表中,选择一个位置,例如
"us-east1"
。点击创建。
命令行
要在命令行上使用 Cloud KMS,请先安装或升级到最新版本的 Cloud SDK。
gcloud kms keyrings create key-ring \ --location location
将 key-ring 替换为密钥环的名称。将 location 替换为密钥环及其密钥的 Cloud KMS 位置。
如需了解所有标志和可能值,请使用 --help
标志运行命令。
C#
要运行此代码,请先设置 C# 开发环境并安装 Cloud KMS C# SDK。
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Kms.V1;
public class CreateKeyRingSample
{
public KeyRing CreateKeyRing(
string projectId = "my-project", string locationId = "us-east1",
string id = "my-key-ring")
{
// Create the client.
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
// Build the parent location name.
LocationName locationName = new LocationName(projectId, locationId);
// Build the key ring.
KeyRing keyRing = new KeyRing { };
// Call the API.
KeyRing result = client.CreateKeyRing(locationName, id, keyRing);
// Return the result.
return result;
}
}
Go
要运行此代码,请先设置 Go 开发环境并安装 Cloud KMS Go SDK。
import (
"context"
"fmt"
"io"
kms "cloud.google.com/go/kms/apiv1"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
// createKeyRing creates a new ring to store keys on KMS.
func createKeyRing(w io.Writer, parent, id string) error {
// parent := "projects/PROJECT_ID/locations/global"
// id := "my-key-ring"
// Create the client.
ctx := context.Background()
client, err := kms.NewKeyManagementClient(ctx)
if err != nil {
return fmt.Errorf("failed to create kms client: %v", err)
}
// Build the request.
req := &kmspb.CreateKeyRingRequest{
Parent: parent,
KeyRingId: id,
}
// Call the API.
result, err := client.CreateKeyRing(ctx, req)
if err != nil {
return fmt.Errorf("failed to create key ring: %v", err)
}
fmt.Fprintf(w, "Created key ring: %s\n", result.Name)
return nil
}
Java
要运行此代码,请先设置 Java 开发环境并安装 Cloud KMS Java SDK。
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;
import java.io.IOException;
public class CreateKeyRing {
public void createKeyRing() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String locationId = "us-east1";
String id = "my-asymmetric-signing-key";
createKeyRing(projectId, locationId, id);
}
// Create a new key ring.
public void createKeyRing(String projectId, String locationId, String id) 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 and location.
LocationName locationName = LocationName.of(projectId, locationId);
// Build the key ring to create.
KeyRing keyRing = KeyRing.newBuilder().build();
// Create the key ring.
KeyRing createdKeyRing = client.createKeyRing(locationName, id, keyRing);
System.out.printf("Created key ring %s%n", createdKeyRing.getName());
}
}
}
Node.js
要运行此代码,请先设置 Node.js 开发环境并安装 Cloud KMS Node.js SDK。
//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const id = 'my-key-ring';
// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');
// Instantiates a client
const client = new KeyManagementServiceClient();
// Build the parent location name
const locationName = client.locationPath(projectId, locationId);
async function createKeyRing() {
const [keyRing] = await client.createKeyRing({
parent: locationName,
keyRingId: id,
});
console.log(`Created key ring: ${keyRing.name}`);
return keyRing;
}
return createKeyRing();
PHP
要运行此代码,请先了解如何在 Google Cloud 上使用 PHP 并安装 Cloud KMS PHP SDK。
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\KeyRing;
function create_key_ring_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
string $id = 'my-key-ring'
) {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
// Build the parent location name.
$locationName = $client->locationName($projectId, $locationId);
// Build the key ring.
$keyRing = new KeyRing();
// Call the API.
$createdKeyRing = $client->createKeyRing($locationName, $id, $keyRing);
printf('Created key ring: %s' . PHP_EOL, $createdKeyRing->getName());
return $createdKeyRing;
}
Python
要运行此代码,请先设置 Python 开发环境并安装 Cloud KMS Python SDK。
def create_key_ring(project_id, location_id, id):
"""
Creates a new key ring in Cloud KMS
Args:
project_id (string): Google Cloud project ID (e.g. 'my-project').
location_id (string): Cloud KMS location (e.g. 'us-east1').
id (string): ID of the key ring to create (e.g. 'my-key-ring').
Returns:
KeyRing: Cloud KMS key ring.
"""
# Import the client library.
from google.cloud import kms
# Create the client.
client = kms.KeyManagementServiceClient()
# Build the parent location name.
location_name = f'projects/{project_id}/locations/{location_id}'
# Build the key ring.
key_ring = {}
# Call the API.
created_key_ring = client.create_key_ring(request={'parent': location_name, 'key_ring_id': id, 'key_ring': key_ring})
print('Created key ring: {}'.format(created_key_ring.name))
return created_key_ring
Ruby
要运行此代码,请先设置 Ruby 开发环境并安装 Cloud KMS Ruby SDK。
# TODO(developer): uncomment these values before running the sample.
# project_id = "my-project"
# location_id = "us-east1"
# id = "my-key-ring"
# Require the library.
require "google/cloud/kms"
# Create the client.
client = Google::Cloud::Kms.key_management_service
# Build the parent location name.
location_name = client.location_path project: project_id, location: location_id
# Build the key ring.
key_ring = {}
# Call the API.
created_key_ring = client.create_key_ring parent: location_name, key_ring_id: id, key_ring: key_ring
puts "Created key ring: #{created_key_ring.name}"
API
这些示例使用 curl 作为 HTTP 客户端来演示如何使用 API。如需详细了解访问权限控制,请参阅访问 Cloud KMS API。
curl "https://cloudkms.googleapis.com/v1/projects/project-id/locations/location-id/keyRings" \ --request "POST" \ --header "authorization: Bearer token" \ --header "content-type: application/json" \ --header "x-goog-user-project: project-id" \ --data "{\"name\": {\"key-ring-name\": {}}}"
如需了解详情,请参阅 KeyRing.create
API 文档。
创建密钥
按照以下步骤在指定的密钥环和位置创建对称密钥。
网页界面
转到 Cloud Console 中的加密密钥页面。
点击您要为其创建密钥的密钥环的名称。
点击创建密钥。
在您要创建哪种类型的密钥?中,选择生成的密钥。
在密钥名称字段中,输入密钥的名称。
点击保护级别下拉列表,然后选择软件。
点击用途下拉列表,然后选择对称加密/解密。
接受轮替周期和开始日期的默认值。
点击创建。
命令行
要在命令行上使用 Cloud KMS,请先安装或升级到最新版本的 Cloud SDK。
gcloud kms keys create key \ --keyring key-ring \ --location location \ --purpose "encryption"
将 key 替换为密钥的名称。将 key-ring 替换为密钥将要存放到的密钥环的名称。将 location 替换为密钥环的 Cloud KMS 位置。
如需了解所有标志和可能值,请使用 --help
标志运行命令。
C#
要运行此代码,请先设置 C# 开发环境并安装 Cloud KMS C# SDK。
using Google.Cloud.Kms.V1;
public class CreateKeySymmetricEncryptDecryptSample
{
public CryptoKey CreateKeySymmetricEncryptDecrypt(
string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
string id = "my-symmetric-encryption-key")
{
// Create the client.
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
// Build the parent key ring name.
KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
// Build the key.
CryptoKey key = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
}
};
// Call the API.
CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
// Return the result.
return result;
}
}
Go
要运行此代码,请先设置 Go 开发环境并安装 Cloud KMS Go SDK。
import (
"context"
"fmt"
"io"
kms "cloud.google.com/go/kms/apiv1"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
// createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
// on Cloud KMS.
func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
// id := "my-symmetric-encryption-key"
// Create the client.
ctx := context.Background()
client, err := kms.NewKeyManagementClient(ctx)
if err != nil {
return fmt.Errorf("failed to create kms client: %v", err)
}
// Build the request.
req := &kmspb.CreateCryptoKeyRequest{
Parent: parent,
CryptoKeyId: id,
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 fmt.Errorf("failed to create key: %v", err)
}
fmt.Fprintf(w, "Created key: %s\n", result.Name)
return nil
}
Java
要运行此代码,请先设置 Java 开发环境并安装 Cloud KMS Java SDK。
import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import java.io.IOException;
public class CreateKeySymmetricEncryptDecrypt {
public void createKeySymmetricEncryptDecrypt() 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 id = "my-key";
createKeySymmetricEncryptDecrypt(projectId, locationId, keyRingId, id);
}
// Create a new key that is used for symmetric encryption and decryption.
public void createKeySymmetricEncryptDecrypt(
String projectId, String locationId, String keyRingId, String id) 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.
KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
// Build the symmetric key to create.
CryptoKey key =
CryptoKey.newBuilder()
.setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
.setVersionTemplate(
CryptoKeyVersionTemplate.newBuilder()
.setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
.build();
// Create the key.
CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
System.out.printf("Created symmetric key %s%n", createdKey.getName());
}
}
}
Node.js
要运行此代码,请先设置 Node.js 开发环境并安装 Cloud KMS Node.js SDK。
//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-symmetric-encryption-key';
// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');
// Instantiates a client
const client = new KeyManagementServiceClient();
// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
async function createKeySymmetricEncryptDecrypt() {
const [key] = await client.createCryptoKey({
parent: keyRingName,
cryptoKeyId: id,
cryptoKey: {
purpose: 'ENCRYPT_DECRYPT',
versionTemplate: {
algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
},
},
});
console.log(`Created symmetric key: ${key.name}`);
return key;
}
return createKeySymmetricEncryptDecrypt();
PHP
要运行此代码,请先了解如何在 Google Cloud 上使用 PHP 并安装 Cloud KMS PHP SDK。
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
function create_key_symmetric_encrypt_decrypt_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-symmetric-key'
) {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
// Build the parent key ring name.
$keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
// Build the key.
$key = (new CryptoKey())
->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
->setVersionTemplate((new CryptoKeyVersionTemplate())
->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
);
// Call the API.
$createdKey = $client->createCryptoKey($keyRingName, $id, $key);
printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());
return $createdKey;
}
Python
要运行此代码,请先设置 Python 开发环境并安装 Cloud KMS Python SDK。
def create_key_symmetric_encrypt_decrypt(project_id, location_id, key_ring_id, id):
"""
Creates a new symmetric encryption/decryption key in Cloud KMS.
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').
id (string): ID of the key to create (e.g. 'my-symmetric-key').
Returns:
CryptoKey: Cloud KMS key.
"""
# Import the client library.
from google.cloud import kms
# Create the client.
client = kms.KeyManagementServiceClient()
# Build the parent key ring name.
key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
# Build the key.
purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
key = {
'purpose': purpose,
'version_template': {
'algorithm': algorithm,
}
}
# Call the API.
created_key = client.create_crypto_key(request={'parent': key_ring_name, 'crypto_key_id': id, 'crypto_key': key})
print('Created symmetric key: {}'.format(created_key.name))
return created_key
Ruby
要运行此代码,请先设置 Ruby 开发环境并安装 Cloud KMS Ruby SDK。
# TODO(developer): uncomment these values before running the sample.
# project_id = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id = "my-symmetric-key"
# Require the library.
require "google/cloud/kms"
# Create the client.
client = Google::Cloud::Kms.key_management_service
# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
# Build the key.
key = {
purpose: :ENCRYPT_DECRYPT,
version_template: {
algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
}
}
# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created symmetric key: #{created_key.name}"
设置密钥轮替周期和开始时间
可以使用指定的轮替周期创建密钥,该周期是两次自动生成新密钥版本的时间间隔。还可以使用指定的下次轮替时间创建密钥。
网页界面
使用 Google Cloud Console 创建密钥时,如果您未指定自己的轮替周期和下次轮替的时间,则 Cloud KMS 会自动设置该密钥的轮替周期和下次轮替的时间。
如需在创建密钥期间,但在点击创建按钮之前指定其他轮替周期和开始时间,请执行以下操作:
点击轮替周期下拉列表,然后针对轮替周期选择一个值。
在开始日期字段中点击日期,然后针对下一次轮替选择一个日期。
命令行
要在命令行上使用 Cloud KMS,请先安装或升级到最新版本的 Cloud SDK。
gcloud kms keys create key \ --keyring key-ring \ --location location \ --purpose "encryption" \ --rotation-period rotation-period \ --next-rotation-time next-rotation-time
将 key 替换为密钥的名称。将 key-ring 替换为密钥将要存放到的现有密钥环的名称。将 location 替换为密钥环的 Cloud KMS 位置。将 rotation-period 替换为一个时间间隔,例如 30d
,以每 30 天轮替一次密钥。将 next-rotation-time 替换为开始第一次轮替的时间戳,例如 "1970-01-01T01:02:03"
。
如需了解所有标志和可能值,请使用 --help
标志运行命令。
C#
要运行此代码,请先设置 C# 开发环境并安装 Cloud KMS C# SDK。
using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;
using System;
public class CreateKeyRotationScheduleSample
{
public CryptoKey CreateKeyRotationSchedule(
string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
string id = "my-key-with-rotation-schedule")
{
// Create the client.
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
// Build the parent key ring name.
KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
// Build the key.
CryptoKey key = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
},
// Rotate the key every 30 days.
RotationPeriod = new Duration
{
Seconds = 60 * 60 * 24 * 30, // 30 days
},
// Start the first rotation in 24 hours.
NextRotationTime = new Timestamp
{
Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
}
};
// Call the API.
CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
// Return the result.
return result;
}
}
Go
要运行此代码,请先设置 Go 开发环境并安装 Cloud KMS Go SDK。
import (
"context"
"fmt"
"io"
"time"
kms "cloud.google.com/go/kms/apiv1"
"github.com/golang/protobuf/ptypes/duration"
"github.com/golang/protobuf/ptypes/timestamp"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
// createKeyRotationSchedule creates a key with a rotation schedule.
func createKeyRotationSchedule(w io.Writer, parent, id string) error {
// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
// id := "my-key-with-rotation-schedule"
// Create the client.
ctx := context.Background()
client, err := kms.NewKeyManagementClient(ctx)
if err != nil {
return fmt.Errorf("failed to create kms client: %v", err)
}
// Build the request.
req := &kmspb.CreateCryptoKeyRequest{
Parent: parent,
CryptoKeyId: id,
CryptoKey: &kmspb.CryptoKey{
Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
},
// Rotate the key every 30 days
RotationSchedule: &kmspb.CryptoKey_RotationPeriod{
RotationPeriod: &duration.Duration{
Seconds: int64(60 * 60 * 24 * 30), // 30 days
},
},
// Start the first rotation in 24 hours
NextRotationTime: ×tamp.Timestamp{
Seconds: time.Now().Add(24 * time.Hour).Unix(),
},
},
}
// Call the API.
result, err := client.CreateCryptoKey(ctx, req)
if err != nil {
return fmt.Errorf("failed to create key: %v", err)
}
fmt.Fprintf(w, "Created key: %s\n", result.Name)
return nil
}
Java
要运行此代码,请先设置 Java 开发环境并安装 Cloud KMS Java SDK。
import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.time.temporal.ChronoUnit;
public class CreateKeyRotationSchedule {
public void createKeyRotationSchedule() 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 id = "my-key";
createKeyRotationSchedule(projectId, locationId, keyRingId, id);
}
// Create a new key that automatically rotates on a schedule.
public void createKeyRotationSchedule(
String projectId, String locationId, String keyRingId, String id) 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.
KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
// Calculate the date 24 hours from now (this is used below).
long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();
// Build the key to create with a rotation schedule.
CryptoKey key =
CryptoKey.newBuilder()
.setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
.setVersionTemplate(
CryptoKeyVersionTemplate.newBuilder()
.setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
// Rotate every 30 days.
.setRotationPeriod(
Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))
// Start the first rotation in 24 hours.
.setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
.build();
// Create the key.
CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
System.out.printf("Created key with rotation schedule %s%n", createdKey.getName());
}
}
}
Node.js
要运行此代码,请先设置 Node.js 开发环境并安装 Cloud KMS Node.js SDK。
//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-rotating-encryption-key';
// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');
// Instantiates a client
const client = new KeyManagementServiceClient();
// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
async function createKeyRotationSchedule() {
const [key] = await client.createCryptoKey({
parent: keyRingName,
cryptoKeyId: id,
cryptoKey: {
purpose: 'ENCRYPT_DECRYPT',
versionTemplate: {
algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
},
// Rotate the key every 30 days.
rotationPeriod: {
seconds: 60 * 60 * 24 * 30,
},
// Start the first rotation in 24 hours.
nextRotationTime: {
seconds: new Date().getTime() / 1000 + 60 * 60 * 24,
},
},
});
console.log(`Created rotating key: ${key.name}`);
return key;
}
return createKeyRotationSchedule();
PHP
要运行此代码,请先了解如何在 Google Cloud 上使用 PHP 并安装 Cloud KMS PHP SDK。
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;
function create_key_rotation_schedule_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-key-with-rotation-schedule'
) {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
// Build the parent key ring name.
$keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
// Build the key.
$key = (new CryptoKey())
->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
->setVersionTemplate((new CryptoKeyVersionTemplate())
->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION))
// Rotate the key every 30 days.
->setRotationPeriod((new Duration())
->setSeconds(60*60*24*30)
)
// Start the first rotation in 24 hours.
->setNextRotationTime((new Timestamp())
->setSeconds(time() + 60*60*24)
);
// Call the API.
$createdKey = $client->createCryptoKey($keyRingName, $id, $key);
printf('Created key with rotation: %s' . PHP_EOL, $createdKey->getName());
return $createdKey;
}
Python
要运行此代码,请先设置 Python 开发环境并安装 Cloud KMS Python SDK。
def create_key_rotation_schedule(project_id, location_id, key_ring_id, id):
"""
Creates a new key in Cloud KMS that automatically rotates.
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').
id (string): ID of the key to create (e.g. 'my-rotating-key').
Returns:
CryptoKey: Cloud KMS key.
"""
# Import the client library.
from google.cloud import kms
# Import time for getting the current time.
import time
# Create the client.
client = kms.KeyManagementServiceClient()
# Build the parent key ring name.
key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
# Build the key.
purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
key = {
'purpose': purpose,
'version_template': {
'algorithm': algorithm,
},
# Rotate the key every 30 days.
'rotation_period': {
'seconds': 60*60*24*30
},
# Start the first rotation in 24 hours.
'next_rotation_time': {
'seconds': int(time.time()) + 60*60*24
}
}
# Call the API.
created_key = client.create_crypto_key(request={'parent': key_ring_name, 'crypto_key_id': id, 'crypto_key': key})
print('Created labeled key: {}'.format(created_key.name))
return created_key
Ruby
要运行此代码,请先设置 Ruby 开发环境并安装 Cloud KMS Ruby SDK。
# TODO(developer): uncomment these values before running the sample.
# project_id = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id = "my-key-with-rotation"
# Require the library.
require "google/cloud/kms"
# Create the client.
client = Google::Cloud::Kms.key_management_service
# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
# Build the key.
key = {
purpose: :ENCRYPT_DECRYPT,
version_template: {
algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
},
# Rotate the key every 30 days.
rotation_period: {
seconds: 60 * 60 * 24 * 30
},
# Start the first rotation in 24 hours.
next_rotation_time: {
seconds: (Time.now + 60 * 60 * 24).to_i
}
}
# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created rotating key: #{created_key.name}"
手动创建新的密钥版本
除了自动轮替外,您还可以手动轮替密钥。如需了解详情,请参阅轮替密钥。