【问题标题】:What is the right way to create a SSECustomerKey for boto3 file encryption in python?在 python 中为 boto3 文件加密创建 SSECustomerKey 的正确方法是什么?
【发布时间】:2016-10-17 02:16:28
【问题描述】:

我在我的 django 应用程序中使用 boto3 将媒体上传到 S3。但我无法使用“使用客户提供的加密密钥进行服务器端加密”来加密服务器上的文件

我正在使用 boto3 的 object.put() api 来上传文件并指定加密密钥。但我收到以下错误。

"计算的密钥的 MD5 哈希值与之前的哈希值不匹配 提供。”

我不确定如何创建将在服务器端匹配的密钥的 md5。这是我的代码。

password = "32characterslongpassphraseneeded".encode('utf-8')
encryption_key = hashlib.md5(password).hexdigest()
encryption_key_md5 = hashlib.md5(encryption_key.encode('utf-8')).hexdigest()
import boto3
s3 = boto3.resource('s3')
key = s3.Object(bucket_name, key_name)
kwargs = {
            'SSECustomerAlgorithm': 'AES256',
            'SSECustomerKey': encryption_key,
            'SSECustomerKeyMD5': encryption_key_md5,
            'ContentType': file_obj.content_type,
            'Body': file_obj,
        }

key.put(**kwargs)

我正在通过一个 php 客户端使用相同的 s3 api,它工作正常。

$name="somename"
$customerKey = md5($name);
                    $s3->putObject([
                        'Bucket' => S3_BUCKET,
                        'Key'    => "scope/{$name}",
                        'Body'   => fopen($tmp_file_path, 'rb'),
                        'ACL'    => S3_ACL,
                        'SSECustomerAlgorithm' => 'AES256',
                        'SSECustomerKey'       => $customerKey,
                        'SSECustomerKeyMD5'    => md5($customerKey ,true),
                    ]);

我在这里看到的唯一区别是 php 的 md5 方法可以采用第二个参数,如果为 true,则返回 16 个字符长的摘要,而普通的 32 个字符长的摘要。现在我不知道如何使用 hashlib.md5 创建一个 16 字符长的摘要。

【问题讨论】:

  • 如果不提供SSECustomerKeyMD5 参数会怎样? Boto3 应该会为您计算。
  • 如果我不提供,则会收到 400 Bad Request 错误。
  • SSECustomerKey 和 MD5 假设在 base64 中,因此不匹配

标签: python encryption amazon-s3 boto boto3


【解决方案1】:

正确的做法是使用os.urandom

import os
secret_key = os.urandom(32) # The key needs to be 32 character long.

并且不需要提供SSECustomerKeyMD5,因为 boto3 会为您计算。

而且 SSE-C 在key.put 中也不能正常工作,至于现在,我不知道是什么原因。必须这样做。

s3 = boto3.client('s3')
s3.put_object(**kwargs)

【讨论】:

  • 非常感谢。我几乎一无所知。
【解决方案2】:

似乎 SSE 也适用于 Object。一个例子如下

import boto3
from botocore.config import Config

s3 = boto3.resource('s3', 
                    region_name="us-east-1",
                    aws_access_key_id="key id",
                    aws_secret_access_key="access key",
                    config=Config(signature_version='s3v4')) 
s3.Object("bucket", "filename").put(Body="text",
                                    SSEKMSKeyId="some id",
                                    ServerSideEncryption='aws:kms')

要阅读它,请使用

s3.Object("bucket", "filename").get()['Body'].read()

【讨论】:

    猜你喜欢
    • 2014-08-23
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多