首页 > 解决方案 > 如何使用 botocore 解密数据

问题描述

我正在尝试使用加密数据打印解密数据以验证它是否正确。

session = botocore.session.get_session()
    client = session.create_client('kms',region_name = 'us-east-1',aws_access_key_id = '[YOUR ACCESS KEY]',aws_secret_access_key = '[YOUR SECRET ACCESS KEY]')

key_id = '[KEY ID]'
plaintext='[FILEPATH\FILENAME.CSV]'


ciphertext = client.encrypt(KeyId=key_id, Plaintext=plaintext)
ciphertextblob = ciphertext
decrypt_ciphertext = client.decrypt(CiphertextBlob = ciphertextblob)
print('Ciphertext: ' ciphertext)
print('Decrypted Ciphertext: 'decrypt_ciphertext)

当我运行此代码时,数据已成功加密,但是,当它尝试解密数据时,它会给我一个 Parameter Validation Failed 错误。有谁知道为什么会出现此错误或如何解决?

标签: amazon-web-servicesencryptionaws-kmsbotocore

解决方案


boto3/botocore 的参数验证错误来自构造请求的预处理器。因此,这将在任何内容发送到实际服务 API 之前触发。

在这种情况下,如果您完全按照问题中的方式运行代码,则将整个encrypt响应作为CiphertextBlob参数传递,这将引发参数验证错误,因为它需要一个字节串但接收到一个字典。您需要从响应中提取密文并发送它。

即:更改ciphertextblob = ciphertextciphertextblob = ciphertext['CiphertextBlob']

话虽这么说,从您的示例内容来看,您似乎正在尝试加密文件?encryptKMS 服务通过/ decryptAPI最多只能处理 4096 字节的数据。如果您需要加密大量数据,则需要使用某种形式的信封加密。我会推荐 AWS 加密 SDK[1]。它经过专门设计,尽可能简单地安全使用,并与 AWS KMS 进行了内置集成。

[1] https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html


推荐阅读