使用 Google Cloud Console、gcloud
命令行工具和 Cloud Key Management Service API,您可以检索非对称密钥版本的公钥部分。
公钥采用隐私权保密增强电子邮件 (PEM) 格式。如需了解详情,请参阅 RFC 7468 部分中的一般注意事项和主体公钥信息的文本编码。
将检索公钥的用户或服务需要具有密钥版本的 cloudkms.cryptoKeyVersions.viewPublicKey
权限。您可以参阅权限和角色,了解 Cloud KMS 测试版中的权限。
要下载现有非对称密钥版本的公钥,请执行以下操作:
网页界面
转到 Cloud Console 中的加密密钥页面。
点击包含您要检索公钥的非对称密钥的密钥环的名称。
点击要检索公钥的密钥的名称。
在与要检索公钥的密钥版本对应的行中,点击查看更多 more_vert。
点击获取公钥。
公钥显示在提示中。您可以将公钥复制到剪贴板。要下载公钥,请点击下载。
如果您没有看到获取公钥选项,请验证密钥是否为非对称密钥,以及您是否拥有 cloudkms.cryptoKeyVersions.viewPublicKey
权限。
从 Cloud Console 下载的公钥的文件名格式为:
[key-ring]-[key-name]-[key-version].pub
文件名的每个部分由连字符分隔。
命令行
要在命令行上使用 Cloud KMS,请先安装或升级到最新版本的 Cloud SDK。
gcloud kms keys versions get-public-key key-version \ --key key \ --keyring key-ring-name \ --location location \ --output-file public-key.pub
将 key-version 替换为密钥版本。将 key 替换为密钥的名称。将 key-ring 替换为存储密钥的密钥环的名称。将 location 替换为密钥环的 Cloud KMS 位置。将 public-key.pub 替换为要保存公钥的文件路径。
如需了解所有标志和可能值,请使用 --help
标志运行命令。
C#
要运行此代码,请先设置 C# 开发环境并安装 Cloud KMS C# SDK。
using Google.Cloud.Kms.V1;
public class GetPublicKeySample
{
public PublicKey GetPublicKey(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
{
// Create the client.
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
// Build the key version name.
CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);
// Call the API.
PublicKey result = client.GetPublicKey(keyVersionName);
// Return the ciphertext.
return result;
}
}
Go
要运行此代码,请先设置 Go 开发环境并安装 Cloud KMS Go SDK。
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"hash/crc32"
"io"
kms "cloud.google.com/go/kms/apiv1"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
// getPublicKey retrieves the public key from an asymmetric key pair on
// Cloud KMS.
func getPublicKey(w io.Writer, name string) error {
// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"
// 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.GetPublicKeyRequest{
Name: name,
}
// Call the API.
result, err := client.GetPublicKey(ctx, req)
if err != nil {
return fmt.Errorf("failed to get public key: %v", err)
}
// The 'Pem' field is the raw string representation of the public key.
// Convert 'Pem' into bytes for further processing.
key := []byte(result.Pem)
// Optional, but recommended: perform integrity verification on result.
// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
// https://cloud.google.com/kms/docs/data-integrity-guidelines
crc32c := func(data []byte) uint32 {
t := crc32.MakeTable(crc32.Castagnoli)
return crc32.Checksum(data, t)
}
if int64(crc32c(key)) != result.PemCrc32C.Value {
return fmt.Errorf("getPublicKey: response corrupted in-transit")
}
// Optional - parse the public key. This transforms the string key into a Go
// PublicKey.
block, _ := pem.Decode(key)
publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse public key: %v", err)
}
fmt.Fprintf(w, "Retrieved public key: %v\n", publicKey)
return nil
}
Java
要运行此代码,请先设置 Java 开发环境并安装 Cloud KMS Java SDK。
import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.PublicKey;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.protobuf.Int64Value;
import java.io.IOException;
import java.security.GeneralSecurityException;
public class GetPublicKey {
public void getPublicKey() throws IOException, GeneralSecurityException {
// 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";
String keyVersionId = "123";
getPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
}
// Get the public key associated with an asymmetric key.
public void getPublicKey(
String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
throws IOException, GeneralSecurityException {
// 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 key version name from the project, location, key ring, key,
// and key version.
CryptoKeyVersionName keyVersionName =
CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);
// Get the public key.
PublicKey publicKey = client.getPublicKey(keyVersionName);
// Optional, but recommended: perform integrity verification on response.
// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
// https://cloud.google.com/kms/docs/data-integrity-guidelines
if (!publicKey.getName().equals(keyVersionName.toString())) {
throw new IOException("GetPublicKey: request to server corrupted");
}
// See helper below.
if (!crcMatches(publicKey.getPemCrc32C().getValue(),
publicKey.getPemBytes().toByteArray())) {
throw new IOException("GetPublicKey: response from server corrupted");
}
System.out.printf("Public key: %s%n", publicKey.getPem());
}
}
private long getCrc32cAsLong(byte[] data) {
return Hashing.crc32c().hashBytes(data).padToLong();
}
private boolean crcMatches(long expectedCrc, byte[] data) {
return expectedCrc == getCrc32cAsLong(data);
}
}
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 keyId = 'my-key';
// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');
// Instantiates a client
const client = new KeyManagementServiceClient();
// Build the key version name
const versionName = client.cryptoKeyVersionPath(
projectId,
locationId,
keyRingId,
keyId,
versionId
);
async function getPublicKey() {
const [publicKey] = await client.getPublicKey({
name: versionName,
});
console.log(`Public key pem: ${publicKey.pem}`);
return publicKey;
}
return getPublicKey();
PHP
要运行此代码,请先了解如何在 Google Cloud 上使用 PHP 并安装 Cloud KMS PHP SDK。
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
function get_public_key_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key',
string $versionId = '123'
) {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
// Build the key version name.
$keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);
// Call the API.
$publicKey = $client->getPublicKey($keyVersionName);
printf('Public key: %s' . PHP_EOL, $publicKey->getPem());
return $publicKey;
}
Python
要运行此代码,请先设置 Python 开发环境并安装 Cloud KMS Python SDK。
def get_public_key(project_id, location_id, key_ring_id, key_id, version_id):
"""
Get the public key for an asymmetric 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 to use (e.g. 'my-key').
version_id (string): ID of the key to use (e.g. '1').
Returns:
PublicKey: Cloud KMS public key response.
"""
# Import the client library.
from google.cloud import kms
# Create the client.
client = kms.KeyManagementServiceClient()
# Build the key version name.
key_version_name = client.crypto_key_version_path(project_id, location_id, key_ring_id, key_id, version_id)
# Call the API.
public_key = client.get_public_key(request={'name': key_version_name})
# Optional, but recommended: perform integrity verification on public_key.
# For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
# https://cloud.google.com/kms/docs/data-integrity-guidelines
if not public_key.name == key_version_name:
raise Exception('The request sent to the server was corrupted in-transit.')
# See crc32c() function defined below.
if not public_key.pem_crc32c == crc32c(public_key.pem):
raise Exception('The response received from the server was corrupted in-transit.')
# End integrity verification
print('Public key: {}'.format(public_key.pem))
return public_key
def crc32c(data):
"""
Calculates the CRC32C checksum of the provided data.
Args:
data: the bytes over which the checksum should be calculated.
Returns:
An int representing the CRC32C checksum of the provided bytes.
"""
import crcmod
import six
crc32c_fun = crcmod.predefined.mkPredefinedCrcFun('crc-32c')
return crc32c_fun(six.ensure_binary(data))
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"
# key_id = "my-key"
# version_id = "123"
# Require the library.
require "google/cloud/kms"
# Create the client.
client = Google::Cloud::Kms.key_management_service
# Build the key version name.
key_version_name = client.crypto_key_version_path project: project_id,
location: location_id,
key_ring: key_ring_id,
crypto_key: key_id,
crypto_key_version: version_id
# Call the API.
public_key = client.get_public_key name: key_version_name
puts "Public key: #{public_key.pem}"
API
这些示例使用 curl 作为 HTTP 客户端来演示如何使用 API。如需详细了解访问权限控制,请参阅访问 Cloud KMS API。
通过调用 CryptoKeyVersions.getPublicKey 方法检索公钥。