Cloud KMS 客户端库

本页面介绍了如何开始使用 Cloud KMS API 的 Google API 客户端库。如需详细了解 Cloud API 客户端库,请参阅客户端库说明

安装客户端库

C#

如需了解详情,请参阅设置 C# 开发环境。在 Visual Studio 2013/2015 中,打开 Package Manager Console 并运行以下命令:
Install-Package Google.Apis.CloudKMS.v1

Go

go get -u google.golang.org/api/cloudkms/v1

Java

如需了解详情,请参阅设置 Java 开发环境。如果您使用的是 Maven,请将以下内容添加到您的 pom.xml 文件中:

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-cloudkms</artifactId>
    <version>v1-rev71-1.25.0</version>
</dependency>

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

compile group: 'com.google.apis', name: 'google-api-services-cloudkms', version: 'v1-rev71-1.25.0'

Node.js

如需了解详情,请参阅设置 Node.js 开发环境
npm install --save googleapis

PHP

composer require google/apiclient

Python

如需了解详情,请参阅设置 Python 开发环境
pip install --upgrade google-api-python-client

Ruby

如需了解详情,请参阅设置 Ruby 开发环境
gem install google-api-client

设置身份验证

要运行客户端库,必须先通过创建服务帐号并设置环境变量来设置身份验证。完成以下步骤即可设置身份验证。如需了解详情,请参阅 GCP 身份验证文档

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]

使用客户端库

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

C#

如需查看使用 Visual Studio 构建和运行此示例 C# 代码的说明,请参阅 README.md
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
// Imports the Google Cloud KMS client library
using Google.Apis.CloudKMS.v1;
using Google.Apis.CloudKMS.v1.Data;
using System.Linq;

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.
            string parent = $"projects/{projectId}/locations/{location}";

            // Authorize the client using Application Default Credentials.
            // See: https://developers.google.com/identity/protocols/application-default-credentials
            GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
            // Specify the Cloud Key Management Service scope.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    Google.Apis.CloudKMS.v1.CloudKMSService.Scope.CloudPlatform
                });
            }
            // Instantiate the Cloud Key Management Service API.
            CloudKMSService cloudKms = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled = false
            });

            // List key rings.
            ListKeyRingsResponse result = cloudKms.Projects.Locations.KeyRings.List(parent).Execute();
            if (result.KeyRings != null)
            {
                Console.WriteLine("Key Rings: ");
                result.KeyRings.ToList().ForEach(response => Console.WriteLine(response.Name));
            }
            else { Console.WriteLine("No Key Rings found."); }
        }
    }
}

Go

import (
	"context"
	"fmt"
	"log"

	"golang.org/x/oauth2/google"
	cloudkms "google.golang.org/api/cloudkms/v1"
)

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

	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	client, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		log.Fatal(err)
	}

	// Create the KMS client.
	kmsService, err := cloudkms.New(client)
	if err != nil {
		log.Fatal(err)
	}

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

	// Make the RPC call.
	response, err := kmsService.Projects.Locations.KeyRings.List(parentName).Do()
	if err != nil {
		log.Fatalf("Failed to list key rings: %v", err)
	}

	// Print the returned key rings.
	for _, keyRing := range response.KeyRings {
		fmt.Printf("KeyRing: %q\n", keyRing.Name)
	}
}

Java

// Imports the Google Cloud client library

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudkms.v1.CloudKMS;
import com.google.api.services.cloudkms.v1.CloudKMSScopes;
import com.google.api.services.cloudkms.v1.model.KeyRing;
import com.google.api.services.cloudkms.v1.model.ListKeyRingsResponse;
import java.io.IOException;

public class Quickstart {
  /**
   * Creates an authorized CloudKMS client service using Application Default Credentials.
   *
   * @return an authorized CloudKMS client
   * @throws IOException if there's an error getting the default credentials.
   */
  public static CloudKMS createAuthorizedClient() throws IOException {
    // Create the credential
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    // Authorize the client using Application Default Credentials
    // @see https://g.co/dv/identity/protocols/application-default-credentials
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
    // Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the scope if required.
    if (credential.createScopedRequired()) {
      credential = credential.createScoped(CloudKMSScopes.all());
    }

    return new CloudKMS.Builder(transport, jsonFactory, credential)
        .setApplicationName("CloudKMS snippets")
        .build();
  }

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

    // Create the Cloud KMS client.
    CloudKMS kms = createAuthorizedClient();

    // The resource name of the cryptoKey
    String keyRingPath = String.format(
        "projects/%s/locations/%s",
        projectId, location);

    // Make the RPC call
    ListKeyRingsResponse response = kms.projects().locations()
        .keyRings()
        .list(keyRingPath)
        .execute();

    // Print the returned key rings
    if (null != response.getKeyRings()) {
      System.out.println("Key Rings: ");
      for (KeyRing keyRing : response.getKeyRings()) {
        System.out.println(keyRing.getName());
      }
    } else {
      System.out.println("No key rings defined.");
    }
  }
}

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';

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

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

// The resource name of the location associated with the KeyRings
$parent = sprintf('projects/%s/locations/%s', $projectId, $location);

// Instantiate the client
$client = new Google_Client();

// Authorize the client using Application Default Credentials
// @see https://developers.google.com/identity/protocols/application-default-credentials
$client->useApplicationDefaultCredentials();

// Set the required scopes to access the Key Management Service API
$client->setScopes(array(
    'https://www.googleapis.com/auth/cloud-platform'
));

// Instantiate the Key Management Service API
$kms = new Google_Service_CloudKMS($client);

// list all key rings for your project
$keyRings = $kms->projects_locations_keyRings->listProjectsLocationsKeyRings(
    $projectId,
    array('parent' => $parent)
);

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

Python

# Imports the Google APIs client library
import googleapiclient.discovery

# 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.
kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

# The resource name of the location associated with the key rings.
parent = 'projects/{}/locations/{}'.format(project_id, location)

# Lists key rings
request = kms_client.projects().locations().keyRings().list(parent=parent)
response = request.execute()

if 'keyRings' in response and response['keyRings']:
    print('Key rings:')
    for key_ring in response['keyRings']:
        print(key_ring['name'])
else:
    print('No key rings found.')

Ruby

# Imports the Google Cloud KMS API client
require "google/apis/cloudkms_v1"

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

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

# Instantiate the client
Cloudkms   = Google::Apis::CloudkmsV1 # Alias the module
kms_client = Cloudkms::CloudKMSService.new

# Set the required scopes to access the Key Management Service API
# @see https://developers.google.com/identity/protocols/application-default-credentials#callingruby
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the location associated with the key rings
parent = "projects/#{project_id}/locations/#{location_id}"

# Request list of key rings
response = kms_client.list_project_location_key_rings parent

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

其他资源

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud KMS 文档