【发布时间】:2018-06-15 23:16:51
【问题描述】:
我正在尝试使用客户端加密来加密敏感数据,然后再将其移至 S3 上的云存储并将其移至红移。我尝试使用 AWS 提供的示例代码,在尝试了它之后,我让它运行而没有返回错误,但是,它没有做任何我可以判断的事情,因为它没有按应有的方式打印。
def cycle_string(key_arn, source_plaintext, botocore_session=None):
"""Encrypts and then decrypts a string using a KMS customer master key (CMK)
:param str key_arn: [encryption key]
(http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html)
:param bytes source_plaintext:
:param botocore_session: Existing botocore session
:type botocore_session: botocore.session.Session
"""
# Create a KMS master key provider
kms_kwargs = dict(key_ids=[key_arn])
if botocore_session is not None:
kms_kwargs['botocore_session'] = botocore_session
master_key_provider =
aws_encryption_sdk.KMSMasterKeyProvider(**kms_kwargs)
# Encrypt the plaintext source data
ciphertext, encryptor_header = aws_encryption_sdk.encrypt(
source=source_plaintext,
key_provider=master_key_provider
)
print('Ciphertext: ', ciphertext)
# Decrypt the ciphertext
cycled_plaintext, decrypted_header = aws_encryption_sdk.decrypt(
source=ciphertext,
key_provider=master_key_provider
)
# Verify that the "cycled" (encrypted, then decrypted) plaintext is identical to the source
# plaintext
assert cycled_plaintext == source_plaintext
# Verify that the encryption context used in the decrypt operation includes all key pairs from
# the encrypt operation. (The SDK can add pairs, so don't require an exact match.)
#
# In production, always use a meaningful encryption context. In this sample, we omit the
# encryption context (no key pairs).
assert all(
pair in decrypted_header.encryption_context.items()
for pair in encryptor_header.encryption_context.items()
)
print('Decrypted: ', cycled_plaintext)
我是 Python 和加密的新手,所以我可能会遗漏一些语法,或者只是不了解它的工作原理。这是在 python 中使用 AWS 客户端加密的最佳方式吗?如果是这样,为什么这段代码没有返回任何东西?
更新: 我用稍微不同的方法让它工作
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 ACCESSKEY]')
key_id = '[KEY ID]'
plaintext='[FILEPATH\FILENAME.CSV]'
ciphertext = kms.encrypt(KeyId=key_id, Plaintext=plaintext)
#decrypt_ciphertext = kms.decrypt(CiphertextBlob = ciphertext['CiphertextBlob'])
print('Ciphertext: ', ciphertext)
#print('Decrypted Ciphertext: ', decrypt_ciphertext)
现在可以打印了,但我不确定如何判断数据是否真正加密
【问题讨论】:
-
你知道 Python 对代码缩进有严格的规定吗?
-
是的,我在复制代码时忘记添加一些空格。现在应该修复了
-
再添加一些打印语句,看看发生了什么——尤其是对 KMSMasterKeyProvider 等 AWS 服务的调用。了解加密并不重要,更重要的是让最简单的 AWS 程序正常工作。很可能这很简单,比如没有将正确的凭证传递给 AWS。您也可以从 python 提示符中一一运行命令。
标签: python amazon-web-services encryption boto3 aws-kms