我尝试使用带有AWS KMS的python 3.6和boto3进行加密演示,但它缺少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()
答案 0 :(得分:0)
您是否考虑过使用AWS Encryption 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
答案 1 :(得分:-1)
AES_128和AES_256是指AES 128位/ AES 256位加密密钥。
CBC表示密码块链接
GCM表示伽罗瓦/计数器模式
KMS使用AES_256和GCM。不支持CBC。
AWS KMS在其中使用高级加密标准(AES)算法 Galois /计数器模式(GCM),称为AES-GCM。 AWS KMS使用此 具有256位秘密密钥的算法。