检索公钥

使用 Google Cloud Console、gcloud 命令行工具和 Cloud Key Management Service API,您可以检索非对称密钥版本的公钥部分。

公钥采用隐私权保密增强电子邮件 (PEM) 格式。如需了解详情,请参阅 RFC 7468 部分中的一般注意事项主体公钥信息的文本编码

将检索公钥的用户或服务需要具有密钥版本的 cloudkms.cryptoKeyVersions.viewPublicKey 权限。您可以参阅权限和角色,了解 Cloud KMS 测试版中的权限。

要下载现有非对称密钥版本的公钥,请执行以下操作:

网页界面

  1. 转到 Cloud Console 中的加密密钥页面。

    转到“加密密钥”页面

  2. 点击包含您要检索公钥的非对称密钥的密钥环的名称。

  3. 点击要检索公钥的密钥的名称。

  4. 在与要检索公钥的密钥版本对应的行中,点击查看更多

  5. 点击获取公钥

  6. 公钥显示在提示中。您可以将公钥复制到剪贴板。要下载公钥,请点击下载

如果您没有看到获取公钥选项,请验证密钥是否为非对称密钥,以及您是否拥有 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"
	"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.
	key := result.Pem

	//
	// Optional - parse the public key. This transforms the string key into a Go
	// PublicKey.
	//

	block, _ := pem.Decode([]byte(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 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);
      System.out.printf("Public key: %s%n", publicKey.getPem());
    }
  }
}

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})
    print('Public key: {}'.format(public_key.pem))
    return public_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"
# 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 方法检索公钥。