Encrypting and decrypting data with a symmetric key

This topic shows you how to do the following:

  • Encrypt text or binary content (plaintext) by using a Cloud KMS key.
  • Decrypt ciphertext that was encrypted with a Cloud KMS key.

Setup

  • Before you encrypt or decrypt data, you must create a key ring and a key as described in Creating key rings and keys.

    For security reasons, the raw cryptographic key material represented by a Cloud KMS key can never be viewed or exported. It can only be used by an authorized user to encrypt or decrypt data when they invoke the Cloud KMS API.

  • Ensure the user that is calling the encrypt and decrypt methods has the cloudkms.cryptoKeyVersions.useToEncrypt and cloudkms.cryptoKeyVersions.useToDecrypt permissions on the key used to encrypt or decrypt.

    One way to permit a user to encrypt or decrypt using a key is to add the user to the roles/cloudkms.cryptoKeyEncrypter, roles/cloudkms.cryptoKeyDecrypter, or roles/cloudkms.cryptoKeyEncrypterDecrypter IAM roles for that key. For more information, see Permissions and Roles.

  • If you are going to use the client libraries for Cloud KMS, then install the client library for your preferred language.

  • If you are going to use the gcloud command-line tool for Cloud KMS, then install the Cloud SDK.

Encrypt

Command-line

To encrypt data, provide the appropriate key information, specify the name of the plaintext file to encrypt, and specify the name of the file that will contain the encrypted content.

gcloud kms encrypt \
  --location=[LOCATION]  \
  --keyring=[KEY_RING] \
  --key=[KEY] \
  --plaintext-file=[FILEPATH_AND_FILENAME_TO_ENCRYPT] \
  --ciphertext-file=[FILEPATH_AND_FILENAME].enc

For example, if text.txt is the name of the plaintext file to encrypt:

gcloud kms encrypt \
  --location global \
  --keyring my_keyring \
  --key my_key \
  --plaintext-file text.txt \
  --ciphertext-file text.enc

The plaintext file must not be larger than 64 KiB.

The encrypt command supports an optional --additional-authenticated-data- file flag to specify a file that contains additional authenticated data. The additional authenticated data file must not be larger than 64 KiB.

If --plaintext-file or --additional-authenticated-data-file is set to -, that file is read from stdin. Similarly, if --ciphertext-file is set to -, the ciphertext is written to stdout.

The encrypt command supports an optional --version flag to indicate the version of the key to use for encryption. By default, the primary version is used.

The following encrypt example shows how to specify a version key and additional authenticated data.

gcloud kms encrypt \
  --location=[LOCATION]  \
  --keyring=[KEY_RING] \
  --key=[KEY] \
  --version=[KEY_VERSION] \
  --additional-authenticated-data-file=[ADDITIONAL_AUTHENTICATED_DATA_FILEPATH_AND_FILENAME] \
  --plaintext-file=[FILEPATH_AND_FILENAME_TO_ENCRYPT] \
  --ciphertext-file=[FILEPATH_AND_FILENAME].enc

Protocol

Content to be encrypted that is sent to Cloud KMS in JSON must be base64-encoded. For information on encoding and decoding using base64, see Base64 Encoding.

To encrypt data, make a POST request and provide the appropriate project and key information and specify the base64-encoded text to be encrypted in the plaintext field of the request body. Replace API_KEY with a valid API key. For information on generating an API key, see Accessing the API.

POST https://cloudkms.googleapis.com/v1/projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[keyring_name]/cryptoKeys/[key_name]:encrypt&key=API_KEY
{
  "plaintext": "U3VwZXIgc2VjcmV0IHRleHQgdGhhdCBtdXN0IGJlIGVuY3J5cHRlZAo=",
}

Here is an example using curl:

curl -s -X POST "https://cloudkms.googleapis.com/v1/projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING_NAME]/cryptoKeys/[KEY_NAME]:encrypt" \
  -d "{\"plaintext\":\"[BASE64_ENCODED_INPUT]\"}" \
  -H "Authorization:Bearer [API_KEY]"\
  -H "Content-Type:application/json"

C#

        public static void Encrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId,
string plaintextFile, string ciphertextFile)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            byte[] plaintext = File.ReadAllBytes(plaintextFile);
            CryptoKeyPathName pathName = CryptoKeyPathName.Parse(cryptoKeyName.ToString());
            EncryptResponse result = client.Encrypt(pathName, ByteString.CopyFrom(plaintext));

            // Output encrypted data to a file.
            File.WriteAllBytes(ciphertextFile, result.Ciphertext.ToByteArray());
            Console.Write($"Encrypted file created: {ciphertextFile}");
        }

Go

// encrypt will encrypt the input plaintext with the specified symmetric key
// example keyName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID"
func encryptSymmetric(keyName string, plaintext []byte) ([]byte, error) {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return nil, err
	}

	// Build the request.
	req := &kmspb.EncryptRequest{
		Name:      keyName,
		Plaintext: plaintext,
	}
	// Call the API.
	resp, err := client.Encrypt(ctx, req)
	if err != nil {
		return nil, err
	}
	return resp.Ciphertext, nil
}

Java

/**
 * Encrypts the given plaintext using the specified crypto key.
 */
public static byte[] encrypt(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] plaintext)
    throws IOException {

  // Create the KeyManagementServiceClient using try-with-resources to manage client cleanup.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey
    String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);

    // Encrypt the plaintext with Cloud KMS.
    EncryptResponse response = client.encrypt(resourceName, ByteString.copyFrom(plaintext));

    // Extract the ciphertext from the response.
    return response.getCiphertext().toByteArray();
  }
}

Node.js

async function encrypt(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
  plaintextFileName = './path/to/plaintext.txt',
  ciphertextFileName = './path/to/plaintext.txt.encrypted'
) {
  const fs = require('fs');
  const {promisify} = require('util');

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring, e.g. "global"
  const locationId = 'global';

  // Reads the file to be encrypted
  const readFile = promisify(fs.readFile);
  const contentsBuffer = await readFile(plaintextFileName);
  const plaintext = contentsBuffer.toString('base64');
  const name = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );

  // Encrypts the file using the specified crypto key
  const [result] = await client.encrypt({name, plaintext});
  const writeFile = promisify(fs.writeFile);
  await writeFile(ciphertextFileName, Buffer.from(result.ciphertext, 'base64'));
  console.log(`Encrypted ${plaintextFileName} using ${result.name}.`);
  console.log(`Result saved to ${ciphertextFileName}.`);
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';
// $cryptoKeyId = 'The KMS key ID';
// $plaintextFileName = 'The path to the file containing plaintext to encrypt';
// $ciphertextFileName = 'The path to write the ciphertext';

$kms = new KeyManagementServiceClient();

// The resource name of the CryptoKey.
$cryptoKeyName = $kms->cryptoKeyName($projectId, $locationId, $keyRingId, $cryptoKeyId);

$plaintext = file_get_contents($plaintextFileName);
$response = $kms->encrypt($cryptoKeyName, $plaintext);

// Write the encrypted text to a file.
file_put_contents($ciphertextFileName, $response->getCiphertext());
printf('Saved encrypted text to %s' . PHP_EOL, $ciphertextFileName);

Python

def encrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id,
                      plaintext):
    """Encrypts input plaintext data using the provided symmetric CryptoKey."""

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the CryptoKey.
    name = client.crypto_key_path_path(project_id, location_id, key_ring_id,
                                       crypto_key_id)

    # Use the KMS API to encrypt the data.
    response = client.encrypt(name, plaintext)
    return response.ciphertext

Ruby

# project_id      = "Your Google Cloud project ID"
# location_id     = "The location of the key ring"
# key_ring_id     = "The ID of the key ring"
# crypto_key_id   = "The ID of the crypto key"
# plaintext_file  = "File to encrypt"
# ciphertext_file = "File to store encrypted input data"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The crypto key to use
crypto_key = CloudKMS::KeyManagementServiceClient.crypto_key_path(
  project_id, location_id, key_ring_id, crypto_key_id
)

# Read the secret data from the file
plaintext = File.open(plaintext_file, "rb", &:read)

# Use the KMS API to encrypt the data
response = client.encrypt crypto_key, plaintext

# Write the encrypted binary data to the output file
File.open(ciphertext_file, "wb") { |f| f.write response.ciphertext }

puts "Saved encrypted #{plaintext_file} as #{ciphertext_file}"

Decrypt

Command-line

To decrypt data, provide the appropriate key information, specify the name of the encrypted file (ciphertext file) to decrypt, and specify the name of the file that will contain the decrypted content.

gcloud kms decrypt \
  --location=[LOCATION] \
  --keyring=[KEY_RING] \
  --key=[KEY] \
  --ciphertext-file=[FILEPATH_AND_FILENAME_TO_DECRYPT] \
  --plaintext-file=[FILEPATH_AND_FILENAME_TO_DECRYPT].dec

For example, if text.enc is the name of the ciphertext file to decrypt:

gcloud kms decrypt \
  --location=global \
  --keyring=my_keyring \
  --key=my_key \
  --ciphertext-file=text.enc \
  --plaintext-file=text.dec

The decrypt command supports an optional --additional-authenticated-data- file flag to specify a file that contains additional authenticated data. The additional authenticated data file must not be larger than 64 KiB.

If --ciphertext-file or --additional-authenticated-data-file is set to -, that file is read from stdin. Similarly, if --plaintext-file is set to -, the decrypted plaintext is written to stdout.

The following decrypt example shows how to specify additional authenticated data.

gcloud kms decrypt \
  --location=[LOCATION] \
  --keyring=[KEY_RING] \
  --key=[KEY] \
  --additional-authenticated-data-file=[ADDITIONAL_AUTHENTICATED_DATA_FILEPATH_AND_FILENAME] \
  --ciphertext-file=[FILEPATH_AND_FILENAME_TO_DECRYPT] \
  --plaintext-file=[FILEPATH_AND_FILENAME_TO_DECRYPT].dec

Protocol

Decrypted text that is returned in the JSON from Cloud KMS is base64-encoded. For information on encoding and decoding using base64, see Base64 Encoding.

To decrypt encrypted data, make a POST request and provide the appropriate project and key information and specify the encrypted (cipher) text to be decrypted in the ciphertext field of the request body. Replace API_KEY with a valid API key. For information on generating an API key, see Accessing the API.

POST https://cloudkms.googleapis.com/v1/projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING_NAME]/cryptoKeys/[KEY_NAME]:decrypt&key=API_KEY
{
  "ciphertext": "CiQAhMwwBo61cHas7dDgifrUFs5zNzBJ2uZtVFq4ZPEl6fUVT4kSmQ...",
}

Here is an example using curl:

curl -s -X POST "https://cloudkms.googleapis.com/v1/projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING_NAME]/cryptoKeys/[KEY_NAME]:decrypt" \
  -d "{\"ciphertext\":\"[ENCRYPTED_CONTENT]\"}" \
  -H "Authorization:Bearer [API_KEY]"\
  -H "Content-Type:application/json"

C#

        public static void Decrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId,
    string ciphertextFile, string plaintextFile)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            byte[] ciphertext = File.ReadAllBytes(ciphertextFile);
            DecryptResponse result = client.Decrypt(cryptoKeyName, ByteString.CopyFrom(ciphertext));

            // Output decrypted data to a file.
            File.WriteAllBytes(plaintextFile, result.Plaintext.ToByteArray());
            Console.Write($"Decrypted file created: {plaintextFile}");
        }

Go

// decrypt will decrypt the input ciphertext bytes using the specified symmetric key
// example keyName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID"
func decryptSymmetric(keyName string, ciphertext []byte) ([]byte, error) {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return nil, err
	}

	// Build the request.
	req := &kmspb.DecryptRequest{
		Name:       keyName,
		Ciphertext: ciphertext,
	}
	// Call the API.
	resp, err := client.Decrypt(ctx, req)
	if err != nil {
		return nil, err
	}
	return resp.Plaintext, nil
}

Java

/**
 * Decrypts the provided ciphertext with the specified crypto key.
 */
public static byte[] decrypt(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] ciphertext)
    throws IOException {

  // Create the KeyManagementServiceClient using try-with-resources to manage client cleanup.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey
    String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);

    // Decrypt the ciphertext with Cloud KMS.
    DecryptResponse response = client.decrypt(resourceName, ByteString.copyFrom(ciphertext));

    // Extract the plaintext from the response.
    return response.getPlaintext().toByteArray();
  }
}

Node.js

async function decrypt(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
  ciphertextFileName = './path/to/plaintext.txt.encrypted',
  plaintextFileName = './path/to/plaintext.txt.decrypted'
) {
  const fs = require('fs');
  const {promisify} = require('util');

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring, e.g. "global"
  const locationId = 'global';

  // Reads the file to be decrypted
  const readFile = promisify(fs.readFile);
  const contentsBuffer = await readFile(ciphertextFileName);
  const name = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );
  const ciphertext = contentsBuffer.toString('base64');

  // Decrypts the file using the specified crypto key
  const [result] = await client.decrypt({name, ciphertext});

  // Writes the decrypted file to disk
  const writeFile = promisify(fs.writeFile);
  await writeFile(plaintextFileName, Buffer.from(result.plaintext, 'base64'));
  console.log(
    `Decrypted ${ciphertextFileName}, result saved to ${plaintextFileName}.`
  );
}

PHP

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKey;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';
// $cryptoKeyId = 'The KMS key ID';
// $ciphertextFileName = 'The path to the file containing ciphertext to decrypt';
// $plaintextFileName = 'The path to write the plaintext';

$kms = new KeyManagementServiceClient();

// The resource name of the CryptoKey.
$cryptoKey = new CryptoKey();
$cryptoKeyName = $kms->cryptoKeyName($projectId, $locationId, $keyRingId, $cryptoKeyId);

$ciphertext = file_get_contents($ciphertextFileName);
$response = $kms->decrypt($cryptoKeyName, $ciphertext);

// Write the encrypted text to a file.
file_put_contents($plaintextFileName, $response->getPlaintext());
printf('Saved decrypted text to %s' . PHP_EOL, $plaintextFileName);

Python

def decrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id,
                      ciphertext):
    """Decrypts input ciphertext using the provided symmetric CryptoKey."""

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the CryptoKey.
    name = client.crypto_key_path_path(project_id, location_id, key_ring_id,
                                       crypto_key_id)
    # Use the KMS API to decrypt the data.
    response = client.decrypt(name, ciphertext)
    return response.plaintext

Ruby

# project_id    = "Your Google Cloud project ID"
# location_id   = "The location of the key ring"
# key_ring_id   = "The ID of the key ring"
# crypto_key_id = "The ID of the crypto key"
# ciphertext_file = "File to decrypt"
# plaintext_file  = "File to store decrypted data"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The crypto key to use
crypto_key = CloudKMS::KeyManagementServiceClient.crypto_key_path(
  project_id, location_id, key_ring_id, crypto_key_id
)

# Read the encrypted data from the file
ciphertext = File.open(ciphertext_file, "rb", &:read)

# Use the KMS API to decrypt the data
response = client.decrypt crypto_key, ciphertext

# Write the decrypted text to the output file
File.open(plaintext_file, "wb") { |f| f.write response.plaintext }

puts "Saved decrypted #{ciphertext_file} as #{plaintext_file}"

What's next

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

Send feedback about...