Cloud HSM

This topic provides an overview of Cloud HSM and shows you how to create anduse HSM-protected encryption keys in Cloud Key Management Service.

What is Cloud HSM?

Cloud HSM is a cloud-hosted Hardware Security Module (HSM) service thatallows you to host encryption keys and perform cryptographic operations in acluster ofFIPS 140-2 Level 3 certified HSMs. Googlemanages the HSM cluster for you, so you don't need to worry about clustering,scaling, or patching. Because Cloud HSM uses Cloud KMS asits front end, you can leverage all the conveniences and features thatCloud KMS provides.

Note: When you use HSM-backed keys and key versions for cryptographicoperations, the Google Cloud project that makes the cryptographic requestincurscryptographic operation quota usage, and the Google Cloudproject that contains the HSM keys incursHSM QPM quota usage. For moreinformation about Cloud KMS, seeQuotas.

Create a key ring

When you create a key, you add it to a key ring in a given Google Cloudlocation. You can create a new key ring or use an existing one. In this topic,you create a new key ring and add a new key to it.

Create a key ring in a Google Cloudlocation that supportsCloud HSM.

Note: Key rings with the same name can exist in differentlocations, so you must always specify thelocation.

Console

  1. Go to theKey Management page in the Google Cloud console.

    Go to Key Management

  2. ClickCreate key ring.

  3. ForKey ring name, enter a name for your key ring.

  4. ForKey ring location, select a location like"us-east1".

    Note: Choose a location that is near the resources you want to protect.For CMEK usage, your key ring should be in the same location as the resourcesyou use it with. For Cloud EKM keys, the location must be physicallyclose to your external key manager (EKM) vendor.
  5. ClickCreate.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

  2. In your environment, run thegcloud kms keyrings create command:

    gcloudkmskeyringscreateKEY_RING\--locationLOCATION

    Replace the following:

    • KEY_RING: the name of the key ring that contains the key.
    • LOCATION: the Cloud KMS location of the key ring.

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

C#

To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.

usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Kms.V1;publicclassCreateKeyRingSample{publicKeyRingCreateKeyRing(stringprojectId="my-project",stringlocationId="us-east1",stringid="my-key-ring"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent location name.LocationNamelocationName=newLocationName(projectId,locationId);// Build the key ring.KeyRingkeyRing=newKeyRing{};// Call the API.KeyRingresult=client.CreateKeyRing(locationName,id,keyRing);// Return the result.returnresult;}}

Go

To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.

import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// createKeyRing creates a new ring to store keys on KMS.funccreateKeyRing(wio.Writer,parent,idstring)error{// parent := "projects/PROJECT_ID/locations/global"// id := "my-key-ring"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.CreateKeyRingRequest{Parent:parent,KeyRingId:id,}// Call the API.result,err:=client.CreateKeyRing(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create key ring: %w",err)}fmt.Fprintf(w,"Created key ring: %s\n",result.Name)returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.

importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.KeyRing;importcom.google.cloud.kms.v1.LocationName;importjava.io.IOException;publicclassCreateKeyRing{publicvoidcreateKeyRing()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";Stringid="my-asymmetric-signing-key";createKeyRing(projectId,locationId,id);}// Create a new key ring.publicvoidcreateKeyRing(StringprojectId,StringlocationId,Stringid)throwsIOException{// 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(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent name from the project and location.LocationNamelocationName=LocationName.of(projectId,locationId);// Build the key ring to create.KeyRingkeyRing=KeyRing.newBuilder().build();// Create the key ring.KeyRingcreatedKeyRing=client.createKeyRing(locationName,id,keyRing);System.out.printf("Created key ring %s%n",createdKeyRing.getName());}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.

//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const id = 'my-key-ring';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the parent location nameconstlocationName=client.locationPath(projectId,locationId);asyncfunctioncreateKeyRing(){const[keyRing]=awaitclient.createKeyRing({parent:locationName,keyRingId:id,});console.log(`Created key ring:${keyRing.name}`);returnkeyRing;}returncreateKeyRing();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\CreateKeyRingRequest;use Google\Cloud\Kms\V1\KeyRing;function create_key_ring(    string $projectId = 'my-project',    string $locationId = 'us-east1',    string $id = 'my-key-ring'): KeyRing {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the parent location name.    $locationName = $client->locationName($projectId, $locationId);    // Build the key ring.    $keyRing = new KeyRing();    // Call the API.    $createKeyRingRequest = (new CreateKeyRingRequest())        ->setParent($locationName)        ->setKeyRingId($id)        ->setKeyRing($keyRing);    $createdKeyRing = $client->createKeyRing($createKeyRingRequest);    printf('Created key ring: %s' . PHP_EOL, $createdKeyRing->getName());    return $createdKeyRing;}

Python

To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.

fromgoogle.cloudimportkmsdefcreate_key_ring(project_id:str,location_id:str,key_ring_id:str)->kms.CryptoKey:"""    Creates a new key ring in Cloud KMS    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 key ring to create (e.g. 'my-key-ring').    Returns:        KeyRing: Cloud KMS key ring.    """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent location name.location_name=f"projects/{project_id}/locations/{location_id}"# Build the key ring.key_ring={}# Call the API.created_key_ring=client.create_key_ring(request={"parent":location_name,"key_ring_id":key_ring_id,"key_ring":key_ring,})print(f"Created key ring:{created_key_ring.name}")returncreated_key_ring

Ruby

To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.

# TODO(developer): uncomment these values before running the sample.# project_id  = "my-project"# location_id = "us-east1"# id = "my-key-ring"# 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_pathproject:project_id,location:location_id# Build the key ring.key_ring={}# Call the API.created_key_ring=client.create_key_ringparent:location_name,key_ring_id:id,key_ring:key_ringputs"Created key ring:#{created_key_ring.name}"

API

These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings?key_ring_id=KEY_RING" \    --request "POST" \    --header "authorization: BearerTOKEN"

Replace the following:

  • PROJECT_ID: the ID of the project that contains the key ring.
  • KEY_RING: the name of the key ring that contains the key.
  • LOCATION: the Cloud KMS location of the key ring.

See theKeyRing.create API documentationfor more information.

Create a key

Follow these steps to create a Cloud HSM key on the specified key ringand location.

Console

  1. Go to theKey Management page in the Google Cloud console.

    Go to the Key Management page

  2. Click the name of the key ring for which you will create a key.

  3. ClickCreate key.

  4. In theWhat type of key do you want to create?, chooseGeneratedkey.

  5. In theKey name field, enter the name for your key.

  6. Click theProtection level dropdown and selectHSM.

  7. Click thePurpose dropdown and selectSymmetric encrypt/decrypt.

  8. Accept the default values forRotation period andStarting on.

  9. ClickCreate.

gcloud

To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.

gcloud kms keys createkey \    --keyringkey-ring \    --locationlocation \--purpose "encryption" \--protection-level "hsm"

Replacekey with a name for the new key. Replacekey-ringwith the name of the existing key ring where the key will be located. Replacelocation with the Cloud KMS location for the key ring.

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

C#

To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.

usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf.WellKnownTypes;publicclassCreateKeyHsmSample{publicCryptoKeyCreateKeyHsm(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringid="my-hsm-encryption-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent key ring name.KeyRingNamekeyRingName=newKeyRingName(projectId,locationId,keyRingId);// Build the key.CryptoKeykey=newCryptoKey{Purpose=CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,VersionTemplate=newCryptoKeyVersionTemplate{ProtectionLevel=ProtectionLevel.Hsm,Algorithm=CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration=newDuration{Seconds=24*60*60,}};// Call the API.CryptoKeyresult=client.CreateCryptoKey(keyRingName,id,key);// Return the result.returnresult;}}

Go

To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.

import("context""fmt""io""time"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/durationpb")// createKeyHSM creates a new symmetric encrypt/decrypt key on Cloud KMS.funccreateKeyHSM(wio.Writer,parent,idstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-hsm-encryption-key"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.CreateCryptoKeyRequest{Parent:parent,CryptoKeyId:id,CryptoKey:&kmspb.CryptoKey{Purpose:kmspb.CryptoKey_ENCRYPT_DECRYPT,VersionTemplate:&kmspb.CryptoKeyVersionTemplate{ProtectionLevel:kmspb.ProtectionLevel_HSM,Algorithm:kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration:durationpb.New(24*time.Hour),},}// Call the API.result,err:=client.CreateCryptoKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create key: %w",err)}fmt.Fprintf(w,"Created key: %s\n",result.Name)returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.

importcom.google.cloud.kms.v1.CryptoKey;importcom.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;importcom.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;importcom.google.cloud.kms.v1.CryptoKeyVersionTemplate;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.KeyRingName;importcom.google.cloud.kms.v1.ProtectionLevel;importcom.google.protobuf.Duration;importjava.io.IOException;publicclassCreateKeyHsm{publicvoidcreateKeyHsm()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-hsm-key";createKeyHsm(projectId,locationId,keyRingId,id);}// Create a new key that is stored in an HSM.publicvoidcreateKeyHsm(StringprojectId,StringlocationId,StringkeyRingId,Stringid)throwsIOException{// 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(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent name from the project, location, and key ring.KeyRingNamekeyRingName=KeyRingName.of(projectId,locationId,keyRingId);// Build the hsm key to create.CryptoKeykey=CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setProtectionLevel(ProtectionLevel.HSM).setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))// Optional: customize how long key versions should be kept before destroying..setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24*60*60)).build();// Create the key.CryptoKeycreatedKey=client.createCryptoKey(keyRingName,id,key);System.out.printf("Created hsm key %s%n",createdKey.getName());}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall 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 id = 'my-hsm-encryption-key';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the parent key ring nameconstkeyRingName=client.keyRingPath(projectId,locationId,keyRingId);asyncfunctioncreateKeyHsm(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'ENCRYPT_DECRYPT',versionTemplate:{algorithm:'GOOGLE_SYMMETRIC_ENCRYPTION',protectionLevel:'HSM',},// Optional: customize how long key versions should be kept before// destroying.destroyScheduledDuration:{seconds:60*60*24},},});console.log(`Created hsm key:${key.name}`);returnkey;}returncreateKeyHsm();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;use Google\Cloud\Kms\V1\CryptoKey;use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;use Google\Cloud\Kms\V1\ProtectionLevel;use Google\Protobuf\Duration;function create_key_hsm(    string $projectId = 'my-project',    string $locationId = 'us-east1',    string $keyRingId = 'my-key-ring',    string $id = 'my-hsm-key'): CryptoKey {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the parent key ring name.    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);    // Build the key.    $key = (new CryptoKey())        ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)        ->setVersionTemplate((new CryptoKeyVersionTemplate())            ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)            ->setProtectionLevel(ProtectionLevel::HSM)        )        // Optional: customize how long key versions should be kept before destroying.        ->setDestroyScheduledDuration((new Duration())            ->setSeconds(24 * 60 * 60)        );    // Call the API.    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())        ->setParent($keyRingName)        ->setCryptoKeyId($id)        ->setCryptoKey($key);    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);    printf('Created hsm key: %s' . PHP_EOL, $createdKey->getName());    return $createdKey;}

Python

To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.

importdatetimefromgoogle.cloudimportkmsfromgoogle.protobufimportduration_pb2# type: ignoredefcreate_key_hsm(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:"""    Creates a new key in Cloud KMS backed by Cloud HSM.    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 create (e.g. 'my-hsm-key').    Returns:        CryptoKey: Cloud KMS key.    """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key ring name.key_ring_name=client.key_ring_path(project_id,location_id,key_ring_id)# Build the key.purpose=kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPTalgorithm=(kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION)protection_level=kms.ProtectionLevel.HSMkey={"purpose":purpose,"version_template":{"algorithm":algorithm,"protection_level":protection_level,},# Optional: customize how long key versions should be kept before# destroying."destroy_scheduled_duration":duration_pb2.Duration().FromTimedelta(datetime.timedelta(days=1)),}# Call the API.created_key=client.create_crypto_key(request={"parent":key_ring_name,"crypto_key_id":key_id,"crypto_key":key})print(f"Created hsm key:{created_key.name}")returncreated_key

Ruby

To run this code, firstset up a Ruby development environment andinstall 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"# id          = "my-hsm-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key ring name.key_ring_name=client.key_ring_pathproject:project_id,location:location_id,key_ring:key_ring_id# Build the key.key={purpose::ENCRYPT_DECRYPT,version_template:{algorithm::GOOGLE_SYMMETRIC_ENCRYPTION,protection_level::HSM},# Optional: customize how long key versions should be kept before destroying.destroy_scheduled_duration:{seconds:24*60*60}}# Call the API.created_key=client.create_crypto_keyparent:key_ring_name,crypto_key_id:id,crypto_key:keyputs"Created hsm key:#{created_key.name}"

Encrypt data

Now that you have a key, you can use that key to encrypt text or binary content.

gcloud

To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.

gcloud kms encrypt \    --keyKEY_NAME \    --keyringKEY_RING \    --locationLOCATION  \    --plaintext-fileFILE_TO_ENCRYPT \    --ciphertext-fileENCRYPTED_OUTPUT

Replace the following:

  • KEY_NAME: the name of the key that you want to use for encryption.
  • KEY_RING: the name of the key ring that contains the key.
  • LOCATION: the Cloud KMS location that contains the keyring.
  • FILE_TO_ENCRYPT: the path to the file that you want toencrypt.
  • ENCRYPTED_OUTPUT: the path where you want to save theencrypted output.

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

C#

To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.

usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf;usingSystem.Text;publicclassEncryptSymmetricSample{publicbyte[]EncryptSymmetric(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringmessage="Sample message"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key name.CryptoKeyNamekeyName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// Convert the message into bytes. Cryptographic plaintexts and// ciphertexts are always byte arrays.byte[]plaintext=Encoding.UTF8.GetBytes(message);// Call the API.EncryptResponseresult=client.Encrypt(keyName,ByteString.CopyFrom(plaintext));// Return the ciphertext.returnresult.Ciphertext.ToByteArray();}}

Go

To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.

import("context""fmt""hash/crc32""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/wrapperspb")// encryptSymmetric encrypts the input plaintext with the specified symmetric// Cloud KMS key.funcencryptSymmetric(wio.Writer,namestring,messagestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// message := "Sample message"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Convert the message into bytes. Cryptographic plaintexts and// ciphertexts are always byte arrays.plaintext:=[]byte(message)// Optional but recommended: Compute plaintext's CRC32C.crc32c:=func(data[]byte)uint32{t:=crc32.MakeTable(crc32.Castagnoli)returncrc32.Checksum(data,t)}plaintextCRC32C:=crc32c(plaintext)// Build the request.req:=&kmspb.EncryptRequest{Name:name,Plaintext:plaintext,PlaintextCrc32C:wrapperspb.Int64(int64(plaintextCRC32C)),}// Call the API.result,err:=client.Encrypt(ctx,req)iferr!=nil{returnfmt.Errorf("failed to encrypt: %w",err)}// 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-guidelinesifresult.VerifiedPlaintextCrc32C==false{returnfmt.Errorf("Encrypt: request corrupted in-transit")}ifint64(crc32c(result.Ciphertext))!=result.CiphertextCrc32C.Value{returnfmt.Errorf("Encrypt: response corrupted in-transit")}fmt.Fprintf(w,"Encrypted ciphertext: %s",result.Ciphertext)returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.

importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.EncryptResponse;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.protobuf.ByteString;importjava.io.IOException;publicclassEncryptSymmetric{publicvoidencryptSymmetric()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";Stringplaintext="Plaintext to encrypt";encryptSymmetric(projectId,locationId,keyRingId,keyId,plaintext);}// Encrypt data with a given key.publicvoidencryptSymmetric(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,Stringplaintext)throwsIOException{// 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(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the key version name from the project, location, key ring, key,// and key version.CryptoKeyNamekeyVersionName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Encrypt the plaintext.EncryptResponseresponse=client.encrypt(keyVersionName,ByteString.copyFromUtf8(plaintext));System.out.printf("Ciphertext: %s%n",response.getCiphertext().toStringUtf8());}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall 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';// const plaintextBuffer = Buffer.from('...');// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key nameconstkeyName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);// Optional, but recommended: compute plaintext's CRC32C.constcrc32c=require('fast-crc32c');constplaintextCrc32c=crc32c.calculate(plaintextBuffer);asyncfunctionencryptSymmetric(){const[encryptResponse]=awaitclient.encrypt({name:keyName,plaintext:plaintextBuffer,plaintextCrc32c:{value:plaintextCrc32c,},});constciphertext=encryptResponse.ciphertext;// Optional, but recommended: perform integrity verification on encryptResponse.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinesif(!encryptResponse.verifiedPlaintextCrc32c){thrownewError('Encrypt: request corrupted in-transit');}if(crc32c.calculate(ciphertext)!==Number(encryptResponse.ciphertextCrc32c.value)){thrownewError('Encrypt: response corrupted in-transit');}console.log(`Ciphertext:${ciphertext.toString('base64')}`);returnciphertext;}returnencryptSymmetric();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\EncryptRequest;function encrypt_symmetric(    string $projectId = 'my-project',    string $locationId = 'us-east1',    string $keyRingId = 'my-key-ring',    string $keyId = 'my-key',    string $plaintext = '...') {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the key name.    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);    // Call the API.    $encryptRequest = (new EncryptRequest())        ->setName($keyName)        ->setPlaintext($plaintext);    $encryptResponse = $client->encrypt($encryptRequest);    printf('Ciphertext: %s' . PHP_EOL, $encryptResponse->getCiphertext());    return $encryptResponse;}

Python

To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.

# Import base64 for printing the ciphertext.importbase64# Import the client library.fromgoogle.cloudimportkmsdefencrypt_symmetric(project_id:str,location_id:str,key_ring_id:str,key_id:str,plaintext:str)->bytes:"""    Encrypt plaintext using a symmetric 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').        plaintext (string): message to encrypt    Returns:        bytes: Encrypted ciphertext.    """# Convert the plaintext to bytes.plaintext_bytes=plaintext.encode("utf-8")# Optional, but recommended: compute plaintext's CRC32C.# See crc32c() function defined below.plaintext_crc32c=crc32c(plaintext_bytes)# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# Call the API.encrypt_response=client.encrypt(request={"name":key_name,"plaintext":plaintext_bytes,"plaintext_crc32c":plaintext_crc32c,})# Optional, but recommended: perform integrity verification on encrypt_response.# For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:# https://cloud.google.com/kms/docs/data-integrity-guidelinesifnotencrypt_response.verified_plaintext_crc32c:raiseException("The request sent to the server was corrupted in-transit.")ifnotencrypt_response.ciphertext_crc32c==crc32c(encrypt_response.ciphertext):raiseException("The response received from the server was corrupted in-transit.")# End integrity verificationprint(f"Ciphertext:{base64.b64encode(encrypt_response.ciphertext)}")returnencrypt_responsedefcrc32c(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.    """importcrcmod# type: ignorecrc32c_fun=crcmod.predefined.mkPredefinedCrcFun("crc-32c")returncrc32c_fun(data)

Ruby

To run this code, firstset up a Ruby development environment andinstall 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"# plaintext  = "..."# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Call the API.response=client.encryptname:key_name,plaintext:plaintextputs"Ciphertext:#{Base64.strict_encode64response.ciphertext}"

API

These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.

When using JSON and the REST API, content must be base64 encoded before it canbe encrypted by Cloud KMS.

Tip: You can base64-encode or decode datausing thebase64 command on Linux or macOS, or theBase64.exe command on Windows. Programming and scriptinglanguages typically include libraries for base64-encoding. For command-lineexamples, seeBase64 Encoding in theCloud Vision API documentation.

To encrypt data, make aPOST request and provide the appropriate project andkey information and specify the base64 encoded text to be encrypted in theplaintext field of the request body.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME:encrypt" \  --request "POST" \  --header "authorization: BearerTOKEN" \  --header "content-type: application/json" \  --data "{\"plaintext\": \"PLAINTEXT_TO_ENCRYPT\"}"

Replace the following:

  • PROJECT_ID: the ID of the project that contains the key ring andkey that you want to use for encryption.
  • LOCATION: the Cloud KMS location that contains the keyring.
  • KEY_RING: the key ring that contains the key that you want to usefor encryption.
  • KEY_NAME: the name of the key that you want to use for encryption.
  • PLAINTEXT_TO_ENCRYPT: the plaintext data that you wantto encrypt. The plaintext must be base64 encoded before you call theencrypt method.

Here is an example payload with base64 encoded data:

{"plaintext":"U3VwZXIgc2VjcmV0IHRleHQgdGhhdCBtdXN0IGJlIGVuY3J5cHRlZAo=",}

Decrypt ciphertext

To decrypt encrypted content, you must use the same key that was used to encryptthe content.

gcloud

To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.

gcloud kms decrypt \    --keyKEY_NAME \    --keyringKEY_RING \    --locationLOCATION  \    --ciphertext-fileFILE_TO_DECRYPT \    --plaintext-fileDECRYPTED_OUTPUT

Replace the following:

  • KEY_NAME: the name of the key that you want to use for decryption.
  • KEY_RING: the name of the key ring that contains the key.
  • LOCATION: the Cloud KMS location that contains the keyring.
  • FILE_TO_DECRYPT: the path to the file that you want todecrypt.
  • DECRYPTED_OUTPUT: the path where you want to save thedecrypted output.

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

C#

To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.

usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf;usingSystem.Text;publicclassDecryptSymmetricSample{publicstringDecryptSymmetric(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",byte[]ciphertext=null){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key name.CryptoKeyNamekeyName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// Call the API.DecryptResponseresult=client.Decrypt(keyName,ByteString.CopyFrom(ciphertext));// Get the plaintext. Cryptographic plaintexts and ciphertexts are// always byte arrays.byte[]plaintext=result.Plaintext.ToByteArray();// Return the result.returnEncoding.UTF8.GetString(plaintext);}}

Go

To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.

import("context""fmt""hash/crc32""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/wrapperspb")// decryptSymmetric will decrypt the input ciphertext bytes using the specified symmetric key.funcdecryptSymmetric(wio.Writer,namestring,ciphertext[]byte)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// ciphertext := []byte("...")  // result of a symmetric encryption call// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Optional, but recommended: Compute ciphertext's CRC32C.crc32c:=func(data[]byte)uint32{t:=crc32.MakeTable(crc32.Castagnoli)returncrc32.Checksum(data,t)}ciphertextCRC32C:=crc32c(ciphertext)// Build the request.req:=&kmspb.DecryptRequest{Name:name,Ciphertext:ciphertext,CiphertextCrc32C:wrapperspb.Int64(int64(ciphertextCRC32C)),}// Call the API.result,err:=client.Decrypt(ctx,req)iferr!=nil{returnfmt.Errorf("failed to decrypt ciphertext: %w",err)}// 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-guidelinesifint64(crc32c(result.Plaintext))!=result.PlaintextCrc32C.Value{returnfmt.Errorf("Decrypt: response corrupted in-transit")}fmt.Fprintf(w,"Decrypted plaintext: %s",result.Plaintext)returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.

importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.DecryptResponse;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.protobuf.ByteString;importjava.io.IOException;publicclassDecryptSymmetric{publicvoiddecryptSymmetric()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";byte[]ciphertext=null;decryptSymmetric(projectId,locationId,keyRingId,keyId,ciphertext);}// Decrypt data that was encrypted using a symmetric key.publicvoiddecryptSymmetric(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,byte[]ciphertext)throwsIOException{// 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(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the key version name from the project, location, key ring, and// key.CryptoKeyNamekeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Decrypt the response.DecryptResponseresponse=client.decrypt(keyName,ByteString.copyFrom(ciphertext));System.out.printf("Plaintext: %s%n",response.getPlaintext().toStringUtf8());}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall 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';// Ciphertext must be either a Buffer object or a base-64 encoded string// const ciphertext = Buffer.from('...');// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key nameconstkeyName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);// Optional, but recommended: compute ciphertext's CRC32C.constcrc32c=require('fast-crc32c');constciphertextCrc32c=crc32c.calculate(ciphertext);asyncfunctiondecryptSymmetric(){const[decryptResponse]=awaitclient.decrypt({name:keyName,ciphertext:ciphertext,ciphertextCrc32c:{value:ciphertextCrc32c,},});// Optional, but recommended: perform integrity verification on decryptResponse.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinesif(crc32c.calculate(decryptResponse.plaintext)!==Number(decryptResponse.plaintextCrc32c.value)){thrownewError('Decrypt: response corrupted in-transit');}constplaintext=decryptResponse.plaintext.toString();console.log(`Plaintext:${plaintext}`);returnplaintext;}returndecryptSymmetric();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\DecryptRequest;function decrypt_symmetric(    string $projectId = 'my-project',    string $locationId = 'us-east1',    string $keyRingId = 'my-key-ring',    string $keyId = 'my-key',    string $ciphertext = '...') {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the key name.    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);    // Call the API.    $decryptRequest = (new DecryptRequest())        ->setName($keyName)        ->setCiphertext($ciphertext);    $decryptResponse = $client->decrypt($decryptRequest);    printf('Plaintext: %s' . PHP_EOL, $decryptResponse->getPlaintext());    return $decryptResponse;}

Python

To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.

fromgoogle.cloudimportkmsdefdecrypt_symmetric(project_id:str,location_id:str,key_ring_id:str,key_id:str,ciphertext:bytes)->kms.DecryptResponse:"""    Decrypt the ciphertext using the symmetric 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').        ciphertext (bytes): Encrypted bytes to decrypt.    Returns:        DecryptResponse: Response including plaintext.    """# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# Optional, but recommended: compute ciphertext's CRC32C.# See crc32c() function defined below.ciphertext_crc32c=crc32c(ciphertext)# Call the API.decrypt_response=client.decrypt(request={"name":key_name,"ciphertext":ciphertext,"ciphertext_crc32c":ciphertext_crc32c,})# Optional, but recommended: perform integrity verification on decrypt_response.# For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:# https://cloud.google.com/kms/docs/data-integrity-guidelinesifnotdecrypt_response.plaintext_crc32c==crc32c(decrypt_response.plaintext):raiseException("The response received from the server was corrupted in-transit.")# End integrity verificationprint(f"Plaintext:{decrypt_response.plaintext!r}")returndecrypt_responsedefcrc32c(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.    """importcrcmod# type: ignorecrc32c_fun=crcmod.predefined.mkPredefinedCrcFun("crc-32c")returncrc32c_fun(data)

Ruby

To run this code, firstset up a Ruby development environment andinstall 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"# ciphertext  = "..."# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Call the API.response=client.decryptname:key_name,ciphertext:ciphertextputs"Plaintext:#{response.plaintext}"

API

These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.

Decrypted text that is returned in the JSON from Cloud KMS isbase64 encoded.

Tip: You can base64-encode or decode datausing thebase64 command on Linux or macOS, or theBase64.exe command on Windows. Programming and scriptinglanguages typically include libraries for base64-encoding. For command-lineexamples, seeBase64 Encoding in theCloud Vision API documentation.

To decrypt encrypted data, make aPOST request and provide the appropriateproject and key information and specify the encrypted text (also known asciphertext) to be decrypted in theciphertext field of the request body.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME:decrypt" \  --request "POST" \  --header "authorization: BearerTOKEN" \  --header "content-type: application/json" \  --data "{\"ciphertext\": \"ENCRYPTED_DATA\"}"

Replace the following:

  • PROJECT_ID: the ID of the project that contains the key ring andkey that you want to use for decryption.
  • LOCATION: the Cloud KMS location that contains the keyring.
  • KEY_RING: the key ring that contains the key that you want to usefor decryption.
  • KEY_NAME: the name of the key that you want to use for decryption.
  • ENCRYPTED_DATA: the encrypted data that you wantto decrypt.

Here is an example payload with base64 encoded data:

{"ciphertext":"CiQAhMwwBo61cHas7dDgifrUFs5zNzBJ2uZtVFq4ZPEl6fUVT4kSmQ...",}

Next steps

Known limitations

  • Message size is limited to 8 KiB (as opposed to 64 KiB forCloud KMS software keys) for user-provided plaintext andciphertext, including theadditional authenticated data.

  • Cloud HSM may not be available in certain multi or dual regions.For details, seeSupported regions for Cloud HSM.

  • If you use Cloud HSM keys with customer-managed encryption key(CMEK) integrations in other Google Cloud services, the locations youuse for the services must match the locations of your Cloud HSMkeys exactly. This applies to regional, dual-regional, and multi-regionallocations.

    For more information about CMEK integrations, see the relevant section ofEncryption at rest.

  • Currently key operations for asymmetric keys stored in Cloud HSMmay incur a noticeably greater latency compared to usingCloud KMS software keys.

Bare Metal Rack HSM

Google Cloud offers additional HSM options, such as single-tenancy.Bare Metal Rack HSM is available for customers to host their own HSMsin Google-provided space. Inquire with your account representative foradditional information.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-16 UTC.