使用 KEM 进行封装和解封装

本文档介绍了如何将密钥封装机制 (KEM) 与 Cloud KMS 密钥搭配使用来建立共享密钥。

封装使用 KEM 密钥对的公钥,解封装使用该密钥对的私钥。借助 Cloud KMS,您可以检索公钥,然后将该公钥与标准库搭配使用,以封装共享密钥。如需解封装共享密钥,请使用 Cloud KMS 解封装方法。您无法在 Cloud KMS 之外使用私钥材料。

准备工作

  • 本文档提供在命令行运行的示例。为简化示例的使用,请使用 Cloud Shell。加密示例使用预先安装在 Cloud Shell 上的 OpenSSL。否则,请在您的机器上安装 OpenSSL。
  • 创建一个 KEM 密钥密钥用途KEY_ENCAPSULATION)。 如需查看密钥用途 KEY_ENCAPSULATION 支持哪些算法,请参阅密钥封装算法

授予密钥权限

如需详细了解 Cloud KMS 中的权限和角色,请参阅权限和角色

封装

如需使用 KEM 密钥进行封装,请检索公钥并使用该公钥进行封装。

gcloud

此示例要求在本地系统上安装 OpenSSL

下载公钥

gcloud kms keys versions get-public-key KEY_VERSION \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION  \
    --output-file PUBLIC_KEY_FILE \
    --public-key-format PUBLIC_KEY_FORMAT

替换以下内容:

  • KEY_VERSION:您要用于封装的密钥的版本号,例如 2
  • KEY_NAME:您要用于封装的密钥的名称。
  • KEY_RING:包含密钥的密钥环的名称。
  • LOCATION:密钥环的 Cloud KMS 位置。
  • PUBLIC_KEY_FILE:将保存公钥的本地文件路径。
  • PUBLIC_KEY_FORMAT:公钥的目标格式,例如 nist-pqc。默认格式为 pem

重新设置公钥格式

封装命令要求公钥采用 PEM 格式。如果您下载的公钥采用其他格式(例如 nist-pqc),则必须将该密钥转换为 PEM 格式。如果您的公钥已采用 PEM 格式,请从封装开始继续操作。

使用以下命令转换 ML-KEM-768 密钥的公钥:

{ echo -n "MIIEsjALBglghkgBZQMEBAIDggShAA==" | base64 -d ; cat PUBLIC_KEY_FILE; } | \
openssl pkey -inform DER -pubin -pubout -out PEM_PUBLIC_KEY_FILE

使用以下命令转换 ML-KEM-1024 密钥的公钥:

{ echo -n "MIIGMjALBglghkgBZQMEBAMDggYhAA==" | base64 -d ; cat PUBLIC_KEY_FILE; } | \
openssl pkey -inform DER -pubin -pubout -out PEM_PUBLIC_KEY_FILE

替换以下内容:

  • PUBLIC_KEY_FILE:以原始格式下载的公钥文件的路径。
  • PEM_PUBLIC_KEY_FILE:要保存 PEM 格式的公钥的路径和文件名。

封装

如需创建共享密钥和密文,您可以使用以下命令:

openssl pkeyutl \
    -encap \
    -pubin \
    -inkey PEM_PUBLIC_KEY_FILE \
    -out CIPHERTEXT_FILE \
    -secret SHARED_SECRET_FILE

替换以下内容:

  • PEM_PUBLIC_KEY_FILE:下载的 PEM 格式的公钥文件的路径。
  • CIPHERTEXT_FILE:您要将生成的密文保存到的路径。
  • SHARED_SECRET_FILE:您要将生成的共享密钥保存到的路径。

Go

要运行此代码,请先设置 Go 开发环境安装 Cloud KMS Go SDK

import (
	"context"
	"crypto/mlkem"
	"fmt"
	"hash/crc32"
	"io"

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

// encapsulateMLKEM demonstrates how to encapsulate a shared secret using an ML-KEM-768 public key
// from Cloud KMS.
func encapsulateMLKEM(w io.Writer, keyVersionName string) error {
	// keyVersionName := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/1"

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

	// crc32c calculates the CRC32C checksum of the given data.
	crc32c := func(data []byte) uint32 {
		t := crc32.MakeTable(crc32.Castagnoli)
		return crc32.Checksum(data, t)
	}

	// Build the request to get the public key in NIST PQC format.
	req := &kmspb.GetPublicKeyRequest{
		Name:            keyVersionName,
		PublicKeyFormat: kmspb.PublicKey_NIST_PQC,
	}

	// Call the API to get the public key.
	response, err := client.GetPublicKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get public key: %w", err)
	}

	// Optional, but recommended: perform integrity verification on the 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 response.GetName() != req.GetName() {
		return fmt.Errorf("GetPublicKey: request corrupted in-transit")
	}
	if response.GetPublicKeyFormat() != req.GetPublicKeyFormat() {
		return fmt.Errorf("GetPublicKey: request corrupted in-transit")
	}
	if int64(crc32c(response.GetPublicKey().GetData())) != response.GetPublicKey().GetCrc32CChecksum().GetValue() {
		return fmt.Errorf("GetPublicKey: response corrupted in-transit")
	}

	// Use the public key with crypto/mlkem to encapsulate a shared secret.
	ek, err := mlkem.NewEncapsulationKey768(response.GetPublicKey().GetData())
	if err != nil {
		return fmt.Errorf("NewEncapsulationKey768: %w", err)
	}
	sharedSecret, ciphertext := ek.Encapsulate()

	fmt.Fprintf(w, "Encapsulated ciphertext: %x\n", ciphertext)
	fmt.Fprintf(w, "Shared secret: %x\n", sharedSecret)
	return nil
}

解封装

使用 Cloud KMS 对密文进行解封装。

gcloud

如需在命令行上使用 Cloud KMS,请先安装或升级到最新版本的 Google Cloud CLI

gcloud kms decapsulate \
    --version KEY_VERSION \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION  \
    --ciphertext-file CIPHERTEXT_FILE \
    --shared-secret-file SHARED_SECRET_FILE

替换以下内容:

  • KEY_VERSION:用于解封装的密钥版本,例如 3
  • KEY_NAME:用于解封装的密钥的名称。
  • KEY_RING:密钥所在的密钥环的名称。
  • LOCATION:密钥环的 Cloud KMS 位置。
  • CIPHERTEXT_FILE:输入密文的本地文件路径。
  • SHARED_SECRET_FILE:用于保存输出共享密钥的本地文件路径。

Go

要运行此代码,请先设置 Go 开发环境安装 Cloud KMS Go SDK

import (
	"context"
	"fmt"
	"hash/crc32"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

// decapsulate decapsulates the given ciphertext using a saved private key of purpose
// KEY_ENCAPSULATION stored in KMS.
func decapsulate(w io.Writer, keyVersionName string, ciphertext []byte) error {
	// keyVersionName := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/1"
	// ciphertext := []byte("...")

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

	// crc32c calculates the CRC32C checksum of the given data.
	crc32c := func(data []byte) uint32 {
		t := crc32.MakeTable(crc32.Castagnoli)
		return crc32.Checksum(data, t)
	}

	// Optional but recommended: Compute ciphertext's CRC32C.
	ciphertextCRC32C := crc32c(ciphertext)

	// Build the request.
	req := &kmspb.DecapsulateRequest{
		Name:             keyVersionName,
		Ciphertext:       ciphertext,
		CiphertextCrc32C: wrapperspb.Int64(int64(ciphertextCRC32C)),
	}

	// Call the API.
	result, err := client.Decapsulate(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to decapsulate: %w", err)
	}

	// Optional, but recommended: perform integrity verification on the 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 !result.GetVerifiedCiphertextCrc32C() {
		return fmt.Errorf("Decapsulate: request corrupted in-transit")
	}
	if result.GetName() != req.GetName() {
		return fmt.Errorf("Decapsulate: request corrupted in-transit")
	}
	if int64(crc32c(result.GetSharedSecret())) != result.GetSharedSecretCrc32C() {
		return fmt.Errorf("Decapsulate: response corrupted in-transit")
	}

	fmt.Fprintf(w, "Decapsulated plaintext: %x", result.GetSharedSecret())
	return nil
}

API

这些示例使用 curl 作为 HTTP 客户端来演示如何使用 API。如需详细了解访问权限控制,请参阅访问 Cloud KMS API

使用 CryptoKeyVersions.decapsulate 方法。

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION:decapsulate" \
  --request "POST" \
  --header "authorization: Bearer TOKEN" \
  --header "content-type: application/json" \
  --data '{"ciphertext": "CIPHERTEXT"}'

替换以下内容:

  • PROJECT_ID:包含密钥环的项目的 ID。
  • LOCATION:密钥环的 Cloud KMS 位置。
  • KEY_RING:包含密钥的密钥环的名称。
  • KEY_NAME:用于加密的密钥的名称。
  • KEY_VERSION:用于加密的密钥版本的 ID
  • CIPHERTEXT:要解封装的 base64 编码密文。