获取密钥版本的证明

获取 HSM 后端密钥的证明。

代码示例

C#

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

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


using Google.Cloud.Kms.V1;
using System;

public class GetKeyVersionAttestationSample
{
    public byte[] GetKeyVersionAttestation(
      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 name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        CryptoKeyVersion result = client.GetCryptoKeyVersion(keyVersionName);

        // Only HSM keys have an attestation. For other key types, the attestion
        // will be nil.
        KeyOperationAttestation attestation = result.Attestation;
        if (attestation == null)
        {
            throw new InvalidOperationException("no attestation");
        }

        // Return the attestation.
        return attestation.Content.ToByteArray();
    }
}

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"
)

// getKeyVersionAttestation gets the attestation on a key version, if one
// exists.
func getKeyVersionAttestation(w io.Writer, name string) error {
	// name := "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: %w", err)
	}

	// Build the request.
	req := &kmspb.GetCryptoKeyVersionRequest{
		Name: name,
	}

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

	// Only HSM keys have an attestation. For other key types, the attestion will
	// be nil.
	attestation := result.Attestation
	if attestation == nil {
		return fmt.Errorf("no attestation for %s", name)
	}

	// Print the attestation, hex-encoded.
	fmt.Fprintf(w, "%s: %x", attestation.Format, attestation.Content)
	return nil
}

Java

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

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

import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyOperationAttestation;
import java.io.IOException;
import java.util.Base64;

public class GetKeyVersionAttestation {

  public void getKeyVersionAttestation() 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";
    String keyVersionId = "123";
    getKeyVersionAttestation(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Get the attestations for a key version
  public void getKeyVersionAttestation(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      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 name from the project, location, key ring, and keyId.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Get the key version.
      CryptoKeyVersion keyVersion = client.getCryptoKeyVersion(keyVersionName);

      // Only HSM keys have an attestation. For other key types, the attestion
      // will be nil.
      if (!keyVersion.hasAttestation()) {
        System.out.println("no attestation");
        return;
      }

      // Print the attestation, base64-encoded.
      KeyOperationAttestation attestation = keyVersion.getAttestation();
      String format = attestation.getFormat().toString();
      byte[] content = attestation.getContent().toByteArray();
      System.out.printf("%s: %s", format, Base64.getEncoder().encodeToString(content));
    }
  }
}

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';
// const versionId = '123';

// 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 getKeyVersionAttestation() {
  const [version] = await client.getCryptoKeyVersion({
    name: versionName,
  });

  // Only HSM keys have an attestation. For other key types, the attestion
  // will be nil.
  const attestation = version.attestation;
  if (!attestation) {
    throw new Error('no attestation');
  }

  console.log(`Attestation: ${attestation.toString('base64')}`);
  return attestation.content;
}

return getKeyVersionAttestation();

PHP

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

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

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\GetCryptoKeyVersionRequest;

function get_key_version_attestation(
    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 name.
    $keyVersionName = $client->cryptokeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Call the API.
    $getCryptoKeyVersionRequest = (new GetCryptoKeyVersionRequest())
        ->setName($keyVersionName);
    $version = $client->getCryptoKeyVersion($getCryptoKeyVersionRequest);

    // Only HSM keys have an attestation. For other key types, the attestion
    // will be NULL.
    $attestation = $version->getAttestation();
    if (!$attestation) {
        throw new Exception('no attestation - attestations only exist on HSM keys');
    }

    printf('Got key attestation: %s' . PHP_EOL, $attestation->getContent());

    return $attestation;
}

Python

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

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

from google.cloud import kms

def get_key_version_attestation(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.KeyOperationAttestation:
    """
    Get an HSM-backend key's attestation.

    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 version to use (e.g. '1').

    Returns:
        Attestation: Cloud KMS key attestation.

    """

    # Import base64 for printing the attestation.
    import base64

    # 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.
    version = client.get_crypto_key_version(request={"name": key_version_name})

    # Only HSM keys have an attestation. For other key types, the attestion
    # will be None.
    attestation = version.attestation
    if not attestation:
        raise "no attestation - attestations only exist on HSM keys"

    encoded_attestation = base64.b64encode(attestation.content)
    print(f"Got key attestation: {encoded_attestation!r}")
    return attestation

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"
# 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.
version = client.get_crypto_key_version name: key_version_name

# Only HSM keys have an attestation. For other key types, the attestion will
# be nil.
attestation = version.attestation
unless attestation
  raise "no attestation"
end

puts "Attestation: #{Base64.strict_encode64 attestation.content}"

后续步骤

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