首页 > 解决方案 > 带有 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()

标签: python-3.xamazon-web-servicesboto3aws-kms

解决方案


您是否考虑过使用 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


推荐阅读