Skip to content

Instantly share code, notes, and snippets.

@michalc
Last active November 16, 2022 03:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalc/4c3a1ee3ab8b0be73433ece3e13b7fef to your computer and use it in GitHub Desktop.
Save michalc/4c3a1ee3ab8b0be73433ece3e13b7fef to your computer and use it in GitHub Desktop.
Decrypt KMS-encrypted SES emails in an S3 bucket
import base64
import json
import boto3
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
kms_client = boto3.client('kms')
for obj in bucket.objects.filter(Prefix='incoming/'):
print(obj)
obj_get = obj.get()
obj_bytes = obj_get['Body'].read()
data_key = kms_client.decrypt(
CiphertextBlob=base64.b64decode(obj_get['Metadata']['x-amz-key-v2']),
EncryptionContext=json.loads(obj_get['Metadata']['x-amz-matdesc']),
)['Plaintext']
plain = AESGCM(data_key).decrypt(
base64.b64decode(obj_get['Metadata']['x-amz-iv']),
obj_bytes,
None,
)
print(plain)
print('Done')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment