Search code examples
pythonamazon-web-servicesamazon-s3aws-lambdaamazon-kms

Encrypt a file using KMS and push to S3


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 ?


Solution

  • 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.