Cloud KMS 客户端库

本页面介绍如何开始使用 Cloud Key Management Service API 的 Cloud 客户端库。通过客户端库,您可以更轻松地使用支持的语言访问 Google Cloud API。虽然您可以通过向服务器发出原始请求来直接使用 Google Cloud API,但客户端库可实现简化,从而显著减少您需要编写的代码量。

请参阅客户端库说明,详细了解 Cloud 客户端库和旧版 Google API 客户端库。

安装客户端库

C++

如需详细了解此客户端库的要求和安装依赖项,请参阅设置 C++ 开发环境

C#

使用 PowerShell 或 Visual Studio Package Manager Console:

Install-Package "Google.Cloud.Kms.V1" -Version "2.0.0-beta03"

使用 dotnet CLI:

dotnet add package "Google.Cloud.Kms.V1" -Version "2.0.0-beta03"

如需了解详情,请参阅设置 C# 开发环境

Go

go get "cloud.google.com/go/kms/apiv1"

如需了解详情,请参阅设置 Go 开发环境

Java

如果您使用的是 Maven,请将以下代码添加到您的 pom.xml 文件中。如需详细了解 BOM,请参阅 Google Cloud Platform 库 BOM

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.37.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-kms</artifactId>
  </dependency>

如果您使用的是 Gradle,请将以下代码添加到您的依赖项中:

implementation 'com.google.cloud:google-cloud-kms:2.44.0'

如果您使用的是 sbt,请将以下代码添加到您的依赖项中:

libraryDependencies += "com.google.cloud" % "google-cloud-kms" % "2.44.0"

如果您使用的是 Visual Studio Code、IntelliJ 或 Eclipse,可以通过以下 IDE 插件将客户端库添加到您的项目中:

上述插件还提供其他功能,例如服务账号密钥管理。如需了解详情,请参阅各个插件相应的文档。

如需了解详情,请参阅设置 Java 开发环境

Node.js

npm install --save "@google-cloud/kms"

如需了解详情,请参阅设置 Node.js 开发环境

PHP

composer require "google/cloud-kms"

如需了解详情,请参阅在 Google Cloud 上使用 PHP

Python

pip install --upgrade "google-cloud-kms"

如需了解详情,请参阅设置 Python 开发环境

Ruby

gem install "google-cloud-kms"

如需了解详情,请参阅设置 Ruby 开发环境

设置身份验证

为了对 Google Cloud API 的调用进行身份验证,客户端库支持应用默认凭据 (ADC);这些库会在一组指定的位置查找凭据,并使用这些凭据对发送到 API 的请求进行身份验证。借助 ADC,您可以在各种环境(例如本地开发或生产环境)中为您的应用提供凭据,而无需修改应用代码。

对于生产环境,设置 ADC 的方式取决于服务和上下文。如需了解详情,请参阅设置应用默认凭据

对于本地开发环境,您可以使用与您的 Google 账号关联的凭据设置 ADC:

  1. 安装并初始化 gcloud CLI

    初始化 gcloud CLI 时,请务必指定您在其中有权访问应用所需的资源的 Google Cloud 项目。

  2. 创建凭据文件:

    gcloud auth application-default login

    登录屏幕随即出现。在您登录后,您的凭据会存储在 ADC 使用的本地凭据文件中。

使用客户端库

以下示例展示了如何使用客户端库。

C++


#include "google/cloud/kms/v1/key_management_client.h"
#include "google/cloud/location.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " project-id location-id\n";
    return 1;
  }

  auto const location = google::cloud::Location(argv[1], argv[2]);

  namespace kms = ::google::cloud::kms_v1;
  auto client = kms::KeyManagementServiceClient(
      kms::MakeKeyManagementServiceConnection());

  for (auto kr : client.ListKeyRings(location.FullName())) {
    if (!kr) throw std::move(kr).status();
    std::cout << kr->DebugString() << "\n";
  }

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

C#


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Kms.V1;

public class QuickstartSample
{
    public void Quickstart(string projectId = "my-project", string locationId = "us-east1")
    {
        // Create a Cloud KMS client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent location name.
        LocationName locationName = new LocationName(projectId, locationId);

        // Iterate over and print each key ring name;
        foreach (KeyRing keyRing in client.ListKeyRings(locationName))
        {
            // ... (e.g. keyRing.Name)
        }
    }
}

Go


// Sample quickstart is a basic program that uses Cloud KMS.
package main

import (
	"context"
	"fmt"
	"log"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"google.golang.org/api/iterator"
)

func main() {
	// GCP project with which to communicate.
	projectID := "your-project-id"

	// Location in which to list key rings.
	locationID := "global"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		log.Fatalf("failed to setup client: %v", err)
	}
	defer client.Close()

	// Create the request to list KeyRings.
	listKeyRingsReq := &kmspb.ListKeyRingsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, locationID),
	}

	// List the KeyRings.
	it := client.ListKeyRings(ctx, listKeyRingsReq)

	// Iterate and print the results.
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatalf("Failed to list key rings: %v", err)
		}

		fmt.Printf("key ring: %s\n", resp.Name)
	}
}

Java

import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyManagementServiceClient.ListKeyRingsPagedResponse;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;
import java.io.IOException;

public class Quickstart {

  public void quickstart() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    quickstart(projectId, locationId);
  }

  public void quickstart(String projectId, String locationId) 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 from the project and location.
      LocationName parent = LocationName.of(projectId, locationId);

      // Call the API.
      ListKeyRingsPagedResponse response = client.listKeyRings(parent);

      // Iterate over each key ring and print its name.
      System.out.println("key rings:");
      for (KeyRing keyRing : response.iterateAll()) {
        System.out.printf("%s%n", keyRing.getName());
      }
    }
  }
}

Node.js

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the location name
const locationName = client.locationPath(projectId, locationId);

async function listKeyRings() {
  const [keyRings] = await client.listKeyRings({
    parent: locationName,
  });

  for (const keyRing of keyRings) {
    console.log(keyRing.name);
  }

  return keyRings;
}

return listKeyRings();

PHP

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

function quickstart(
    string $projectId = 'my-project',
    string $locationId = 'us-east1'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent location name.
    $locationName = $client->locationName($projectId, $locationId);

    // Call the API.
    $listKeyRingsRequest = (new ListKeyRingsRequest())
        ->setParent($locationName);
    $keyRings = $client->listKeyRings($listKeyRingsRequest);

    // Example of iterating over key rings.
    printf('Key rings in %s:' . PHP_EOL, $locationName);
    foreach ($keyRings as $keyRing) {
        printf('%s' . PHP_EOL, $keyRing->getName());
    }

    return $keyRings;
}

Python

from google.cloud import kms
from google.cloud import kms_v1

def quickstart(
    project_id: str, location_id: str
) -> kms_v1.services.key_management_service.pagers.ListKeyRingsPager:
    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent location name.
    location_name = f"projects/{project_id}/locations/{location_id}"

    # Call the API.
    key_rings = client.list_key_rings(request={"parent": location_name})

    # Example of iterating over key rings.
    for key_ring in key_rings:
        print(key_ring.name)

    return key_rings

Ruby

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"

# 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

# Call the API.
key_rings = client.list_key_rings parent: location_name

# Example of iterating over key rings.
puts "Key rings in #{location_name}"
key_rings.each do |key_ring|
  puts key_ring.name
end

后续步骤

了解如何以编程方式加密和解密数据。

其他资源

C++

以下列表包含与 C++ 版客户端库相关的更多资源的链接:

C#

以下列表包含与 C# 版客户端库相关的更多资源的链接:

Go

以下列表包含与 Go 版客户端库相关的更多资源的链接:

Java

以下列表包含与 Java 版客户端库相关的更多资源的链接:

Node.js

以下列表包含与 Node.js 版客户端库相关的更多资源的链接:

PHP

以下列表包含与 PHP 版客户端库相关的更多资源的链接:

Python

以下列表包含与 Python 版客户端库相关的更多资源的链接:

Ruby

以下列表包含与 Ruby 版客户端库相关的更多资源的链接: