Google Cloud Key Management Service
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
- breaking Starting with version 3.0.0 (released 2024-09-23), the default retry policy has been removed from all API calls. This affects both synchronous and asynchronous clients, meaning calls will no longer automatically retry on transient errors unless a custom retry policy is explicitly configured.
- gotcha Cloud KMS has a plaintext size limit of 64 KiB (65,536 bytes) for direct encryption operations. Attempting to encrypt larger data directly will result in an error.
- gotcha Incorrect IAM permissions are a frequent source of `Permission Denied` errors. Ensure the service account or user calling KMS has the necessary roles (e.g., `roles/cloudkms.viewer`, `roles/cloudkms.cryptoKeyEncrypterDecrypter`) on the specific key, key ring, or project, and that roles are applied to the correct resource type (e.g., KMS keys, not a GCS bucket when encrypting GCS objects with a CMEK).
- gotcha Resource names (key paths) must be precisely formatted using `projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING_ID/cryptoKeys/KEY_ID`. Mismatched IDs or incorrect segment ordering will result in `NOT_FOUND` or `INVALID_ARGUMENT` errors. The location can be global or a specific region.
- gotcha When manually importing key material, issues with key formatting or wrapping can lead to the imported key version having an `IMPORT_FAILED` status.
Install
-
pip install google-cloud-kms
Imports
- KeyManagementServiceClient
from google.cloud import kms client = kms.KeyManagementServiceClient()
Quickstart
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.")