Cloud KMS Client Libraries

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

Client libraries for more languages are coming soon.

Installing the client library

C#

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

If you are using Maven, add this to your pom.xml file:

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

If you are using Gradle, add this to your dependencies:

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

Node.js

npm install --save googleapis

PHP

composer require google/apiclient

Python

pip install --upgrade google-api-python-client

Ruby

gem install google-api-client

Using the client library

To run the client library, you must first set up authentication.

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."); }
        }
    }
}
Read more in the C# API Reference Documentation for the Google Cloud KMS Client Library.

Go

import (
	"fmt"
	"log"

	"golang.org/x/net/context"
	"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)
	}
}
Read more in the Go API Reference Documentation for the Google Cloud KMS Client Library.

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.");
    }
  }
}
Read more in the Java API Reference Documentation for the Google Cloud KMS Client Library.

Node.js

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

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

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

// Acquires credentials
google.auth.getApplicationDefault((err, authClient) => {
  if (err) {
    console.error('Failed to acquire credentials');
    return;
  }

  if (authClient.createScopedRequired && authClient.createScopedRequired()) {
    authClient = authClient.createScoped([
      'https://www.googleapis.com/auth/cloud-platform'
    ]);
  }

  // Instantiates an authorized client
  const cloudkms = google.cloudkms({
    version: 'v1',
    auth: authClient
  });
  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.keyRings || [];

    if (keyRings.length) {
      console.log('Key rings:');
      result.keyRings.forEach((keyRing) => console.log(keyRing.name));
    } else {
      console.log(`No key rings found.`);
    }
  });
});
Read more in the Node.js API Reference Documentation for the Google Cloud KMS Client Library.

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;
}
Read more in the PHP API Reference Documentation for the Google Cloud KMS Client Library.

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.')
Read more in the Python API Reference Documentation for the Google Cloud KMS Client Library.

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
Read more in the Ruby API Reference Documentation for the Google Cloud KMS Client Library.

Additional Resources

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud KMS Documentation