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

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...