import base64 from Crypto.Cipher import AES from Crypto.Random import get_random_bytes NONCE_SIZE = 16 TAG_SIZE = 16 def seal(key, plaintext, associated_data): cipher = AES.new(key, AES.MODE_GCM, nonce=get_random_bytes(NONCE_SIZE)) cipher.update(associated_data) ciphertext, tag = cipher.encrypt_and_digest(plaintext) return cipher.nonce + ciphertext + tag def unseal(key, envelope, associated_data): cipher = AES.new(key, AES.MODE_GCM, nonce=envelope[:NONCE_SIZE]) cipher.update(associated_data) plaintext = cipher.decrypt_and_verify( envelope[NONCE_SIZE:-TAG_SIZE], envelope[-TAG_SIZE:], ) return plaintext def encode_envelope(key, secret, implant_id): associated_data = implant_id.encode("ascii") envelope = seal(key, secret, associated_data) return base64.b64encode(envelope).decode("ascii") def decode_envelope(key, envelope, implant_id): associated_data = implant_id.encode("ascii") decoded = base64.b64decode(envelope, validate=True) return unseal(key, decoded, associated_data).decode("utf-8")