Cloud KMS Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Key Management Service 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.

Using PowerShell or the Visual Studio Package Manager Console:

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

Using the dotnet CLI:

dotnet add package "Google.Cloud.Kms.V1" -Version "2.0.0-beta03"

Go

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

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

Java

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

Wenn Sie Maven verwenden, fügen Sie Ihrer Datei pom.xml den folgenden Code hinzu. Weitere Informationen zu BOMs finden Sie unter The Google Cloud Platform Libraries BOM.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>16.1.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>

Wenn Sie Gradle verwenden, fügen Sie den Abhängigkeiten Folgendes hinzu:

compile 'com.google.cloud:google-cloud-kms:1.40.2'

Wenn Sie sbt nutzen, fügen Sie den Abhängigkeiten Folgendes hinzu:

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

Bei Verwendung von IntelliJ oder Eclipse können Sie Ihrem Projekt mithilfe der folgenden IDE-Plug-ins Clientbibliotheken hinzufügen:

Diese Plug-ins bieten zusätzliche Funktionen wie die Schlüsselverwaltung für Dienstkonten. Einzelheiten finden Sie in der Dokumentation der einzelnen Plug-ins.

Node.js

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

npm install --save "@google-cloud/kms"

PHP

For more information, see Using PHP on Google Cloud.

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 other ways to authenticate, see the GCP authentication documentation.

Cloud Console

  1. Wechseln Sie in der Cloud Console zur Seite Dienstkontoschlüssel erstellen.

    Zur Seite „Dienstkontoschlüssel erstellen“
  2. Wählen Sie aus der Liste Dienstkonto die Option Neues Dienstkonto aus.
  3. Geben Sie im Feld Dienstkontoname einen Namen ein.
  4. Wählen Sie in der Liste Rolle die Option Projekt > Inhaber

  5. Klicken Sie auf Erstellen. Eine JSON-Datei mit Ihrem Schlüssel wird auf Ihren Computer heruntergeladen.

Befehlszeile

Sie können die folgenden Befehle mithilfe des Cloud SDK auf Ihrem lokalen Computer oder in Cloud Shell ausführen.

  1. Erstellen Sie das Dienstkonto. Ersetzen Sie NAME mit einem Namen für das Dienstkonto.

    gcloud iam service-accounts create NAME
  2. Gewähren Sie dem Dienstkonto Berechtigungen. Geben Sie für PROJECT_ID Ihre Projekt-ID an.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. Erstellen Sie die Schlüsseldatei. Geben Sie für FILE_NAME einen Namen für die Schlüsseldatei an.

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

Die Anmeldedaten zur Authentifizierung für Ihren Anwendungscode geben Sie durch Festlegung der Umgebungsvariable GOOGLE_APPLICATION_CREDENTIALS an. Geben Sie für [PATH] den Dateipfad der JSON-Datei an, die Ihren Dienstkontoschlüssel enthält. Diese Variable gilt nur für Ihre aktuelle Shell-Sitzung. Wenn Sie eine neue Sitzung öffnen, müssen Sie die Variable neu festlegen.

Linux oder macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Beispiel:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

Windows

Mit PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Beispiel:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"

Mit Eingabeaufforderung:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

To learn how to install and use the client library for Cloud KMS, see the Cloud KMS Client Libraries. For more information, see the Cloud KMS C# API reference documentation.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Kms.V1;

public class QuickstartSample
{
    public void Quickstart(string projectId = "my-project", string locationId = "us-east1")
    {
        // Create a Cloud KMS client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent location name.
        LocationName locationName = new LocationName(projectId, locationId);

        // Iterate over and print each key ring name;
        foreach (KeyRing keyRing in client.ListKeyRings(locationName))
        {
            // ... (e.g. keyRing.Name)
        }
    }
}

Go

To learn how to install and use the client library for Cloud KMS, see the Cloud KMS Client Libraries. For more information, see the Cloud KMS Go API reference documentation.


// Sample quickstart is a basic program that uses Cloud KMS.
package main

import (
	"context"
	"fmt"
	"log"

	kms "cloud.google.com/go/kms/apiv1"
	"google.golang.org/api/iterator"
	kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

func main() {
	// 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)
	if err != nil {
		log.Fatalf("failed to setup client: %v", err)
	}

	// 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()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatalf("Failed to list key rings: %v", err)
		}

		fmt.Printf("key ring: %s\n", resp.Name)
	}
}

Java

To learn how to install and use the client library for Cloud KMS, see the Cloud KMS Client Libraries. For more information, see the Cloud KMS Java API reference documentation.

import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyManagementServiceClient.ListKeyRingsPagedResponse;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;
import java.io.IOException;

public class Quickstart {

  public void quickstart() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    quickstart(projectId, locationId);
  }

  public void quickstart(String projectId, String locationId) throws IOException {
    // 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

To learn how to install and use the client library for Cloud KMS, see the Cloud KMS Client Libraries. For more information, see the Cloud KMS Node.js API reference documentation.

//
// 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
const client = new KeyManagementServiceClient();

// Build the location name
const locationName = client.locationPath(projectId, locationId);

async function listKeyRings() {
  const [keyRings] = await client.listKeyRings({
    parent: locationName,
  });

  for (const keyRing of keyRings) {
    console.log(keyRing.name);
  }

  return keyRings;
}

return listKeyRings();

PHP

To learn how to install and use the client library for Cloud KMS, see the Cloud KMS Client Libraries. For more information, see the Cloud KMS PHP API reference documentation.

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

function quickstart_sample(
    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.
    $keyRings = $client->listKeyRings($locationName);

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

To learn how to install and use the client library for Cloud KMS, see the Cloud KMS Client Libraries. For more information, see the Cloud KMS Python API reference documentation.

def quickstart(project_id, location_id):
    # Import the client library.
    from google.cloud import kms

    # 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

To learn how to install and use the client library for Cloud KMS, see the Cloud KMS Client Libraries. For more information, see the Cloud KMS Ruby API reference documentation.

# 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_path project: project_id, location: location_id

# Call the API.
key_rings = client.list_key_rings parent: location_name

# Example of iterating over key rings.
puts "Key rings in #{location_name}"
key_rings.each do |key_ring|
  puts key_ring.name.to_s
end

Next steps

Learn how to programmatically encrypt and decrypt data.

Additional resources