Package: alibabacloud-kms-python-sdk
image0Alibaba Cloud KMS SDK for Python can help Python developers to use the
KMS.Read this in other
languages:English,简体中文Alibaba Cloud KMS
HomepageSample CodeIssuesReleaseAdvantageAlibaba Cloud KMS SDK helps Python developers quickly use all APIs of
Alibaba Cloud KMS products: - KMS resource management and key operations
can be performed through KMS public gateway access - You can perform key
operations through KMS instance gatewayRequirementsPython 3.6 or laterInstallpip install alibabacloud-kms-python-sdkIntroduction to KMS ClientKMS client classesIntroductionUsage scenariosalibabacloud_kms_k
ms20160120.client.ClientKMS resource
management and key
operations for KMS
instance gateways
are supported1. Scenarios where
key operations are
performed only
through VPC
gateways. 2. KMS
resource management
scenarios that only
use public
gateways. 3.
Scenarios where you
want to perform key
operations through
VPC gateways and
manage KMS
resources through
public gateways.al
ibabacloud_kms_kms201601
20.client.TransferClientUsers can migrate
from KMS 1.0 key
operations to KMS
3.0 key operationsUsers who use
Alibaba Cloud SDK
to access KMS 1.0
key operations need
to migrate to KMS
3.0Sample code1. Scenarios where key operations are performed only through VPC gateways.Refer to the following sample code to call the KMS AdvanceEncrypt API. For more API examples, seeoperation samplesimportsysfromtypingimportListfromopenapiimportmodelsasdedicated_kms_openapi_modelsfromalibabacloud_kms_kms20160120.clientimportClientasKmsSdkClientfromsdkimportmodelsasdedicated_kms_sdk_modelsfromalibabacloud_tea_util.clientimportClientasUtilClientfromalibabacloud_darabonba_env.clientimportClientasEnvClientclassAdvanceEncrypt:def__init__(self):pass@staticmethoddefcreate_kms_instance_config(client_key_file:str,password:str,endpoint:str,ca_file_path:str,)->dedicated_kms_openapi_models.Config:config=dedicated_kms_openapi_models.Config(client_key_file=client_key_file,password=password,endpoint=endpoint,ca_file_path=ca_file_path)returnconfig@staticmethoddefcreate_client(kms_instance_config:dedicated_kms_openapi_models.Config,)->KmsSdkClient:returnKmsSdkClient(kms_instance_config=kms_instance_config)@staticmethoddefadvance_encrypt(client:KmsSdkClient,key_id:str,plaintext:bytes,)->dedicated_kms_sdk_models.AdvanceEncryptResponse:request=dedicated_kms_sdk_models.AdvanceEncryptRequest(key_id=key_id,plaintext=plaintext)returnclient.advance_encrypt(request)@staticmethoddefmain(args:List[str],)->None:kms_instance_config=AdvanceEncrypt.create_kms_instance_config(EnvClient.get_env('your client key file path env'),EnvClient.get_env('your client key password env'),'your kms instance endpoint','your ca file path')client=AdvanceEncrypt.create_client(kms_instance_config)key_id='your keyId'plaintext=UtilClient.to_bytes('your plaintext')response=AdvanceEncrypt.advance_encrypt(client,key_id,plaintext)print(response)if__name__=='__main__':AdvanceEncrypt.main(sys.argv[1:])2. KMS resources are managed only through public gateways.Refer to the following sample code to call the KMS CreateKey API. For more API examples, seemanage samplesimportsysfromtypingimportListfromalibabacloud_tea_openapiimportmodelsasopen_api_modelsfromalibabacloud_kms_kms20160120.clientimportClientasKmsSdkClientfromalibabacloud_kms20160120importmodelsaskms_20160120_modelsfromalibabacloud_darabonba_env.clientimportClientasEnvClientclassCreateKey:def__init__(self):pass@staticmethoddefcreate_open_api_config(access_key_id:str,access_key_secret:str,region_id:str,)->open_api_models.Config:config=open_api_models.Config(access_key_id=access_key_id,access_key_secret=access_key_secret,region_id=region_id)returnconfig@staticmethoddefcreate_client(open_api_config:open_api_models.Config,)->KmsSdkClient:returnKmsSdkClient(open_api_config=open_api_config)@staticmethoddefcreate_key(client:KmsSdkClient,enable_automatic_rotation:bool,rotation_interval:str,key_usage:str,origin:str,description:str,dkmsinstance_id:str,protection_level:str,key_spec:str,)->kms_20160120_models.CreateKeyResponse:request=kms_20160120_models.CreateKeyRequest(enable_automatic_rotation=enable_automatic_rotation,rotation_interval=rotation_interval,key_usage=key_usage,origin=origin,description=description,dkmsinstance_id=dkmsinstance_id,protection_level=protection_level,key_spec=key_spec)returnclient.create_key(request)@staticmethoddefmain(args:List[str],)->None:#Make sure that the environment in which the code runs has environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET set.#Project code leakage may cause AccessKey to be leaked and threaten the security of all resources under the account. The following code example uses an environment variable to obtain the AccessKey for reference only, it is recommended to use the more secure STS mode, for more authentication access methods, see https://help.aliyun.com/document_detail/378657.htmlopen_api_config=CreateKey.create_open_api_config(EnvClient.get_env('ALIBABA_CLOUD_ACCESS_KEY_ID'),EnvClient.get_env('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),'your region id')client=CreateKey.create_client(open_api_config)enable_automatic_rotation=Falserotation_interval='your rotationInterval'key_usage='your keyUsage'origin='your origin'description='your description'd_kmsinstance_id='your dKMSInstanceId'protection_level='your protectionLevel'key_spec='your keySpec'response=CreateKey.create_key(client,enable_automatic_rotation,rotation_interval,key_usage,origin,description,d_kmsinstance_id,protection_level,key_spec)print(response)if__name__=='__main__':CreateKey.main(sys.argv[1:])3. You must not only perform key operations through a VPC gateway, but also manage KMS resources through a public gateway.Refer to the following sample code to call the KMS CreateKey API and the AdvanceEncrypt API. For more API examples, seeoperation samples和manage samplesimportsysfromtypingimportListfromopenapiimportmodelsasdedicated_kms_openapi_modelsfromalibabacloud_kms_kms20160120.clientimportClientasKmsSdkClientfromsdkimportmodelsasdedicated_kms_sdk_modelsfromalibabacloud_tea_util.clientimportClientasUtilClientfromalibabacloud_darabonba_env.clientimportClientasEnvClientfromalibabacloud_tea_openapiimportmodelsasopen_api_modelsfromalibabacloud_kms20160120importmodelsaskms_20160120_modelsclassSample:def__init__(self):pass@staticmethoddefcreate_kms_instance_config(client_key_file:str,password:str,endpoint:str,ca_file_path:str,)->dedicated_kms_openapi_models.Config:config=dedicated_kms_openapi_models.Config(client_key_file=client_key_file,password=password,endpoint=endpoint,ca_file_path=ca_file_path)returnconfig@staticmethoddefcreate_open_api_config(access_key_id:str,access_key_secret:str,region_id:str,)->open_api_models.Config:config=open_api_models.Config(access_key_id=access_key_id,access_key_secret=access_key_secret,region_id=region_id)returnconfig@staticmethoddefcreate_client(kms_instance_config:dedicated_kms_openapi_models.Config,open_api_config:open_api_models.Config)->KmsSdkClient:returnKmsSdkClient(kms_instance_config=kms_instance_config,open_api_config=open_api_config)@staticmethoddefcreate_key(client:KmsSdkClient,enable_automatic_rotation:bool,rotation_interval:str,key_usage:str,origin:str,description:str,dkmsinstance_id:str,protection_level:str,key_spec:str,)->kms_20160120_models.CreateKeyResponse:request=kms_20160120_models.CreateKeyRequest(enable_automatic_rotation=enable_automatic_rotation,rotation_interval=rotation_interval,key_usage=key_usage,origin=origin,description=description,dkmsinstance_id=dkmsinstance_id,protection_level=protection_level,key_spec=key_spec)returnclient.create_key(request)@staticmethoddefadvance_encrypt(client:KmsSdkClient,key_id:str,plaintext:bytes,)->dedicated_kms_sdk_models.AdvanceEncryptResponse:request=dedicated_kms_sdk_models.AdvanceEncryptRequest(key_id=key_id,plaintext=plaintext)returnclient.advance_encrypt(request)@staticmethoddefmain(args:List[str],)->None:kms_instance_config=Sample.create_kms_instance_config(EnvClient.get_env('your client key file path env'),EnvClient.get_env('your client key password env'),'your kms instance endpoint','your ca file path')#Make sure that the environment in which the code runs has environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET set.#Project code leakage may cause AccessKey to be leaked and threaten the security of all resources under the account. The following code example uses an environment variable to obtain the AccessKey for reference only, it is recommended to use the more secure STS mode, for more authentication access methods, see https://help.aliyun.com/document_detail/378657.htmlopen_api_config=Sample.create_open_api_config(EnvClient.get_env('ALIBABA_CLOUD_ACCESS_KEY_ID'),EnvClient.get_env('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),'your region id')client=Sample.create_client(kms_instance_config,open_api_config)#CreateKeyenable_automatic_rotation=Falserotation_interval='your rotationInterval'key_usage='your keyUsage'origin='your origin'description='your description'd_kmsinstance_id='your dKMSInstanceId'protection_level='your protectionLevel'key_spec='your keySpec'create_key_resp=Sample.create_key(client,enable_automatic_rotation,rotation_interval,key_usage,origin,description,d_kmsinstance_id,protection_level,key_spec)print(create_key_resp)#Advance Encryptkey_id='your keyId'plaintext=UtilClient.to_bytes('your plaintext')encrypt_resp=Sample.advance_encrypt(client,key_id,plaintext)print(encrypt_resp)if__name__=='__main__':Sample.main(sys.argv[1:])Users who uses Alibaba Cloud SDK to access KMS 1.0 keys need to migrate to access KMS 3.0 keys.Refer to the following sample code to call the KMS API. For more API examples, seekms transfer samplesimportosfromalibabacloud_kms20160120importmodelsaskms_20160120_modelsfromalibabacloud_tea_openapiimportmodelsasopen_api_modelsfromalibabacloud_kms_kms20160120.modelsimportKmsConfig,KmsRuntimeOptionsfromalibabacloud_kms_kms20160120.transfer_clientimportTransferClientdefcreate_client():# set configopenapi_config=open_api_models.Config(# set region idregion_id='<your-region-id>',# set access key idaccess_key_id=os.getenv('ACCESS_KEY_ID'),# set access key secretaccess_key_secret=os.getenv('ACCESS_KEY_SECRET'))# set kms configkms_config=KmsConfig(# set the request protocol to httpsprotocol='https',# set client key file pathclient_key_file='<your-client-key-file-path>',# set client key passwordpassword='<your-password>',# set kms instance endpointendpoint='<your-kms-instance-endpoint>')# create transfer clientreturnTransferClient(config=config,kms_config=kms_config)defcreate_key(client):request=kms_20160120_models.CreateKeyRequest(key_spec='<your-key-spec>',key_usage='<your-key-usage>')# If verify server CA certificate,you can set CA certificate file path with RuntimeOptionsruntime=KmsRuntimeOptions(ca='<your-ca-certificate-file-path>')# If you ignore ssl verification，you can set ignore_ssl with True related to the RuntimeOptions parameter# runtime = KmsRuntimeOptions(#    ignore_ssl=True# )try:response=client.create_key_with_options(request,runtime)print(str(response.body))exceptExceptionase:print(str(e))defgenerate_data_key(client):request=kms_20160120_models.GenerateDataKeyRequest(key_id='<your-key-id>',)# If verify server CA certificate,you can set CA certificate file path with RuntimeOptionsruntime=KmsRuntimeOptions(ca='<your-ca-certificate-file-path>')# If you ignore ssl verification，you can set ignore_ssl with True related to the RuntimeOptions parameter# runtime = KmsRuntimeOptions(#    ignore_ssl=True# )try:response=client.generate_data_key_with_options(request,runtime)print(str(response.body))exceptExceptionase:print(str(e))client=create_client()create_key(client)generate_data_key(client)KMS instance performance testingIf you need to use the KMS instance SDK for KMS instance performance
testing, please refer to the sample code of the pressure measurement
tools in the directory named benchmarks , compile it into an executable
program and run it with the following command:$pythonbenchmark.py--case=encrypt--client_key_file=./ClientKey_****.json--client_key_password=****--endpoint=kst-****.cryptoservice.kms.aliyuncs.com--key_id=key-****--data_size=32--concurrence_nums=32--duration=600How to compile and use the stress test tool, please refer tothe
document.LicenseApache License
2.0Copyright (c) 2009-present, Alibaba Cloud All rights reserved.