我尝试在Python上使用Crypto和AWS KMS加密然后解密文本,我有以下代码:
import base64
import boto3
from Crypto.Cipher import AES
PAD = lambda s: s + (256 - len(s) % 256) * ' '
def get_arn(aws_data):
return 'arn:aws:kms:{region}:{account_number}:key/{key_id}'.format(**aws_data)
def encrypt_data(aws_data, plaintext_message):
kms_client = boto3.client(
'kms',
region_name=aws_data['region'])
data_key = kms_client.generate_data_key(
KeyId=aws_data['key_id'],
KeySpec='AES_256')
cipher_text_blob = data_key.get('CiphertextBlob')
plaintext_key = data_key.get('Plaintext')
# Note, does not use IV or specify mode... for demo purposes only.
cypher = AES.new(plaintext_key, AES.MODE_CBC)
encrypted_data = base64.b64encode(cypher.encrypt(PAD(plaintext_message).encode("utf-8")))
# Need to preserve both of these data elements
return encrypted_data, cipher_text_blob
def decrypt_data(aws_data, encrypted_data, cipher_text_blob):
kms_client = boto3.client(
'kms',
region_name=aws_data['region'])
decrypted_key = kms_client.decrypt(CiphertextBlob=cipher_text_blob).get('Plaintext')
cypher = AES.new(decrypted_key, AES.MODE_CBC)
return cypher.decrypt(base64.b64decode(encrypted_data)).rstrip()
def main():
# Add your account number / region / KMS Key ID here.
aws_data = {
'region': 'eu-west-1',
'account_number': '7011777xxxxx',
'key_id': 'xxxxxx-83ac-xxxxxx-93d4-xxxxxx',
}
# And your super secret message to envelope encrypt...
plaintext = 'Hello, Worldas!'
# Store encrypted_data & cipher_text_blob in your persistent storage. You will need them both later.
encrypted_data, cipher_text_blob = encrypt_data(aws_data, plaintext)
print(encrypted_data)
decrypted_data = decrypt_data(aws_data, encrypted_data, cipher_text_blob)
print(decrypted_data)
if __name__ == '__main__':
main()
我加密测试消息“你好,Worldas!” my encrypted_data in output looks like : b'ESsdSQv6JxpQptBmj321eX/bVj3gyGJ7AHtrH5qeIfTWbqSzIP7i6URrZFme1PGSNRGzl12B/NBFbK0nHBcCcaj9Wb9Qh+YMYJjeSTnGWOKFWmcIKYAAut9d040xiWG0KKBwHJTdl+41+g8F2ueSWqO1zR9Uuw1qyekF9s/141W7t+Le8IRe60tQKhgMAW5qxDVGluWZGJXLYDLIqFXszN9OhLmjwbMnF4g0ryMq41xbAXH77x0EJODhF1GQ+peHnKuexlhuzRjq1XVAvIgxQ1kYvBSE9AkqqCsO5BwIJuAlwfOWA93gSyTgLmWOg8bPTan4UnQNtTQ3vaRScffPgg=='
但后来我尝试解密我得到输出:b'-94\xc1\xee\xecF\xfbw9\x81o;\x9d\x1a\x10'而不是'Hello, Worldas!' 也许谁知道问题出在哪里?为什么会发生?以及如何正确加密和解密我的文件?请建议!