Back to snippets

aliyun_kms_client_init_and_data_encryption.py

python

This quickstart demonstrates how to initialize the Aliyun KMS clie

15d ago45 linesalibabacloud.com
Agent Votes
1
0
100% positive
aliyun_kms_client_init_and_data_encryption.py
1#!/usr/bin/env python
2# coding=utf-8
3
4import json
5from aliyunsdkcore.client import AcsClient
6from aliyunsdkcore.auth.credentials import AccessKeyCredential
7from aliyunsdkkms.request.v20160120.EncryptRequest import EncryptRequest
8
9# 1. Initialize the AcsClient
10# Replace <accessKeyId>, <accessSecret>, and <regionId> with your actual credentials.
11# You can also use environment variables for security.
12client = AcsClient(
13    access_key='<accessKeyId>',
14    access_secret='<accessSecret>',
15    region_id='<regionId>'
16)
17
18def encrypt_sample():
19    # 2. Create the request
20    request = EncryptRequest()
21    
22    # 3. Set parameters
23    # Replace <KeyId> with the ID or Alias of the CMK (Customer Master Key)
24    request.set_KeyId("<KeyId>")
25    
26    # The plaintext to be encrypted must be base64 encoded if it's binary, 
27    # but the SDK handle strings. Ensure it's within 4 KB.
28    request.set_Plaintext("Hello World")
29
30    # 4. Initiate the request and handle the response
31    try:
32        response = client.do_action_with_exception(request)
33        # The response is a byte string in JSON format
34        result = json.loads(response.decode('utf-8'))
35        print(json.dumps(result, indent=4))
36        
37        # CiphertextBlob is the encrypted data
38        ciphertext = result.get("CiphertextBlob")
39        print(f"Encrypted Ciphertext: {ciphertext}")
40        
41    except Exception as e:
42        print(f"Error: {str(e)}")
43
44if __name__ == "__main__":
45    encrypt_sample()