boto3 Client Error: Server Side Encryption with Customer provided key is incompatible with the encryption method specified

boto3 Client Error: Server Side Encryption with Customer provided key is incompatible with the encryption method specified

我在我的 django 应用程序中使用 boto3 将一些文件上传到 S3。但是当我尝试使用 boto3's Object's API.

指定客户端加密算法和密钥时收到以下错误

An error occurred (InvalidArgument) when calling the PutObject operation: Server Side Encryption with Customer provided key is incompatible with the encryption method specified.

这是我指定加密算法和密钥的代码。

    import boto3
    s3 = boto3.resource('s3')
    key = s3.Object(bucket_name, key_name)
    file_obj.seek(0)
    kwargs = {
        'ServerSideEncryption': 'AES256',
        'SSECustomerAlgorithm': 'AES256',
        'SSECustomerKey': settings.AWS_ENCRYPTION_KEY,
    }

    key.put(**kwargs)
    key.put(Body=file_obj)
    key.Acl().put(ACL='public-read')

下面是我如何在 settings.py

中生成加密密钥
# settings.py
password = '32characterslongpassphraseneeded'.encode('utf-8')
AWS_ENCRYPTION_KEY = base64.b64encode(password)

更新

我正在使用 python3。

在 boto3 库上发布问题后,我终于得到了一个工作示例。这是应该如何完成的。

import boto3
import os

BUCKET = 'YOUR-BUCKET'
KEY = os.urandom(32)
s3 = boto3.client('s3')
print("Put object...")
s3.put_object(Bucket=BUCKET,
              Key='path_of_object_in_bucket', Body=b'foobar',
              SSECustomerKey=KEY,
              SSECustomerAlgorithm='AES256')
print("Done")
# Make sure to save the KEY!

# Getting the object:
print("Getting object...")
response = s3.get_object(Bucket=BUCKET,
                         Key='path_of_object_in_bucket',
                         SSECustomerKey=KEY,
                         SSECustomerAlgorithm='AES256')
print("Done, response body:")
print(response['Body'].read())