Encrypt and decrypt data with Cloud KMS (Asymmetric)

Cloud KMS is a cloud-hosted key management service that lets you manage cryptographic keys for your cloud services the same way you do on-premises. It includes support for encryption, decryption, signing, and verification using a variety of key types and sources including Cloud HSM for hardware-backed keys. This tutorial teaches you how to encrypt and decrypt data using asymmetric Cloud KMS keys.

You will learn

  • How to enable the Cloud KMS API
  • How to create a Key Ring
  • How to create a Crypto Key for asymmetric encryption/decryption

Self-paced environment setup

  1. Sign in to Cloud Console and create a new project or reuse an existing one. (If you don't already have a Gmail or G Suite account, you must create one.)

dMbN6g9RawQj_VXCSYpdYncY-DbaRzr2GbnwoV7jFf1u3avxJtmGPmKpMYgiaMH-qu80a_NJ9p2IIXFppYk8x3wyymZXavjglNLJJhuXieCem56H30hwXtd8PvXGpXJO9gEUDu3cZw

ci9Oe6PgnbNuSYlMyvbXF1JdQyiHoEgnhl4PlV_MFagm2ppzhueRkqX4eLjJllZco_2zCp0V0bpTupUSKji9KkQyWqj11pqit1K1faS1V6aFxLGQdkuzGp4rsQTan7F01iePL5DtqQ

8-tA_Lheyo8SscAVKrGii2coplQp2_D1Iosb2ViABY0UUO1A8cimXUu6Wf1R9zJIRExL5OB2j946aIiFtyKTzxDcNnuznmR45vZ2HMoK3o67jxuoUJCAnqvEX6NgPGFjCVNgASc-lg

Remember the project ID, a unique name across all Google Cloud projects (the name above has already been taken and will not work for you, sorry!). It will be referred to later in this codelab as PROJECT_ID.

  1. Next, you'll need to enable billing in Cloud Console in order to use Google Cloud resources.

Running through this codelab shouldn't cost much, if anything at all. Be sure to to follow any instructions in the "Cleaning up" section which advises you how to shut down resources so you don't incur billing beyond this tutorial. New users of Google Cloud are eligible for the $300USD Free Trial program.

Start Cloud Shell

In this codelab you will use Cloud Shell, a free virtualized environment running on Google Cloud. From the GCP Console click the Cloud Shell icon on the top right toolbar:

vezHz_9nBUSt_0pD8eMHkzgHehRa83ILgMpcztEJtGZspECiZTk47O02PYk6Zp7jyStful3AIDEZU8qcCNbiXF4WcpkUdJi2LoUbxTWg4cZ4skDnvGKNywBZlDBzzWha111IZ1KqXQ

It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:

wQQCzLZ7_omk2cuoBaKVPnniKDFG6MsP8h2OA0j3Iw9LRSFQ9TkD6Ccq4dcUASPoD5UKe1Ur7bIgYn5gAh2r6BlQDnpFmgyAtv9x2D6ppXS0pfjfxViuEfoetgLvgVeduekc2hgU2Q

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on the Google Cloud, greatly enhancing network performance and authentication. Unless otherwise instructed, run all commands from this shell.

Before you can use Cloud KMS, you must first enable the service in your project. This only needs to be done once per project. To enable the Cloud KMS service, run the following command:

$ gcloud services enable cloudkms.googleapis.com \
    --project "${GOOGLE_CLOUD_PROJECT}"

It can take up to a minute to enable. The command will report success when it finishes.

Create a Cloud KMS Key Ring. In Cloud KMS, a Key Ring is a logical collection of cryptographic keys. The Key Ring contains metadata about the keys such as their location. Create a Key Ring named my-keyring in the global region:

$ gcloud kms keyrings create "my-keyring" \
    --location "global"

Now create a Crypto Key named my-asymmetric-encryption-key with the purpose asymmetric-encryption inside the Key Ring you just created.

$ gcloud kms keys create "my-asymmetric-encryption-key" \
    --location "global" \
    --keyring "my-keyring" \
    --purpose "asymmetric-encryption" \
    --default-algorithm "rsa-decrypt-oaep-4096-sha512"

With asymmetric keys, Cloud KMS does not perform the encryption. Instead, it provides access to a public key and you encrypt data using that public key via public key cryptography. With asymmetric keys, encryption can be done completely offline and does not require access to Cloud KMS or any other Google Cloud APIs. Encryption is performed using a cryptographic tool like openssl or with a programming language or library that supports public key cryptography.

Download the public key from Cloud KMS:

$ gcloud kms keys versions get-public-key "1" \
    --location "global" \
    --keyring "my-keyring" \
    --key "my-asymmetric-encryption-key" \
    --output-file ./key.pub

Create a file with data to encrypt and use the openssl command line tool to encrypt the data in the file:

$ echo "my-contents" > ./data.txt
$ openssl pkeyutl -encrypt -pubin \
    -in ./data.txt \
    -inkey ./key.pub \
    -pkeyopt "rsa_padding_mode:oaep" \
    -pkeyopt "rsa_oaep_md:sha512" \
    -pkeyopt "rsa_mgf1_md:sha512" > ./data.txt.enc

The encrypted data (also known as "ciphertext") will be saved in data.txt.enc on disk. If you open the data.txt.enc file, you will notice that it has strange, unprintable characters. That is because the resulting data is in binary format.

When storing the ciphertext in a database or transmitting it as part of an HTTP request, you may need to encode the data. The most common encoding mechanism for ciphertext is base64.

Cloud KMS does not store any of the plaintext you provide. You need to save this ciphertext in a secure location as it will be required to retrieve the plaintext value.

Unlike encryption, decrypting data that was encrypted using an asymmetric Cloud KMS key does require online access to the Cloud KMS service. Decrypt the ciphertext from the file using the gcloud command line tool:

$ gcloud kms asymmetric-decrypt \


    --location "global" \
    --keyring "my-keyring" \
    --key "my-asymmetric-encryption-key" \
    --version "1" \
    --plaintext-file - \
    --ciphertext-file ./data.txt.enc

The gcloud command line tool reads the ciphertext from the file and decrypts it using Cloud KMS. Notice this example specifies the --plaintext-file argument as -. This instructs gcloud to print the result to the terminal.

The console will print my-contents, which is the same plaintext value from the file above.

You enabled the Cloud KMS API, created an asymmetric encryption key, and encrypted and decrypted data! Cloud KMS is a powerful product and encryption/decryption just scratches the surface of its capabilities.

Clean up

If you are done exploring, please consider deleting your project.

  • Go to the Cloud Platform Console
  • Select the project you want to shut down, then click "Delete" at the top. This schedules the project for deletion.

Learn More

License

This work is licensed under a Creative Commons Attribution 2.0 Generic License.