Last active
October 12, 2017 15:00
-
-
Save Magrath/28609b1ebf6e4be20a8dcf642c713ac8 to your computer and use it in GitHub Desktop.
Retrieving and decrypting from S3 using KMS client side decryption
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
def get(bucket, s3_key) | |
client = Aws::S3::Client.new(region: "us-east-1") | |
params = { bucket: bucket, key: s3_key } | |
req = client.build_request(:get_object, params) | |
req.send_request | |
end | |
def decrypt(get_object_output, kms_key_id) | |
cipher_provider = Aws::S3::Encryption::KmsCipherProvider.new(kms_key_id: kms_key_id, kms_client: Aws::KMS::Client.new) | |
envelope = get_object_output.metadata | |
encrypted = get_object_output.body.read | |
http_resp = get_object_output.context.http_response | |
auth_tag_length = http_resp.headers['x-amz-meta-x-amz-tag-len'].to_i / 8 | |
cipher = cipher_provider.decryption_cipher(envelope) | |
cipher.update(encrypted[0..(encrypted.length-auth_tag_length)]) | |
end | |
bucket = "BUCKET" | |
kms_key_id = "KEY_ID" | |
s3_key = "S3_KEY" | |
get_object_output = get(bucket, s3_key) | |
decrypt(get_object_output, kms_key_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This relates to AWS Support Case 4161422531. Simple usage of
client.get_object(bucket: bucket, key: s3_key)
fails with anOpenSSL::Cipher::CipherError
for a particular input S3 object. The above code is able to decrypt the same input S3 object.