Retrieving a public key

You can retrieve the public key portion of an asymmetric key version by using the Google Cloud Console, the gcloud command-line tool, and the Cloud Key Management Service API.

The public key is in the Privacy-enhanced Electronic Mail (PEM) format. For more information, see the RFC 7468 sections for General Considerations and Textual Encoding of Subject Public Key Info.

The user or service that will retrieve the public key requires cloudkms.cryptoKeyVersions.viewPublicKey permission on the key version. You can learn about permissions in the Cloud KMS beta release at Permissions and Roles.

To download the public key for an existing asymmetric key version:

Web UI

  1. Go to the Cryptographic Keys page in the Cloud Console.

    Go to the Cryptographic Keys page

  2. Click the name of the key ring that contains the asymmetric key for which you want to retrieve the public key.

  3. Click on the name of the key for which you want to retrieve the public key.

  4. On the row corresponding to the key version for which you want to retrieve the public key, click View More .

  5. Click Get public key.

  6. The public key is displayed in the prompt. You can copy the public key to your clipboard. To download the public key, click Download.

If you do not see the Get public key option, verify the key is an asymmetric key and that you have the cloudkms.cryptoKeyVersions.viewPublicKey permission.

The file name of a public key downloaded from the Cloud Console is of the form:

[key-ring]-[key-name]-[key-version].pub

Each portion of the file name is separated by a hyphen.

Command-line

To use Cloud KMS on the command line, first Install or upgrade to the latest version of Cloud SDK.

gcloud kms keys versions get-public-key key-version \
    --key key \
    --keyring key-ring-name \
    --location location \
    --output-file public-key.pub

Replace key-version with the key version. Replace key with the name of the key. Replace key-ring with the name of the key ring where the key is stored. Replace location with the Cloud KMS location for the key ring. Replace public-key.pub with the file path to save the public key.

For information on all flags and possible values, run the command with the --help flag.

C#

To run this code, first set up a C# development environment and install the Cloud KMS C# SDK.


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

To run this code, first set up a Go development environment and install the Cloud KMS Go SDK.

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

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

// getPublicKey retrieves the public key from an asymmetric key pair on
// Cloud KMS.
func getPublicKey(w io.Writer, name string) error {
	// parent := "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: %v", err)
	}

	// 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: %v", err)
	}

	// The 'Pem' field is the raw string representation of the public key.
	key := result.Pem

	//
	// Optional - parse the public key. This transforms the string key into a Go
	// PublicKey.
	//

	block, _ := pem.Decode([]byte(key))
	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return fmt.Errorf("failed to parse public key: %v", err)
	}
	fmt.Fprintf(w, "Retrieved public key: %v\n", publicKey)
	return nil
}

Java

To run this code, first set up a Java development environment and install the Cloud KMS Java SDK.

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

To run this code, first set up a Node.js development environment and install the Cloud KMS Node.js SDK.

//
// 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,
  });

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

  return publicKey;
}

return getPublicKey();

PHP

To run this code, first learn about using PHP on Google Cloud and install the Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

function get_public_key_sample(
    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.
    $publicKey = $client->getPublicKey($keyVersionName);
    printf('Public key: %s' . PHP_EOL, $publicKey->getPem());
    return $publicKey;
}

Python

To run this code, first set up a Python development environment and install the Cloud KMS Python SDK.

def get_public_key(project_id, location_id, key_ring_id, key_id, version_id):
    """
    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.

    """

    # Import the client library.
    from google.cloud import kms

    # 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})
    print('Public key: {}'.format(public_key.pem))
    return public_key

Ruby

To run this code, first set up a Ruby development environment and install the Cloud KMS Ruby SDK.

# 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

These examples use curl as an HTTP client to demonstrate using the API. For more information about access control, see Accessing the Cloud KMS API.

Retrieve the public key by calling the CryptoKeyVersions.getPublicKey method.