CodeSample小助手 2019-12-31
本文以加密SSL证书私钥为例,介绍如何调用KMS API实现对数据的在线加密、解密。
您可以调用以下KMS API,完成对数据的加密或解密操作。
API名称 | 说明 |
---|---|
CreateKey | 创建用户主密钥(CMK)。 |
CreateAlias | 为指定用户主密钥创建一个别名。 |
Encrypt | 指定CMK,由KMS加密数据。 |
Decrypt | 解密KMS直接加密的数据,不需要指定CMK。 |
$ aliyun kms CreateKey
{
"KeyMetadata": {
"CreationDate": "2019-04-08T07:45:54Z",
"Description": "",
"KeyId": "1234abcd-12ab-34cd-56ef-12345678****",
"KeyState": "Enabled",
"KeyUsage": "ENCRYPT/DECRYPT",
"DeleteDate": "",
"Creator": "111122223333",
"Arn": "acs:kms:cn-hangzhou:111122223333:key/1234abcd-12ab-34cd-56ef-12345678****",
"Origin": "Aliyun_KMS",
"MaterialExpireTime": ""
},
"RequestId": "2a37b168-9fa0-4d71-aba4-2077dd9e80df"
}
$ aliyun kms CreateAlias --AliasName alias/Apollo/WorkKey --KeyId 1234abcd-12ab-34cd-56ef-12345678****
Apollo/WorkKey
表示Apollo项目中的工作密钥(当前被用于加密的密钥),并在后续示例代码中使用此别名。即表示应用可以使用
alias/Apollo/WorkKey
调用加密API。
alias/Apollo/WorkKey
#!/usr/bin/env python
#coding=utf-8
import json
from aliyunsdkcore import client
from aliyunsdkkms.request.v20160120 import EncryptRequest
from aliyunsdkkms.request.v20160120 import DecryptRequest
def KmsEncrypt(client, plaintext, key_alias):
request = EncryptRequest.EncryptRequest()
request.set_accept_format('JSON')
request.set_KeyId(key_alias)
request.set_Plaintext(plaintext)
response = json.loads(clt.do_action(request))
return response.get("CiphertextBlob")
def ReadTextFile(in_file):
file = open(in_file, 'r')
content = file.read()
file.close()
return content
def WriteTextFile(out_file, content):
file = open(out_file, 'w')
file.write(content)
file.close()
clt = client.AcsClient('<Access-Key-Id>','Access-Key-Secret','<Region-Id>')
key_alias = 'alias/Apollo/WorkKey'
in_file = './certs/key.pem'
out_file = './certs/key.pem.cipher'
# Read private key file in text mode
in_content = ReadTextFile(in_file)
# Encrypt
ciphertext = KmsEncrypt(clt, in_content, key_alias)
# Write encrypted key file in text mode
WriteTextFile(out_file, ciphertext)
#!/usr/bin/env python
#coding=utf-8
import json
from aliyunsdkcore import client
from aliyunsdkkms.request.v20160120 import EncryptRequest
from aliyunsdkkms.request.v20160120 import DecryptRequest
def KmsDecrypt(client, ciphertext):
request = DecryptRequest.DecryptRequest()
request.set_accept_format('JSON')
request.set_CiphertextBlob(ciphertext)
response = json.loads(clt.do_action(request))
return response.get("Plaintext")
def ReadTextFile(in_file):
file = open(in_file, 'r')
content = file.read()
file.close()
return content
def WriteTextFile(out_file, content):
file = open(out_file, 'w')
file.write(content)
file.close()
clt = client.AcsClient('<Access-Key-Id>','Access-Key-Secret','<Region-Id>')
in_file = './certs/key.pem.cipher'
out_file = './certs/decrypted_key.pem'
# Read encrypted key file in text mode
in_content = ReadTextFile(in_file)
# Decrypt
ciphertext = KmsDecrypt(clt, in_content)
# Write Decrypted key file in text mode
WriteTextFile(out_file, ciphertext)