Retrieving a public key

You can retrieve the public key portion of an asymmetric key version by using the Google Cloud Platform Console, the gcloud command-line tool, and the Cloud KMS 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.

Console

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

  1. Open the Cryptographic Keys page in the GCP Console.
  2. Click the name of the key ring that contains the asymmetric key.
  3. Click the name of the key that contains the key version.
  4. For the key version whose public key you want to retrieve, click the More icon (3 vertical dots).
  5. Click Get public key. The public key is displayed, and you can copy the public key to your clipboard or download the public key. (If you do not see the Get public key option, verify the key is an asymmetric key, and verify you have the cloudkms.cryptoKeyVersions.viewPublicKey permission.)

    Public key

The file name of a public key downloaded from the GCP Console is of the form [KEY_RING]-[KEY]-[CRYPTO_KEY_VERSION].pub.

Command-line

gcloud alpha kms keys versions \
  get-public-key [CRYPTO_KEY_VERSION] \
  --location [LOCATION] \
  --keyring [KEY_RING] \
  --key [KEY] \
  --output-file ~/mykey.pub

API

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

Specify the resource ID of the key version for the public key you want to retrieve.

Go

func getAsymmetricPublicKey(ctx context.Context, client *cloudkms.Service, keyPath string) (interface{}, error) {
	response, err := client.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions.
		GetPublicKey(keyPath).Context(ctx).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to fetch public key: %+v", err)
	}
	keyBytes := []byte(response.Pem)
	block, _ := pem.Decode(keyBytes)
	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to parse public key: %+v", err)
	}
	return publicKey, nil
}

Java

/**
 * Retrieves the public key from a saved asymmetric key pair on Cloud KMS 
 *
 * Requires:
 *   java.io.StringReader
 *   java.security.KeyFactory
 *   java.security.PublicKey
 *   java.security.Security
 *   java.security.spec.X509EncodedKeySpec
 *   org.bouncycastle.jce.provider.BouncyCastleProvider
 *   org.bouncycastle.util.io.pem.PemReader
 */
public static PublicKey getAsymmetricPublicKey(CloudKMS client, String keyPath) 
    throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, 
    NoSuchProviderException {
  Security.addProvider(new BouncyCastleProvider());
  com.google.api.services.cloudkms.v1.model.PublicKey response;
  response = client.projects()
                   .locations()
                   .keyRings()
                   .cryptoKeys()
                   .cryptoKeyVersions()
                   .getPublicKey(keyPath)
                   .execute();
  PemReader reader = new PemReader(new StringReader(response.getPem()));
  byte[] pem = reader.readPemObject().getContent();
  X509EncodedKeySpec abstractKey = new X509EncodedKeySpec(pem);
  try {
    return KeyFactory.getInstance("RSA", "BC").generatePublic(abstractKey);
  } catch (InvalidKeySpecException e) {
    return KeyFactory.getInstance("ECDSA", "BC").generatePublic(abstractKey);
  }
}

Python

def getAsymmetricPublicKey(client, key_path):
    """
    Retrieves the public key from a saved asymmetric key pair on Cloud KMS

    Requires:
      cryptography.hazmat.backends.default_backend
      cryptography.hazmat.primitives.serialization
    """
    request = client.projects() \
                    .locations() \
                    .keyRings() \
                    .cryptoKeys() \
                    .cryptoKeyVersions() \
                    .getPublicKey(name=key_path)
    response = request.execute()
    key_txt = response['pem'].encode('ascii')
    key = serialization.load_pem_public_key(key_txt, default_backend())
    return key

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud KMS Documentation