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.Apis.CloudKMS.v1

Go

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

Java

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

If you're using IntelliJ or Eclipse, you can add client libraries to your project using these 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 googleapis

PHP

composer require google/apiclient

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-api-python-client

Ruby

For more information, see Setting Up a Ruby Development Environment.
gem install google-api-client

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 drop-down list, select New service account.
  3. In the Service account name field, enter a name .
  4. From the Role drop-down 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 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 within Cloud Shell.

  1. Create the service account. Replace [NAME] with your desired service account name.

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

// Imports the Google APIs client library
const {google} = require('googleapis');

// Your Google Cloud Platform project ID
const projectId = process.env.GCLOUD_PROJECT;

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

// Acquires credentials
google.auth
  .getClient({scopes: ['https://www.googleapis.com/auth/cloud-platform']})
  .then(auth => {
    // Instantiates an authorized client
    const cloudkms = google.cloudkms({
      version: 'v1',
      auth,
    });
    const request = {
      parent: `projects/${projectId}/locations/${location}`,
    };

    // Lists key rings
    cloudkms.projects.locations.keyRings.list(request, (err, result) => {
      if (err) {
        console.error(err);
        return;
      }

      const keyRings = result.data.keyRings || [];

      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

Additional Resources

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud KMS Documentation