Cloud KMS Client Libraries

This page shows how to get started with the Google APIs Client Libraries for the Cloud Key Management Service API. Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Installing the client library

C#

For more information, see Setting Up a C# Development Environment.

In Visual Studio 2013/2015, open the Package Manager Console and run this command:
Install-Package Google.Cloud.Kms.V1 -Version 1.0.0-beta04

Go

For more information, see Setting Up a Go Development Environment.

go get -u cloud.google.com/go/kms/apiv1

Java

For more information, see Setting Up a Java Development Environment.

如果您使用的是 Maven,请将以下代码添加到您的 pom.xml 文件中:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-kms</artifactId>
  <version>1.34.0</version>
</dependency>
如果您使用的是 Gradle,请将以下代码添加到您的依赖项中:
compile 'com.google.cloud:google-cloud-kms:1.34.0'
如果您使用的是 SBT,请将以下代码添加到您的依赖项中:
libraryDependencies += "com.google.cloud" % "google-cloud-kms" % "1.34.0"

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

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

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/kms

PHP

For more information, see Using PHP on Google Cloud.

composer require google/cloud-kms

Python

For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-kms

Ruby

For more information, see Setting Up a Ruby Development Environment.

gem install google-cloud-kms

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

GCP Console

  1. 在 GCP Console 中,转到创建服务帐号密钥页面。

    转到“创建服务帐号密钥”页面
  2. 服务帐号列表中,选择新的服务帐号
  3. 服务帐号名称字段中,输入一个名称。
  4. 角色列表中,选择项目 > 所有者

    注意角色字段为您的服务帐号授予资源访问权限。稍后您可以使用 GCP Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > 所有者更为精细的权限。如需了解详情,请参阅为服务帐号授予角色
  5. 点击创建。包含密钥的 JSON 文件就会下载到计算机。

命令行

您可以使用本地机器上的 Cloud SDK 或在 Cloud Shell 中运行以下命令。

  1. 创建服务帐号。将 [NAME] 替换为服务帐号的名称。

    gcloud iam service-accounts create [NAME]
  2. 向服务帐号授予权限。将 [PROJECT_ID] 替换为您的项目 ID。

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    注意角色字段为您的服务帐号授予资源访问权限。稍后您可以使用 GCP Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > 所有者更为精细的权限。如需了解详情,请参阅为服务帐号授予角色
  3. 生成密钥文件。将 [FILE_NAME] 替换为密钥文件的名称。

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

通过设置环境变量 GOOGLE_APPLICATION_CREDENTIALS,向您的应用代码提供身份验证凭据。将 [PATH] 替换为包含服务帐号密钥的 JSON 文件的文件路径,将 [FILE_NAME] 替换为文件名。此变量仅适用于当前的 shell 会话,因此,如果您打开新的会话,请重新设置该变量。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

使用命令提示符:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

See README.md for instructions on using Visual Studio to build and run this sample C# code.

using System;
using System.Linq;
// Imports the Google Cloud KMS client library
using Google.Cloud.Kms.V1;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";

            // Lists keys in the "global" location.
            string location = "global";

            // The resource name of the location associated with the key rings.
            LocationName locationName = new LocationName(projectId, location);

            // Instantiate a Cloud KMS client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // List key rings.
            foreach (KeyRing keyRing in client.ListKeyRings(locationName))
            {
                Console.WriteLine(keyRing.Name);
            }
        }
    }
}

Go


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

import (
	"context"
	"fmt"
	"log"

	cloudkms "cloud.google.com/go/kms/apiv1"
	"google.golang.org/api/iterator"
	kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

func main() {
	projectID := "your-project-id"
	// Location of the key rings.
	locationID := "global"

	// Create the KMS client.
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// The resource name of the key rings.
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Build the request.
	req := &kmspb.ListKeyRingsRequest{
		Parent: parent,
	}
	// Query the API.
	it := client.ListKeyRings(ctx, req)

	// Iterate and print 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("KeyRing: %q\n", resp.Name)
	}
}

Java

// Imports the Google Cloud client library

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;

public class Quickstart {

  public static void main(String... args) throws Exception {
    String projectId = args[0];
    // The location of the Key Rings
    String location = args[1];

    // Create the KeyManagementServiceClient using try-with-resources to manage client cleanup.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

      // The resource name of the location to search
      String locationPath = LocationName.format(projectId, location);

      // Make the RPC call
      ListKeyRingsPagedResponse response = client.listKeyRings(locationPath);

      // Iterate over all KeyRings (which may cause more result pages to be loaded automatically)
      for (KeyRing keyRing : response.iterateAll()) {
        System.out.println("Found KeyRing: " + keyRing.getName());
      }
    }
  }
}

Node.js

async function quickstart(
  projectId = 'your-project-id' // Your GCP projectId
) {
  // Imports the @google-cloud/kms client library
  const kms = require('@google-cloud/kms');

  // Instantiates an authorized client
  const client = new kms.KeyManagementServiceClient();

  // Lists keys in the "global" location.
  const locationId = 'global';

  // Lists key rings
  const parent = client.locationPath(projectId, locationId);
  const [keyRings] = await client.listKeyRings({parent});

  // Display the results
  if (keyRings.length) {
    console.log('Key rings:');
    keyRings.forEach(keyRing => console.log(keyRing.name));
  } else {
    console.log(`No key rings found.`);
  }
}

PHP

// Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

// Import the Google Cloud KMS client library.
use Google\Cloud\Kms\V1\KeyManagementServiceClient;

// Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

// Lists keys in the "global" location. Could also be "us-west1", etc.
$locationId = 'global';

// Instantiate the client
$kms = new KeyManagementServiceClient();

$locationName = $kms->locationName($projectId, $locationId);

// list all key rings for your project
$keyRings = $kms->listKeyRings($locationName);

// Print the key rings
echo 'Key Rings: ' . PHP_EOL;
foreach ($keyRings as $keyRing) {
    echo $keyRing->getName() . PHP_EOL;
}

Python

# Imports the Google APIs client library
from google.cloud import kms_v1

# Your Google Cloud Platform project ID
project_id = 'YOUR_PROJECT_ID'

# Lists keys in the "global" location.
location = 'global'

# Creates an API client for the KMS API.
client = kms_v1.KeyManagementServiceClient()

# The resource name of the location associated with the key rings.
parent = client.location_path(project_id, location)

# Lists key rings
response = client.list_key_rings(parent)
response_list = list(response)

if len(response_list) > 0:
    print('Key rings:')
    for key_ring in response_list:
        print(key_ring.name)
else:
    print('No key rings found.')

Ruby

# Imports the Google Cloud KMS API client
require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

# Lists keys in the "global" location.
location_id = "global"

# Instantiate the client
client = CloudKMS::KeyManagementServiceClient.new

# The resource name of the location associated with the key rings
parent = CloudKMS::KeyManagementServiceClient.location_path project_id, location_id

# Request list of key rings
response = client.list_key_rings parent

# List all key rings for your project
puts "Key Rings: "
response.each do |key_ring|
  puts key_ring.name
end

Next steps

Learn how to programmatically encrypt and decrypt data.

Additional resources