I'm trying to decrypt some S3 files that use client side encryption (not by me). I've been given the public and private keys and told RSA is used... but I'm struggling to figure out how to decrypt this file.
My understanding is that it's a 2 step process:
Download the meta data of the file which contains
metadata['x-amz-key']
- This is the first key that need to be decrypted using my private key.Once this is decrypted it produces a new key that I can use to decrypt the actual file?
I'm not really sure how to do this. So far I've tried this (which I think is covering step 1).
Would love some help with this - very confused.
import base64
from Crypto.PublicKey import RSA
key = "-----BEGIN PRIVATE KEY-----\nMAHJKxxxxxxxx\n-----END PRIVATE KEY-----"
rsa_Key =RSA.importKey(key)
raw_cipher_data = envelope_key
second_key = rsa_Key.decrypt(raw_cipher_data)
This then produces something that looks like this:
b"\x15\\xc0\\s'
Even if this is correct... which I suspect it isn't. How would I then go on to decrypt the actual S3 file?
Thanks again.
NEXT STEP
This is as far as I got with it... seems like a reasonable approach and I'm more confident after lots of reading (this post also helped a lot (How To Decrypt AWS Ruby Client-side Encryption in Python).
However, still can't get this working...
from Crypto.Cipher import AES
object_info = s3.head_object(Bucket="xxxx", Key="Secret.txt")
metadata = object_info['Metadata']
envelope_key = base64.b64decode(metadata['x-amz-key'])
envelope_iv = base64.b64decode(metadata['x-amz-iv'])
ENV_KEY_LENGTH = 32
ENCRYPTION_KEY = base64.b64decode(KEY)
key = "-----BEGIN PRIVATE KEY-----\nXXXX\n-----END PRIVATE KEY-----"
rsa_Key =RSA.importKey(key)
envelope_key = rsa_Key.decrypt(envelope_key)[:ENV_KEY_LENGTH]
envelope_iv = rsa_Key.decrypt(envelope_iv)[:ENV_KEY_LENGTH]
decryptor = AES.new(envelope_key, AES.MODE_CBC, envelope_iv)
with open('Desktop/test.txt', 'r') as f:
f.read()
secret_de = decryptor.decrypt(f)
print(secret_de)