Librerie client di Cloud KMS

Questa pagina mostra come iniziare a utilizzare le librerie client di Cloud per l'API Cloud Key Management Service. Le librerie client semplificano l'accesso alle API Google Cloud da un linguaggio supportato. Sebbene sia possibile utilizzare le API Google Cloud direttamente inviando richieste non elaborate al server, le librerie client offrono semplificazioni che riducono notevolmente la quantità di codice da scrivere.

Per ulteriori informazioni sulle librerie client di Cloud e sulle librerie client delle API di Google precedenti, consulta Spiegazioni sulle librerie client.

installa la libreria client

C++

Per i dettagli sui requisiti di questa libreria client e sull'installazione delle dipendenze, consulta Configurazione di un ambiente di sviluppo C++.

C#

Utilizzando PowerShell o la console del gestore di pacchetti di Visual Studio:

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

Utilizzando l'interfaccia a riga di comando dotnet:

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

Per ulteriori informazioni, consulta la sezione Configurazione di un ambiente di sviluppo C#.

Go

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

Per ulteriori informazioni, consulta la sezione Configurazione di un ambiente di sviluppo Go.

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.37.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-kms</artifactId>
  </dependency>

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

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

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

libraryDependencies += "com.google.cloud" % "google-cloud-kms" % "2.44.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.

Per ulteriori informazioni, consulta la sezione Configurazione di un ambiente di sviluppo Java.

Node.js

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

Per ulteriori informazioni, consulta la sezione Configurare un ambiente di sviluppo Node.js.

PHP

composer require "google/cloud-kms"

Per ulteriori informazioni, consulta Utilizzo di PHP su Google Cloud.

Python

pip install --upgrade "google-cloud-kms"

Per ulteriori informazioni, consulta la sezione Configurazione di un ambiente di sviluppo Python.

Ruby

gem install "google-cloud-kms"

Per ulteriori informazioni, consulta la sezione Configurazione di un ambiente di sviluppo Ruby.

Configura l'autenticazione

Per autenticare le chiamate alle API di Google Cloud, le librerie client supportano le credenziali predefinite dell'applicazione (ADC); le librerie cercano le credenziali in un insieme di località definite e le utilizzano per autenticare le richieste all'API. Con ADC, puoi rendere disponibili le credenziali per la tua applicazione in diversi ambienti, ad esempio lo sviluppo o la produzione locale, senza dover modificare il codice dell'applicazione.

Per gli ambienti di produzione, il modo in cui configuri ADC dipende dal servizio e dal contesto. Per ulteriori informazioni, vedi Configurare le credenziali predefinite dell'applicazione.

Per un ambiente di sviluppo locale, puoi configurare ADC con le credenziali associate al tuo Account Google:

  1. Installa e inizializza gcloud CLI.

    Quando inizializza gcloud CLI, assicurati di specificare un progetto Google Cloud in cui disponi dell'autorizzazione per accedere alle risorse necessarie per la tua applicazione.

  2. Crea il file delle credenziali:

    gcloud auth application-default login

    Viene visualizzata una schermata di accesso. Dopo aver eseguito l'accesso, le tue credenziali vengono archiviate nel file delle credenziali locali utilizzato da ADC.

Utilizzare la libreria client

Nell'esempio seguente viene illustrato come utilizzare la libreria client.

C++


#include "google/cloud/kms/v1/key_management_client.h"
#include "google/cloud/location.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " project-id location-id\n";
    return 1;
  }

  auto const location = google::cloud::Location(argv[1], argv[2]);

  namespace kms = ::google::cloud::kms_v1;
  auto client = kms::KeyManagementServiceClient(
      kms::MakeKeyManagementServiceConnection());

  for (auto kr : client.ListKeyRings(location.FullName())) {
    if (!kr) throw std::move(kr).status();
    std::cout << kr->DebugString() << "\n";
  }

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

C#


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


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

import (
	"context"
	"fmt"
	"log"

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

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)
	}
	defer client.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()
		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

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

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

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

from google.cloud import kms
from google.cloud import kms_v1

def quickstart(
    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_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
end

Passaggi successivi

Scopri come criptare e decriptare i dati in modo programmatico.

Risorse aggiuntive

C++

Il seguente elenco contiene i link ad altre risorse correlate alla libreria client per C++:

C#

Il seguente elenco contiene link ad altre risorse relative alla libreria client per C#:

Go

Il seguente elenco contiene i link ad altre risorse correlate alla libreria client di Go:

Java

Il seguente elenco contiene i link ad altre risorse correlate alla libreria client per Java:

Node.js

Il seguente elenco contiene i link ad altre risorse relative alla libreria client per Node.js:

PHP

Il seguente elenco contiene i link ad altre risorse correlate alla libreria client per PHP:

Python

Il seguente elenco contiene i link ad altre risorse relative alla libreria client per Python:

Ruby

Il seguente elenco contiene i link ad altre risorse relative alla libreria client per Ruby: