Cloud KMS Client Libraries

This page shows how to get started with the Google APIs Client Libraries for the Cloud KMS 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

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

Java

For more information, see Setting Up a Java Development Environment. If you are using Maven, add the following to your pom.xml file:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-kms</artifactId>
  <version>1.18.0</version>
</dependency>
If you are using Gradle, add the following to your dependencies:
compile 'com.google.cloud:google-cloud-kms:1.18.0'
If you are using SBT, add the following to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-kms" % "1.18.0"

If you're using IntelliJ or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/kms

PHP

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 more information, see the GCP authentication documentation .

GCP Console

  1. In the GCP Console, go to the Create service account key page.

    Go to the Create Service Account Key page
  2. From the Service account list, select New service account.
  3. In the Service account name field, enter a name.
  4. From the Role list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using the GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Command line

You can run the following commands using the Cloud SDK on your local machine, or in Cloud Shell.

  1. Create the service account. Replace [NAME] with a name for the service account.

    gcloud iam service-accounts create [NAME]
  2. Grant permissions to the service account. Replace [PROJECT_ID] with your project ID.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. Replace [FILE_NAME] with a name for the key file.

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

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

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

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

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

With command prompt:

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.
	parentName := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Build the request.
	req := &kmspb.ListKeyRingsRequest{
		Parent: parentName,
	}
	// 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.api.gax.core.CredentialsProvider;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.auth.Credentials;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyManagementServiceClient.ListKeyRingsPagedResponse;
import com.google.cloud.kms.v1.KeyManagementServiceSettings;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;

import java.io.IOException;

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

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...

Cloud KMS Documentation