Cloud KMS client libraries

This page shows how to get started with the Cloud Client Libraries for theCloud Key Management Service API. Client libraries make it easier to accessGoogle Cloud APIs from a supported language. Although you can useGoogle Cloud APIs directly by making raw requests to the server, clientlibraries provide simplifications that significantly reduce the amount of codeyou need to write.

Read more about the Cloud Client Librariesand the older Google API Client Libraries inClient libraries explained.

Install the client library

C++

SeeSetting up a C++ development environmentfor details about this client library's requirements and install dependencies.

C#

Using PowerShell or the Visual Studio Package Manager Console:

Install-Package"Google.Cloud.Kms.V1"-Version"2.0.0-beta03"

Using the dotnet CLI:

dotnetaddpackage"Google.Cloud.Kms.V1"-Version"2.0.0-beta03"

For more information, seeSetting Up a C# Development Environment.

Go

goget"cloud.google.com/go/kms/apiv1"

For more information, seeSetting Up a Go Development Environment.

Java

If you are usingMaven, addthe following to yourpom.xml file. For more information aboutBOMs, seeThe Google Cloud Platform Libraries BOM.

<dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>libraries-bom</artifactId><version>26.72.0</version><type>pom</type><scope>import</scope></dependency>  </dependencies></dependencyManagement><dependencies>  <dependency>    <groupId>com.google.cloud</groupId><artifactId>google-cloud-kms</artifactId></dependency></dependencies>

If you are usingGradle,add the following to your dependencies:

implementation'com.google.cloud:google-cloud-kms:2.83.0'

If you are usingsbt, addthe following to your dependencies:

libraryDependencies+="com.google.cloud"%"google-cloud-kms"%"2.83.0"

If you're using Visual Studio Code or IntelliJ, 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.

Note: Cloud Java client libraries do not currently support Android.

For more information, seeSetting Up a Java Development Environment.

Node.js

npminstall"@google-cloud/kms"

For more information, seeSetting Up a Node.js Development Environment.

PHP

composerrequire"google/cloud-kms"

For more information, seeUsing PHP on Google Cloud.

Python

pipinstall--upgrade"google-cloud-kms"

For more information, seeSetting Up a Python Development Environment.

Ruby

geminstall"google-cloud-kms"

For more information, seeSetting Up a Ruby Development Environment.

Set up authentication

To authenticate calls to Google Cloud APIs, client libraries supportApplication Default Credentials (ADC);the libraries look for credentials in a set of defined locations and use those credentialsto authenticate requests to the API. With ADC, you can makecredentials available to your application in a variety of environments, such as localdevelopment or production, without needing to modify your application code.

For production environments, the way you set up ADC depends on the serviceand context. For more information, seeSet up Application Default Credentials.

For a local development environment, you can set up ADC with the credentialsthat are associated with your Google Account:

  1. Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:

    gcloudinit

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloudauthapplication-defaultlogin

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    A sign-in screen appears. After you sign in, your credentials are stored in the local credential file used by ADC.

Use the client library

The following example shows how to use the client library.

C++

#include"google/cloud/kms/v1/key_management_client.h"#include"google/cloud/location.h"#include <iostream>intmain(intargc,char*argv[])try{if(argc!=3){std::cerr <<"Usage: " <<argv[0] <<" project-id location-id\n";return1;}autoconstlocation=google::cloud::Location(argv[1],argv[2]);namespacekms=::google::cloud::kms_v1;autoclient=kms::KeyManagementServiceClient(kms::MakeKeyManagementServiceConnection());for(autokr:client.ListKeyRings(location.FullName())){if(!kr)throwstd::move(kr).status();std::cout <<kr->DebugString() <<"\n";}return0;}catch(google::cloud::Statusconst&status){std::cerr <<"google::cloud::Status thrown: " <<status <<"\n";return1;}

C#

usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Kms.V1;publicclassQuickstartSample{publicvoidQuickstart(stringprojectId="my-project",stringlocationId="us-east1"){// Create a Cloud KMS client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent location name.LocationNamelocationName=newLocationName(projectId,locationId);// Iterate over and print each key ring name;foreach(KeyRingkeyRinginclient.ListKeyRings(locationName)){// ... (e.g. keyRing.Name)}}}

Go

// Sample quickstart is a basic program that uses Cloud KMS.packagemainimport("context""fmt""log"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/api/iterator")funcmain(){// GCP project with which to communicate.projectID:="your-project-id"// Location in which to list key rings.locationID:="global"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{log.Fatalf("failed to setup client: %v",err)}deferclient.Close()// Create the request to list KeyRings.listKeyRingsReq:=&kmspb.ListKeyRingsRequest{Parent:fmt.Sprintf("projects/%s/locations/%s",projectID,locationID),}// List the KeyRings.it:=client.ListKeyRings(ctx,listKeyRingsReq)// Iterate and print the results.for{resp,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{log.Fatalf("Failed to list key rings: %v",err)}fmt.Printf("key ring: %s\n",resp.Name)}}

Java

importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.KeyManagementServiceClient.ListKeyRingsPagedResponse;importcom.google.cloud.kms.v1.KeyRing;importcom.google.cloud.kms.v1.LocationName;importjava.io.IOException;publicclassQuickstart{publicvoidquickstart()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";quickstart(projectId,locationId);}publicvoidquickstart(StringprojectId,StringlocationId)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent from the project and location.LocationNameparent=LocationName.of(projectId,locationId);// Call the API.ListKeyRingsPagedResponseresponse=client.listKeyRings(parent);// Iterate over each key ring and print its name.System.out.println("key rings:");for(KeyRingkeyRing:response.iterateAll()){System.out.printf("%s%n",keyRing.getName());}}}}

Node.js

//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the location nameconstlocationName=client.locationPath(projectId,locationId);asyncfunctionlistKeyRings(){const[keyRings]=awaitclient.listKeyRings({parent:locationName,});for(constkeyRingofkeyRings){console.log(keyRing.name);}returnkeyRings;}returnlistKeyRings();

PHP

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\ListKeyRingsRequest;function quickstart(    string $projectId = 'my-project',    string $locationId = 'us-east1') {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the parent location name.    $locationName = $client->locationName($projectId, $locationId);    // Call the API.    $listKeyRingsRequest = (new ListKeyRingsRequest())        ->setParent($locationName);    $keyRings = $client->listKeyRings($listKeyRingsRequest);    // Example of iterating over key rings.    printf('Key rings in %s:' . PHP_EOL, $locationName);    foreach ($keyRings as $keyRing) {        printf('%s' . PHP_EOL, $keyRing->getName());    }    return $keyRings;}

Python

fromgoogle.cloudimportkmsfromgoogle.cloudimportkms_v1defquickstart(project_id:str,location_id:str)->kms_v1.services.key_management_service.pagers.ListKeyRingsPager:# Create the client.client=kms.KeyManagementServiceClient()# Build the parent location name.location_name=f"projects/{project_id}/locations/{location_id}"# Call the API.key_rings=client.list_key_rings(request={"parent":location_name})# Example of iterating over key rings.forkey_ringinkey_rings:print(key_ring.name)returnkey_rings

Ruby

# TODO(developer): uncomment these values before running the sample.# project_id  = "my-project"# location_id = "us-east1"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent location name.location_name=client.location_pathproject:project_id,location:location_id# Call the API.key_rings=client.list_key_ringsparent:location_name# Example of iterating over key rings.puts"Key rings in#{location_name}"key_rings.eachdo|key_ring|putskey_ring.nameend

Next steps

Learn how to programmatically encrypt and decrypt data.

Additional resources

C++

The following list contains links to more resources related to theclient library for C++:

C#

The following list contains links to more resources related to theclient library for C#:

Go

The following list contains links to more resources related to theclient library for Go:

Java

The following list contains links to more resources related to theclient library for Java:

Node.js

The following list contains links to more resources related to theclient library for Node.js:

PHP

The following list contains links to more resources related to theclient library for PHP:

Python

The following list contains links to more resources related to theclient library for Python:

Ruby

The following list contains links to more resources related to theclient library for Ruby:

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-16 UTC.