Darwesh Darwesh - 5 months ago 54
Python Question

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

I'm using boto3 with my django application to upload some files to S3. But I receive the following error when I try to specify the client side encryption algorithm and and keys using 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.


Here is my code for specifying Encryption algorithm and keys.

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


And here is how I generate the encryption key in settings.py

# settings.py
password = '32characterslongpassphraseneeded'.encode('utf-8')
AWS_ENCRYPTION_KEY = base64.b64encode(password)


Update



I'm using python3.

Answer

After posting an issue on boto3 library I finally got a working example. Here is how it should be done.

import boto3
import os

BUCKET = 'YOUR-BUCKET'
KEY = os.urandom(32)
s3 = boto3.client('s3')
print("Put object...")
s3.put_object(Bucket=BUCKET,
              Key='encrypt-key', 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='encrypt-key',
                         SSECustomerKey=KEY,
                         SSECustomerAlgorithm='AES256')
print("Done, response body:")
print(response['Body'].read())
Comments