{"id":1317,"library":"aliyun-python-sdk-kms","title":"Aliyun Python SDK for Key Management Service (KMS)","description":"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.","status":"active","version":"2.16.5","language":"en","source_language":"en","source_url":"https://github.com/aliyun/aliyun-openapi-python-sdk","tags":["aliyun","cloud","kms","security","encryption","key-management"],"install":[{"cmd":"pip install aliyun-python-sdk-kms","lang":"bash","label":"Install `aliyun-python-sdk-kms`"}],"dependencies":[{"reason":"Provides the core client functionality (AcsClient) required for all Aliyun SDK interactions.","package":"aliyun-python-sdk-core"}],"imports":[{"symbol":"AcsClient","correct":"from aliyunsdkcore.client import AcsClient"},{"note":"KMS API requests are typically versioned (e.g., v20160120) and must be imported from the specific version module.","wrong":"from aliyunsdkkms.request import EncryptRequest","symbol":"EncryptRequest","correct":"from aliyunsdkkms.request.v20160120 import EncryptRequest"},{"note":"KMS API requests are typically versioned (e.g., v20160120) and must be imported from the specific version module.","wrong":"from aliyunsdkkms.request import DecryptRequest","symbol":"DecryptRequest","correct":"from aliyunsdkkms.request.v20160120 import DecryptRequest"}],"quickstart":{"code":"import os\nimport json\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkkms.request.v20160102 import EncryptRequest, DecryptRequest\n\n# Configuration from environment variables\n# It's highly recommended to set these environment variables.\nACCESS_KEY_ID = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_ID')\nACCESS_KEY_SECRET = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'YOUR_ACCESS_KEY_SECRET')\nREGION_ID = os.environ.get('ALIBABA_CLOUD_REGION_ID', 'cn-hangzhou') # e.g., cn-hangzhou, us-west-1\nKMS_KEY_ID = os.environ.get('ALIBABA_CLOUD_KMS_KEY_ID', 'alias/example_key') # Replace with your KMS Key ID or alias\n\nif ACCESS_KEY_ID == 'YOUR_ACCESS_KEY_ID' or ACCESS_KEY_SECRET == 'YOUR_ACCESS_KEY_SECRET':\n    print(\"Warning: Please set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.\")\n    print(\"The example will attempt to run with mock credentials, leading to API authentication errors.\")\n\nif KMS_KEY_ID == 'alias/example_key':\n    print(\"Warning: Please set ALIBABA_CLOUD_KMS_KEY_ID environment variable for actual KMS operations.\")\n    print(\"The example will use a placeholder key ID, which will likely cause a 'Key not found' error.\")\n\ntry:\n    # Initialize the KMS client\n    client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION_ID)\n    print(f\"KMS client initialized for region: {REGION_ID}\")\n\n    # 1. Encrypt a plaintext\n    plaintext_to_encrypt = \"This is a secret message to be encrypted by KMS.\"\n    encrypt_request = EncryptRequest.EncryptRequest()\n    encrypt_request.set_KeyId(KMS_KEY_ID)\n    encrypt_request.set_Plaintext(plaintext_to_encrypt)\n    # encrypt_request.set_EncryptionContext(json.dumps({'purpose': 'test'})) # Optional context\n\n    print(f\"\\nAttempting to encrypt: '{plaintext_to_encrypt}' with Key ID: '{KMS_KEY_ID}'\")\n    encrypt_response_bytes = client.do_action_with_exception(encrypt_request)\n    encrypt_response_data = json.loads(encrypt_response_bytes.decode('utf-8'))\n    ciphertext_blob = encrypt_response_data.get('CiphertextBlob')\n    print(f\"Encryption successful. CiphertextBlob (truncated): {ciphertext_blob[:50]}...\")\n\n    # 2. Decrypt the ciphertext\n    if ciphertext_blob:\n        decrypt_request = DecryptRequest.DecryptRequest()\n        decrypt_request.set_CiphertextBlob(ciphertext_blob)\n        # decrypt_request.set_EncryptionContext(json.dumps({'purpose': 'test'})) # Must match encryption context if used\n\n        print(f\"\\nAttempting to decrypt ciphertext...\")\n        decrypt_response_bytes = client.do_action_with_exception(decrypt_request)\n        decrypt_response_data = json.loads(decrypt_response_bytes.decode('utf-8'))\n        decrypted_plaintext = decrypt_response_data.get('Plaintext')\n        print(f\"Decryption successful. Decrypted Plaintext: '{decrypted_plaintext}'\")\n\nexcept Exception as e:\n    print(f\"\\nAn error occurred during KMS operation: {e}\")\n    if \"InvalidAccessKeyId.NotFound\" in str(e) or \"InvalidAccessKeySecret\" in str(e):\n        print(\"Hint: Verify your ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables or credentials.\")\n    elif \"Specified key is not found.\" in str(e) or \"The KeyId specified does not exist.\" in str(e):\n        print(\"Hint: Verify your ALIBABA_CLOUD_KMS_KEY_ID environment variable is a valid KMS Key ID or alias in the specified region.\")\n    elif \"InvalidRegionId\" in str(e):\n        print(\"Hint: Verify your ALIBABA_CLOUD_REGION_ID environment variable.\")\n    elif \"CiphertextBlobIsNullOrEmpty\" in str(e):\n        print(\"Hint: Encryption failed to produce a CiphertextBlob, so decryption cannot proceed. Check encryption parameters.\")","lang":"python","description":"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."},"warnings":[{"fix":"Monitor Aliyun SDK release notes. Update `from aliyunsdkkms.request.vYYYYMMDD import ...` to reflect the current API version.","message":"API 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.","severity":"breaking","affected_versions":"All versions tied to specific API versions (e.g., 2.x.x)"},{"fix":"Always use `json.loads(response_bytes.decode('utf-8'))` to correctly process the API response.","message":"Response 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Region 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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Store and reuse the `EncryptionContext` used during encryption when performing decryption. Ensure it's a JSON string matching the original.","message":"Encryption 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"KMS 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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}