How do you use Boto3 download_file with AWS KMS?

I have a very simple script that loads a file from a bucket. The file uses KMS encrypted keys, my policies and roles are configured correctly, but I still get an error message.

code

#!/usr/bin/env python import boto3 s3_client = boto3.client('s3') s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt') 

Error

 Traceback (most recent call last): File "./getfile.py", line 4, in <module> s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt') File "/usr/local/lib/python2.7/dist-packages/boto3/s3/inject.py", line 91, in download_file extra_args=ExtraArgs, callback=Callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 659, in download_file extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 674, in _download_file self._get_object(bucket, key, filename, extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 698, in _get_object extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 712, in _do_get_object **extra_args) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 301, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 386, in _make_api_call raise ClientError(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the GetObject operation: Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4. 
+6
source share
2 answers

It revealed

code

 #!/usr/bin/env python import boto3 from botocore.client import Config s3_client = boto3.client('s3', config=Config(signature_version='s3v4')) s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt') 
+12
source

You can also learn how to upload a file to s3 using the kms keys.

 s3_client = boto3.client('s3', config=Config(signature_version='s3v4')) s3_client.upload_file(filename, bucketname, objectkey, ExtraArgs={"ServerSideEncryption": "aws:kms", "SSEKMSKeyId": <somekmskeyid>}) 

If you did not specify a kms key key, then by default it uses the s3 kms master key.

+4
source

All Articles