Last active
November 6, 2024 08:18
-
-
Save michalc/4c3a1ee3ab8b0be73433ece3e13b7fef to your computer and use it in GitHub Desktop.
Decrypt KMS-encrypted SES emails in an S3 bucket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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