Google Cloud Key Management Service

From XennisWiki
Jump to: navigation, search

Service of the Google Cloud Platform to manage encryption keys.

Setup

Enable the API

gcloud services enable cloudkms.googleapis.com

Usage

Create a key ring

Create a new keyring for KMS (location is for instance europe-west3)

gcloud kms keyrings create <ring-name> --location <location>

Create a key

Create a key

gcloud kms keys create <key-name> \
    --location <location> \
    --keyring <ring-name> \
    --purpose encryption

Delete a key

List the key to get it's version

gcloud kms keys versions list \
    --location <location> \
    --keyring <ring-name> \
    --key <key-name>

Delete the key

gcloud kms keys versions destroy <version-number> \
    --location <location> \
    --keyring <ring-name> \
    --key <key-name>

Encrypt a file

Encrypt the file config.json and store the encrypted output as config.json.encrypted

gcloud kms encrypt \
    --location <location> \
    --keyring <ring-name> \
    --key <key-name>  \
    --plaintext-file config.json \
    --ciphertext-file config.json.encrypted

Python library

Installation

Install the required package with pip

pip install google-api-python-client

Decrypt a file

Decrypts the file named config.json.encrypted

import io

from googleapiclient import discovery


kms_client = discovery.build('cloudkms', 'v1')
name = 'projects/{project}/locations/{location}/keyRings/{ring}/cryptoKeys/{key}'.format(
    project='GCP-PROJECT-ID',
    location='GCP-PROJECT-ID',
    ring='RING-NAME',
    key='KEY-NAME')

with io.open('config.json.encrypted', 'rb') as ciphertext_file:
    ciphertext = ciphertext_file.read()

crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
request = crypto_keys.decrypt(
    name=name,
    body={'ciphertext': base64.b64encode(ciphertext).decode('ascii')}
)
response = request.execute()
plaintext = base64.b64decode(response['plaintext'].encode('ascii'))
print(plaintext)

See also

External links