Recuperar uma chave pública

Nesta página, mostramos como recuperar a parte da chave pública de uma versão de chave assimétrica ativada.

A chave pública está no formato Privacy-enhanced Electronic Mail (PEM). Para mais informações, consulte as seções RFC 7468 referentes a Considerações gerais e Codificação textual de informações de chave pública do assunto.

Funções exigidas

Para ter as permissões necessárias para recuperar uma chave pública, peça ao administrador para conceder a você o papel do IAM de Leitor de chaves públicas de CryptoKey do Cloud KMS (roles/cloudkms.publicKeyViewer) na sua chave ou em um recurso pai. Para mais informações sobre como conceder papéis, consulte Gerenciar acesso.

Esse papel predefinido contém as permissões necessárias para recuperar uma chave pública. Para conferir as permissões exatas necessárias, expanda a seção Permissões necessárias:

Permissões necessárias

As permissões a seguir são necessárias para recuperar uma chave pública:

  • cloudkms.cryptoKeyVersions.viewPublicKey
  • cloudkms.locations.get
  • cloudkms.locations.list
  • resourcemanager.projects.get

Talvez você também consiga receber essas permissões com papéis personalizados ou outros papéis predefinidos.

Recuperar uma chave pública

Para fazer o download da chave pública de uma versão de chave assimétrica ativada:

Console

  1. No console do Google Cloud, acesse a página Gerenciamento de chaves.

    Vá para Gerenciamento de chaves

  2. Clique no nome do keyring que contém a chave assimétrica para a qual você quer recuperar a chave pública.

  3. Clique no nome da chave para a qual você quer recuperar a chave pública.

  4. Na linha correspondente à versão da chave para a qual você quer recuperar a chave pública, clique em Ver mais .

  5. Clique em Conseguir chave pública.

  6. A chave pública é exibida no prompt. Você pode copiar a chave pública para a área de transferência. Para fazer o download da chave pública, clique em Fazer download.

Se a opção Receber chave pública não aparecer, verifique o seguinte:

  • A chave é assimétrica.
  • A versão da chave está ativada.
  • Você tem a permissão cloudkms.cryptoKeyVersions.viewPublicKey.

O nome do arquivo de uma chave pública salvo do console do Google Cloud tem o seguinte formato:

KEY_RING-KEY_NAME-KEY_VERSION.pub

Cada parte do nome do arquivo é separada por um hífen, por exemplo, ringname-keyname-version.pub.

gcloud

Para usar o Cloud KMS na linha de comando, primeiro instale ou faça upgrade para a versão mais recente da Google Cloud CLI.

gcloud kms keys versions get-public-key KEY_VERSION \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --output-file OUTPUT_FILE_PATH

Substitua:

  • KEY_VERSION: o número da versão da chave.
  • KEY_NAME: o nome da chave;
  • KEY_RING: o nome do keyring que contém a chave.
  • LOCATION: o local do keyring no Cloud KMS.
  • OUTPUT_FILE_PATH: o caminho em que você quer salvar o arquivo de chave pública. Por exemplo, public-key.pub.

Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help.

C#

Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.


using Google.Cloud.Kms.V1;

public class GetPublicKeySample
{
    public PublicKey GetPublicKey(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        PublicKey result = client.GetPublicKey(keyVersionName);

        // Return the ciphertext.
        return result;
    }
}

Go

Para executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.

import (
	"context"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"hash/crc32"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// getPublicKey retrieves the public key from an asymmetric key pair on
// Cloud KMS.
func getPublicKey(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.GetPublicKeyRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetPublicKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get public key: %w", err)
	}

	// The 'Pem' field is the raw string representation of the public key.
	// Convert 'Pem' into bytes for further processing.
	key := []byte(result.Pem)

	// Optional, but recommended: perform integrity verification on result.
	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
	// https://cloud.google.com/kms/docs/data-integrity-guidelines
	crc32c := func(data []byte) uint32 {
		t := crc32.MakeTable(crc32.Castagnoli)
		return crc32.Checksum(data, t)
	}
	if int64(crc32c(key)) != result.PemCrc32C.Value {
		return fmt.Errorf("getPublicKey: response corrupted in-transit")
	}

	// Optional - parse the public key. This transforms the string key into a Go
	// PublicKey.
	block, _ := pem.Decode(key)
	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return fmt.Errorf("failed to parse public key: %w", err)
	}
	fmt.Fprintf(w, "Retrieved public key: %v\n", publicKey)
	return nil
}

Java

Para executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.

import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.PublicKey;
import java.io.IOException;
import java.security.GeneralSecurityException;

public class GetPublicKey {

  public void getPublicKey() throws IOException, GeneralSecurityException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String keyVersionId = "123";
    getPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Get the public key associated with an asymmetric key.
  public void getPublicKey(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      throws IOException, GeneralSecurityException {
    // 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 key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Get the public key.
      PublicKey publicKey = client.getPublicKey(keyVersionName);
      System.out.printf("Public key: %s%n", publicKey.getPem());
    }
  }
}

Node.js

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function getPublicKey() {
  const [publicKey] = await client.getPublicKey({
    name: versionName,
  });

  // Optional, but recommended: perform integrity verification on publicKey.
  // For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
  // https://cloud.google.com/kms/docs/data-integrity-guidelines
  const crc32c = require('fast-crc32c');
  if (publicKey.name !== versionName) {
    throw new Error('GetPublicKey: request corrupted in-transit');
  }
  if (crc32c.calculate(publicKey.pem) !== Number(publicKey.pemCrc32c.value)) {
    throw new Error('GetPublicKey: response corrupted in-transit');
  }

  console.log(`Public key pem: ${publicKey.pem}`);

  return publicKey;
}

return getPublicKey();

PHP

Para executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\GetPublicKeyRequest;

function get_public_key(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key',
    string $versionId = '123'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key version name.
    $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);

    // Call the API.
    $getPublicKeyRequest = (new GetPublicKeyRequest())
        ->setName($keyVersionName);
    $publicKey = $client->getPublicKey($getPublicKeyRequest);
    printf('Public key: %s' . PHP_EOL, $publicKey->getPem());

    return $publicKey;
}

Python

Para executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.

from google.cloud import kms

def get_public_key(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
) -> kms.PublicKey:
    """
    Get the public key for an asymmetric key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        version_id (string): ID of the key to use (e.g. '1').

    Returns:
        PublicKey: Cloud KMS public key response.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key version name.
    key_version_name = client.crypto_key_version_path(
        project_id, location_id, key_ring_id, key_id, version_id
    )

    # Call the API.
    public_key = client.get_public_key(request={"name": key_version_name})

    # Optional, but recommended: perform integrity verification on public_key.
    # For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
    # https://cloud.google.com/kms/docs/data-integrity-guidelines
    if not public_key.name == key_version_name:
        raise Exception("The request sent to the server was corrupted in-transit.")
    # See crc32c() function defined below.
    if not public_key.pem_crc32c == crc32c(public_key.pem.encode("utf-8")):
        raise Exception(
            "The response received from the server was corrupted in-transit."
        )
    # End integrity verification

    print(f"Public key: {public_key.pem}")
    return public_key

def crc32c(data: bytes) -> int:
    """
    Calculates the CRC32C checksum of the provided data.
    Args:
        data: the bytes over which the checksum should be calculated.
    Returns:
        An int representing the CRC32C checksum of the provided bytes.
    """
    import crcmod  # type: ignore

    crc32c_fun = crcmod.predefined.mkPredefinedCrcFun("crc-32c")
    return crc32c_fun(data)

Ruby

Para executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"
# version_id  = "123"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the key version name.
key_version_name = client.crypto_key_version_path project:            project_id,
                                                  location:           location_id,
                                                  key_ring:           key_ring_id,
                                                  crypto_key:         key_id,
                                                  crypto_key_version: version_id

# Call the API.
public_key = client.get_public_key name: key_version_name
puts "Public key: #{public_key.pem}"

API

Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.

Recupere a chave pública chamando o método CryptoKeyVersions.getPublicKey.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION/publicKey" \
    --request "GET" \
    --header "authorization: Bearer TOKEN"

Substitua:

  • PROJECT_ID: o ID do projeto que contém o keyring.
  • LOCATION: o local do keyring no Cloud KMS.
  • KEY_RING: o nome do keyring que contém a chave.
  • KEY_NAME: o nome da chave;
  • KEY_VERSION: o número da versão da chave.

A saída será parecida com esta:

{
  "pem": "-----BEGIN PUBLIC KEY-----\nQ29uZ3JhdHVsYXRpb25zLCB5b3UndmUgZGlzY292ZX
          JlZCB0aGF0IHRoaXMgaXNuJ3QgYWN0dWFsbHkgYSBwdWJsaWMga2V5ISBIYXZlIGEgbmlj
          ZSBkYXkgOik=\n-----END PUBLIC KEY-----\n",
  "algorithm": "ALGORITHM",
  "pemCrc32c": "2561089887",
  "name": "projects/PROJECT_ID/locations/LOCATION/keyRings/
           KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/
           KEY_VERSION",
  "protectionLevel": "SOFTWARE"
}