Cloud KMS client libraries

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

Read more about the Cloud Client Libraries and the older Google API Client Libraries in Client libraries explained.

Install the client library

C++

See Setting up a C++ development environment for 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, see Setting Up a C# Development Environment.

Go

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

For more information, see Setting Up a Go Development Environment.

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.70.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 using Gradle, add the following to your dependencies:

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

If you are using sbt, add the following to your dependencies:

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

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

For more information, see Setting Up a Java Development Environment.

Node.js

npminstall"@google-cloud/kms"

For more information, see Setting Up a Node.js Development Environment.

PHP

composerrequire"google/cloud-kms"

For more information, see Using PHP on Google Cloud.

Python

pipinstall--upgrade"google-cloud-kms"

For more information, see Setting Up a Python Development Environment.

Ruby

geminstall"google-cloud-kms"

For more information, see Setting Up a Ruby Development Environment.

Set up authentication

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

For production environments, the way you set up ADC depends on the service and context. For more information, see Set up Application Default Credentials.

For a local development environment, you can set up ADC with the credentials that 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.
KeyManagementServiceClient client=KeyManagementServiceClient .Create ();
// Build the parent location name.
LocationName locationName=newLocationName (projectId,locationId);
// Iterate over and print each key ring name;
foreach(KeyRing keyRinginclient.ListKeyRings (locationName))
{
// ... (e.g. keyRing.Name)
}
}
}

Go


// Sample quickstart is a basic program that uses Cloud KMS.
packagemain
import(
"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;
publicclass Quickstart{
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(KeyManagementServiceClient client=KeyManagementServiceClient .create()){
// Build the parent from the project and location.
LocationName parent=LocationName .of(projectId,locationId);
// Call the API.
ListKeyRingsPagedResponse response=client.listKeyRings(parent);
// Iterate over each key ring and print its name.
System.out.println("key rings:");
for(KeyRing keyRing: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 library
const{KeyManagementServiceClient}=require('@google-cloud/kms');
// Instantiates a client
constclient=newKeyManagementServiceClient ();
// Build the location name
constlocationName=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.cloudimport kms
fromgoogle.cloudimport kms_v1
defquickstart(
 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.
 for key_ring in key_rings:
 print(key_ring.name)
 return key_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.name
end

Next steps

Learn how to programmatically encrypt and decrypt data.

Additional resources

C++

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

C#

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

Go

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

Java

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

Node.js

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

PHP

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

Python

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

Ruby

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

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

Last updated 2025年10月30日 UTC.