繁体   English   中英

如何在Python中解密AWS Ruby客户端加密

[英]How To Decrypt AWS Ruby Client-side Encryption in Python

AWS的S3 SDK for Ruby允许对文件进行客户端(“信封”)加密。 它是客户端密钥的AES CBC / ECB加密的组合,其中包络密钥和初始化向量存储在元数据中。

我有一个Ruby开发人员,它已经加密了S3存储桶中的各种文件,我需要使用Python检索和解密。 Python S3 AWS SDK目前没有此客户端功能。

假设使用Ruby bucket.write S3 API的encryption_key参数加密文件:

#!/usr/bin/ruby
# coding: utf-8

require 'aws-sdk'
require 'openssl'

access_key = '<aws_access_key>'
secret_access_key = '<secret_access_key>'
encryption_key = "passwordpassword"

s3 = AWS::S3.new
storage_host = "our_bucket"
storage_path = "prod/master_report/test.txt"
bucket_obj = s3.buckets[storage_host].objects[storage_path]
bucket_obj.write(file: 'test.txt', encryption_key: encryption_key)

有没有办法用Python解密文件而不是使用Ruby SDK?

通过Ruby S3 SDK进行了一些跟踪,但客户端加密是使用AES算法实现的“信封加密”。 简而言之,信封的内容使用AES-CBC加密,密钥和IV存储在文件的元数据中(base64编码)。 CBC密钥本身是AES-EBC编码的用户给定的加密密钥。

可以使用此Python解密Ruby客户端加密文件:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
import boto
import tempfile
import base64
from Crypto.Cipher import AES

ENCRYPTION_KEY = b"passwordpassword"
ENV_KEY_LENGTH = 32

conn = boto.connect_s3()
bucket = conn.get_bucket('our_bucket', validate=False)
encrypted = bucket.get_key('prod/master_report/test.txt')

# get envelop keys from file metadata
metadata = encrypted.metadata
envelope_key = base64.b64decode(metadata['x-amz-key'])
envelope_iv = base64.b64decode(metadata['x-amz-iv'])

# decrypt envelope key
cipher = AES.new(ENCRYPTION_KEY, AES.MODE_ECB)
envelope_key = cipher.decrypt(envelope_key)[:ENV_KEY_LENGTH]

# write encrypted file
tf = tempfile.TemporaryFile()
encrypted.get_file(tf)

cipher = AES.new(envelope_key, AES.MODE_CBC, envelope_iv)

# read contents of file
contents = ""
with open('simple/decrypted.txt', 'w') as out:
    tf.seek(0)
    with tf:
        for line in tf:
            dec_line = cipher.decrypt(line)
            contents += dec_line
            print(dec_line, file=out)

tf.close()

print("Decrypted: %s" % (contents,))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM