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

时间:2015-04-21 22:47:06

标签: python ruby amazon-s3 encryption-symmetric aws-sdk

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

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

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

#!/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?

1 个答案:

答案 0 :(得分:7)

通过Ruby S3 SDK进行了一些跟踪,但客户端加密实现为&#34;信封加密&#34;使用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,))