Registry / auth-security / aliyun-python-sdk-kms

aliyun-python-sdk-kms

JSON →
library2.16.5pypypi✓ verified 25d ago

The `aliyun-python-sdk-kms` library provides Python bindings for Alibaba Cloud's Key Management Service (KMS), enabling users to create, manage, and use encryption keys for their data. It allows operations like encryption, decryption, and key management within the Aliyun ecosystem. The current version is 2.16.5, with updates typically tied to Alibaba Cloud API releases.

pip install aliyun-python-sdk-kms
INSTALL
IMPORT
SIG · ALIYUN-PYTHON-SDK-
A
aliyun-python-sdk-kms
auth-securitypythonv2.16.5
Install
2.8s avg
Import
376ms
Disk
38MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.16.5 · 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.95 runs
installs and imports cleanly · install 0.0s · import 0.388s · 39.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.8s · import 0.364s · 40MB
38MB installed
● package 38MB
Code
Verified usage

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

AcsClient
from aliyunsdkcore.client import AcsClient
EncryptRequest
from aliyunsdkkms.request.v20160120 import EncryptRequest
from aliyunsdkkms.request import EncryptRequest
KMS API requests are typically versioned (e.g., v20160120) and must be imported from the specific version module.
DecryptRequest
from aliyunsdkkms.request.v20160120 import DecryptRequest
from aliyunsdkkms.request import DecryptRequest
KMS API requests are typically versioned (e.g., v20160120) and must be imported from the specific version module.

This quickstart demonstrates how to initialize the KMS client, encrypt a plaintext, and then decrypt the resulting ciphertext using your Alibaba Cloud credentials and a specified KMS Key ID. It's crucial to configure your Access Key ID, Access Key Secret, Region ID, and KMS Key ID, ideally using environment variables for security.

import os import json from aliyunsdkcore.client import AcsClient from aliyunsdkkms.request.v20160102 import EncryptRequest, DecryptRequest # Configuration from environment variables # It's highly recommended to set these environment variables. ACCESS_KEY_ID = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_ID') ACCESS_KEY_SECRET = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'YOUR_ACCESS_KEY_SECRET') REGION_ID = os.environ.get('ALIBABA_CLOUD_REGION_ID', 'cn-hangzhou') # e.g., cn-hangzhou, us-west-1 KMS_KEY_ID = os.environ.get('ALIBABA_CLOUD_KMS_KEY_ID', 'alias/example_key') # Replace with your KMS Key ID or alias if ACCESS_KEY_ID == 'YOUR_ACCESS_KEY_ID' or ACCESS_KEY_SECRET == 'YOUR_ACCESS_KEY_SECRET': print("Warning: Please set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.") print("The example will attempt to run with mock credentials, leading to API authentication errors.") if KMS_KEY_ID == 'alias/example_key': print("Warning: Please set ALIBABA_CLOUD_KMS_KEY_ID environment variable for actual KMS operations.") print("The example will use a placeholder key ID, which will likely cause a 'Key not found' error.") try: # Initialize the KMS client client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION_ID) print(f"KMS client initialized for region: {REGION_ID}") # 1. Encrypt a plaintext plaintext_to_encrypt = "This is a secret message to be encrypted by KMS." encrypt_request = EncryptRequest.EncryptRequest() encrypt_request.set_KeyId(KMS_KEY_ID) encrypt_request.set_Plaintext(plaintext_to_encrypt) # encrypt_request.set_EncryptionContext(json.dumps({'purpose': 'test'})) # Optional context print(f"\nAttempting to encrypt: '{plaintext_to_encrypt}' with Key ID: '{KMS_KEY_ID}'") encrypt_response_bytes = client.do_action_with_exception(encrypt_request) encrypt_response_data = json.loads(encrypt_response_bytes.decode('utf-8')) ciphertext_blob = encrypt_response_data.get('CiphertextBlob') print(f"Encryption successful. CiphertextBlob (truncated): {ciphertext_blob[:50]}...") # 2. Decrypt the ciphertext if ciphertext_blob: decrypt_request = DecryptRequest.DecryptRequest() decrypt_request.set_CiphertextBlob(ciphertext_blob) # decrypt_request.set_EncryptionContext(json.dumps({'purpose': 'test'})) # Must match encryption context if used print(f"\nAttempting to decrypt ciphertext...") decrypt_response_bytes = client.do_action_with_exception(decrypt_request) decrypt_response_data = json.loads(decrypt_response_bytes.decode('utf-8')) decrypted_plaintext = decrypt_response_data.get('Plaintext') print(f"Decryption successful. Decrypted Plaintext: '{decrypted_plaintext}'") except Exception as e: print(f"\nAn error occurred during KMS operation: {e}") if "InvalidAccessKeyId.NotFound" in str(e) or "InvalidAccessKeySecret" in str(e): print("Hint: Verify your ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables or credentials.") elif "Specified key is not found." in str(e) or "The KeyId specified does not exist." in str(e): print("Hint: Verify your ALIBABA_CLOUD_KMS_KEY_ID environment variable is a valid KMS Key ID or alias in the specified region.") elif "InvalidRegionId" in str(e): print("Hint: Verify your ALIBABA_CLOUD_REGION_ID environment variable.") elif "CiphertextBlobIsNullOrEmpty" in str(e): print("Hint: Encryption failed to produce a CiphertextBlob, so decryption cannot proceed. Check encryption parameters.")
Debug
Known issues
breakingAPI Version Changes: The import paths for KMS requests include an API version (e.g., `v20160120`). If Alibaba Cloud introduces a new major API version or deprecates an old one, these import paths will break, requiring an update to the code.
fix
Monitor Aliyun SDK release notes. Update `from aliyunsdkkms.request.vYYYYMMDD import ...` to reflect the current API version.
affects: All versions tied to specific API versions (e.g., 2.x.x)
gotchaResponse Handling: The `client.do_action_with_exception` method returns a `bytes` object, not a Python dictionary. It needs to be decoded from UTF-8 and then parsed as JSON.
fix
Always use `json.loads(response_bytes.decode('utf-8'))` to correctly process the API response.
affects: All versions
gotchaRegion and Endpoint Configuration: Incorrect `REGION_ID` during client initialization, or an explicit `request.set_endpoint()` pointing to a wrong URL, can lead to `ServiceUnavailable` or `EndpointNotFound` errors.
fix
Ensure `REGION_ID` passed to `AcsClient` is correct and matches the region where your KMS key resides. Avoid manually setting endpoints unless for specific network configurations.
affects: All versions
gotchaEncryption Context Mismatch: If an `EncryptionContext` is provided during encryption (via `set_EncryptionContext`), the exact same context *must* be provided during decryption for the operation to succeed. A mismatch will result in decryption failure.
fix
Store and reuse the `EncryptionContext` used during encryption when performing decryption. Ensure it's a JSON string matching the original.
affects: All versions
gotchaKMS Key Identifier: Distinguish between Key ID (e.g., `arn:acs:kms:cn-hangzhou:123456789:key/your-key-id`) and Key Alias (e.g., `alias/your-alias`). Ensure you are using the correct identifier where expected.
fix
Verify whether the API call or configuration expects a Key ID or an alias. Use `set_KeyId()` for both, but ensure the string format is correct for your identifier.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'aliyunsdkcore'
The 'aliyunsdkcore' module is not installed in the Python environment.
fix
Install the module using pip: 'pip install aliyun-python-sdk-core'.
ModuleNotFoundError: No module named 'aliyunsdkcore.vendored.six.moves'
The 'six' module is missing or not properly installed, which is required by 'aliyunsdkcore'.
fix
Install or upgrade the 'six' module: 'pip install --upgrade --force-reinstall six'.
ModuleNotFoundError: No module named 'aliyun-python-sdk-kms'
The 'aliyun-python-sdk-kms' package is not installed in the Python environment.
fix
Install the package using pip: 'pip install aliyun-python-sdk-kms'.
Forbidden.KeyNotFound
The specified key ID or alias does not match the parameters used for encryption.
fix
Ensure that the region, key ID, or alias used for decryption is identical to the one used for encryption.
UnsupportedOperation
The application uses an Alibaba Cloud SDK to perform cryptographic operations with a key created in a KMS instance without proper network access configuration.
fix
Enable Internet access for the KMS instance in the Alibaba Cloud console.
Upgrade
Version history
2.16.5latest on PyPI · released Aug 30, 2024
Audit
Dependencies
aliyun-python-sdk-corerequiredProvides the core client functionality (AcsClient) required for all Aliyun SDK interactions.
Agent activity
73 hits · last 30 days
node
60
Perplexity
1
OpenAI (training)
1
Resources