Python Crypto decoding

374 views Asked by At

i try to encrypt and then decrypt text with Crypto and AWS KMS on Python, i have this code :

import base64
import boto3
from Crypto.Cipher import AES

PAD = lambda s: s + (256 - len(s) % 256) * ' '

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'])

    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).encode("utf-8")))

    # 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, AES.MODE_CBC)

    return cypher.decrypt(base64.b64decode(encrypted_data)).rstrip()

def main():
    # Add your account number / region / KMS Key ID here.
    aws_data = {
        'region': 'eu-west-1',
        'account_number': '7011777xxxxx',
        'key_id': 'xxxxxx-83ac-xxxxxx-93d4-xxxxxx',
    }

    # And your super secret message to envelope encrypt...
    plaintext = 'Hello, Worldas!'

    # 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)

    decrypted_data = decrypt_data(aws_data, encrypted_data, cipher_text_blob)
    print(decrypted_data)

if __name__ == '__main__':
    main()

I encrypting for test message 'Hello, Worldas!' my encrypted_data in output looks like : b'ESsdSQv6JxpQptBmj321eX/bVj3gyGJ7AHtrH5qeIfTWbqSzIP7i6URrZFme1PGSNRGzl12B/NBFbK0nHBcCcaj9Wb9Qh+YMYJjeSTnGWOKFWmcIKYAAut9d040xiWG0KKBwHJTdl+41+g8F2ueSWqO1zR9Uuw1qyekF9s/141W7t+Le8IRe60tQKhgMAW5qxDVGluWZGJXLYDLIqFXszN9OhLmjwbMnF4g0ryMq41xbAXH77x0EJODhF1GQ+peHnKuexlhuzRjq1XVAvIgxQ1kYvBSE9AkqqCsO5BwIJuAlwfOWA93gSyTgLmWOg8bPTan4UnQNtTQ3vaRScffPgg=='

But then i try to decrypt i get output : b'-94\xc1\xee\xecF\xfbw9\x81o;\x9d\x1a\x10' instead of 'Hello, Worldas!' Maybe whom know where is a problem? Why it happen? and how can i encrypt and decrypt my file properly ? please suggest!

0

There are 0 answers