Google Cloud Key Management Service

3.12.0 · active · verified Sat Mar 28

The `google-cloud-kms` client library provides an interface for interacting with Google Cloud Key Management Service (KMS). KMS is a cloud-hosted key management service that allows you to manage cryptographic keys for your cloud services. It enables generation, usage, rotation, and destruction of various cryptographic keys (AES256, RSA, EC) and integrates with Cloud IAM and Cloud Audit Logging. The library is actively maintained with frequent releases, currently at version 3.12.0, supporting Python 3.9 and higher.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `google-cloud-kms` client and perform a symmetric encryption and decryption operation. Ensure your GCP project ID, KMS key location, key ring ID, and key ID are set as environment variables or replaced. You also need to authenticate to Google Cloud, for example, by setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a service account key file path or by running in a GCP environment with appropriate permissions.

import os
from google.cloud import kms
import base64

project_id = os.environ.get('GCP_PROJECT_ID', 'your-project-id')
location_id = os.environ.get('KMS_KEY_LOCATION', 'global') # e.g., 'global', 'us-central1'
key_ring_id = os.environ.get('KMS_KEY_RING_ID', 'my-key-ring')
key_id = os.environ.get('KMS_KEY_ID', 'my-symmetric-key')

# Construct the key resource name
key_name = (
    f"projects/{project_id}/locations/{location_id}/keyRings/"
    f"{key_ring_id}/cryptoKeys/{key_id}"
)

# Initialize the KMS client
try:
    client = kms.KeyManagementServiceClient()
    print("KMS client initialized.")
except Exception as e:
    print(f"Error initializing KMS client: {e}")
    print("Ensure GOOGLE_APPLICATION_CREDENTIALS is set or running in a GCP environment.")
    exit(1)

# Data to encrypt
plaintext = b"This is a super secret message."

try:
    # Encrypt the plaintext
    encrypt_response = client.encrypt(request={'name': key_name, 'plaintext': plaintext})
    ciphertext = encrypt_response.ciphertext
    print(f"Plaintext encrypted. Ciphertext (base64): {base64.b64encode(ciphertext).decode('utf-8')}")

    # Decrypt the ciphertext
    decrypt_response = client.decrypt(request={'name': key_name, 'ciphertext': ciphertext})
    decrypted_text = decrypt_response.plaintext
    print(f"Ciphertext decrypted. Decrypted text: {decrypted_text.decode('utf-8')}")

    assert plaintext == decrypted_text
    print("Encryption and decryption successful!")

except Exception as e:
    print(f"An error occurred during KMS operation: {e}")
    print("Make sure the key exists, has appropriate IAM permissions, and billing is enabled.")

view raw JSON →