python-3.x - 带有 AES CBC 的 AWS KMS python3.6 和 boto3 示例
问题描述
我曾尝试使用 python 3.6 和 boto3 与 AWS KMS 进行加密演示,但它缺少 AES 的操作模式。我想知道您是否可以为我指明如何执行此操作的方向。
我试图在 KeySpec 的调用中定义 AES.CBC_MODE,但它只需要 AES_256 或 AES_128。
这是代码:
import base64
import boto3
from Crypto.Cipher import AES
PAD = lambda s: s + (32 - len(s) % 32) * ' '
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'],
aws_access_key_id='your_key_id',
aws_secret_access_key='your_secred_key_id')
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)))
# 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)
return cypher.decrypt(base64.b64decode(encrypted_data)).rstrip()
def main():
# Add your account number / region / KMS Key ID here.
aws_data = {
'region': 'us-east-1',
'account_number': 'your_account',
'key_id': 'your_key_id',
}
# And your super secret message to envelope encrypt...
plaintext = 'Superduper and the mighty Scoop!'
# 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)
# # Later on when you need to decrypt, get these from your persistent storage.
decrypted_data = decrypt_data(aws_data, encrypted_data, cipher_text_blob)
print(decrypted_data)
if __name__ == '__main__':
main()
解决方案
您是否考虑过使用 AWS 加密 SDK,而不是实施您自己的信封加密?[1][2] 它与 AWS KMS 紧密集成,使安全信封加密变得简单,使用 KMS CMK 保护您的数据密钥。它还使您可以轻松跟踪解密所需的所有部分(IV、加密数据密钥、加密上下文等),方法是返回一条密文消息,其中包含客户端解密所需知道的所有内容信息。
您可以在此处找到如何实现与您在问题中显示的内容类似的示例 [3]。
[1] https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html
[2] https://aws-encryption-sdk-python.readthedocs.io/en/latest/
[3] https://github.com/aws/aws-encryption-sdk-python/blob/master/examples/src/basic_encryption.py
推荐阅读
- typescript - TypeScript Fetch response.Json
- 预期 0 类型参数,但得到 1 - c# - 数据绑定时防止数据网格中的重复
- reactjs - 我在我的 jsfiddle 中收到错误未关闭的正则表达式
- android - 在片段中动态生成的 RadioGroup 中获取选中按钮
- redis - 无法加载密钥:redis 服务器不支持扫描命令
- reactjs - 带有 react/redux/router 流的搜索组件
- git - Jenkins 在构建之前无法清理工作区
- spring - 使用 Get 方法 @QueryParam 将枚举列表传递给 Spring REST
- reactjs - 无法将所需的参数传递给反应渲染()的jsx内的函数
- javascript - 如何在 React 中处理 CORS