1

I have a AWS lambda function written in Python that needs to create a file using data in a string variable , KMS encrypt the file and push the file to S3.

s3_resource = boto3.resource("s3")
s3_resource.Bucket(bucket_name).put_object(Key=s3_path, Body=data)

I am using the above to create the file in S3 , but is there a way to use the KMS keys that I have to encrypt the file while pushing to S3 ?

Punter Vicky
  • 15,954
  • 56
  • 188
  • 315

1 Answers1

1

To use KMS encryption when adding an object use the server side encryption options:

  • ServerSideEncryption ="aws:kms" - to enable KMS encryption
  • SSEKMSKeyId=keyId - to specify the KMS key you want to use for encryption. If you don't specify this, AWS will just use your default account key.

For example:

s3_resource.Bucket(bucket_name).put_object(
        Key=s3_path,
        Body=data,
        ServerSideEncryption ="aws:kms"
    )

You may also need to enable v4 signing in your boto configuration file.

thomasmichaelwallace
  • 7,926
  • 1
  • 27
  • 33
  • Thanks @thomasmichaelwallace! The bucket is in a different account and they have enabled AES encryption. Can I still use this option to KMS encrypt the file and push it to the bucket? – Punter Vicky May 02 '19 at 19:32
  • Should I provide the KMS key arn for SSEKMSKeyId field? – Punter Vicky May 02 '19 at 19:33
  • Yes- the SSEKMSKeyId field should be the ARN. Although you will need to make sure you have the permissions all setup correctly (take a look at this question: https://stackoverflow.com/questions/48317364/how-do-i-get-aws-cross-account-kms-keys-to-work) – thomasmichaelwallace May 02 '19 at 19:44
  • I see this error "An error occurred (InvalidArgument) when calling the PutObject operation: Multiple server side encryption methods are specified, only one method is allowed". Is it because the default encryption of the bucket is aes-256 and I am trying to send KMS as SSECustomerAlgorithm? – Punter Vicky May 02 '19 at 20:34
  • Sorry- some bad copy and pasting from the service definition there, I've updated the answer, you should be using ServerSideEncryption, not SSECustomerAlgorithm. – thomasmichaelwallace May 02 '19 at 20:54
  • No worries. Sorry about the confusion! – thomasmichaelwallace May 02 '19 at 21:46
  • If you pass just the ID to SSEKMSKeyId it will be resolved to proper arn – januszm May 06 '21 at 20:52