Registry / gcp / google-cloud-kms

google-cloud-kms

JSON →
library3.12.0pypypi✓ verified 47d ago

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.

gcpauth-security
pip install google-cloud-kms
Install & Compatibility
Where this runs
tested against v3.13.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.925 runs
installs and imports cleanly · install 0.0s · import 2.604s · 72.8MB
glibc
py 3.103.925 runs
installs and imports cleanly · install 5.6s · import 1.804s · 71MB
71MB installed
● package 71MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

KeyManagementServiceClient
from google.cloud import kms
from google.cloud import kms

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.")
Debug
Known issues
breakingStarting 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.
fix
Review your application's error handling for KMS API calls. Implement custom retry logic using `google.api_core.retry` if automatic retries are needed for resilience against transient failures.
affects: >=3.0.0
gotchaCloud 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.
fix
For data larger than 64 KiB, use envelope encryption. This involves generating a data encryption key (DEK) locally, encrypting your large data with the DEK, and then encrypting only the DEK with Cloud KMS. The DEK can then be stored alongside the encrypted data.
affects: All versions
gotchaIncorrect 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).
fix
Verify that the principal making the API call has the `Cloud KMS CryptoKey Encrypter/Decrypter` role (`roles/cloudkms.cryptoKeyEncrypterDecrypter`) on the specific cryptographic key being used. Use `gcloud iam roles describe roles/cloudkms.cryptoKeyEncrypterDecrypter` to see the contained permissions.
affects: All versions
gotchaResource 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.
fix
Always construct resource names carefully, preferably using variables for the project, location, key ring, and key IDs, and ensure they match your existing Cloud KMS resources. Double-check the region for your key ring/key.
affects: All versions
gotchaWhen manually importing key material, issues with key formatting or wrapping can lead to the imported key version having an `IMPORT_FAILED` status.
fix
It is recommended to use automatic key wrapping if possible. If manual wrapping is necessary, carefully review the key formatting requirements and ensure the correct wrapping key from the import job is used.
affects: All versions
breakingThe client failed to initialize because Application Default Credentials (ADC) were not found. This occurs when the `GOOGLE_APPLICATION_CREDENTIALS` environment variable is not set, or when the application is not running in a Google Cloud environment (e.g., GCE, GKE, Cloud Run, Cloud Functions) with an associated service account.
fix
Ensure that Application Default Credentials are configured correctly. If running locally, set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of your service account key file, or run `gcloud auth application-default login`. If deploying to Google Cloud, ensure the service has an associated service account with appropriate roles.
affects: All versions
gotchaThe client failed to initialize due to missing or improperly configured Application Default Credentials (ADC). This error ('Your default credentials were not found') indicates the client could not locate any credentials to authenticate with Google Cloud services.
fix
Ensure your environment is correctly set up for Application Default Credentials. This typically involves: 1. Setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of a service account key file. 2. Running your application in a Google Cloud environment (e.g., Compute Engine, Cloud Run, GKE) where an appropriate service account is attached to the resource. Refer to https://cloud.google.com/docs/authentication/external/set-up-adc for detailed setup instructions.
affects: All versions
Upgrade
Version history
3.13.0latest on PyPI
Audit
Dependencies

No dependency data recorded yet.

Agent activity
47 hits · last 30 days
node
4
seranking-bot
3
ahrefsbot
2
mj12bot
1
Resources