Created
December 13, 2024 00:20
-
-
Save tupui/7059b558608c75c0746d06413267674d to your computer and use it in GitHub Desktop.
Encrypt a file with AES 256 EAX
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 binascii | |
import json | |
from base64 import b64encode, b64decode | |
from Crypto.Cipher import AES | |
from Crypto.Random import get_random_bytes | |
data = b"..." | |
header = b"storachaProof" | |
aes_key = get_random_bytes(32) | |
print(f"This is our key in hex: {aes_key.hex()}") | |
cipher = AES.new(aes_key, AES.MODE_EAX) | |
cipher.update(header) | |
ciphertext, tag = cipher.encrypt_and_digest(data) | |
json_k = ["nonce", "header", "ciphertext", "tag"] | |
json_v = [b64encode(x).decode() for x in (cipher.nonce, header, ciphertext, tag)] | |
payload = dict(zip(json_k, json_v)) | |
with open("encrypted_proof.bin", "w") as fp: | |
json.dump(payload, fp, indent=4) | |
#### Reading check | |
# load the hex value | |
aes_key = binascii.unhexlify("...") | |
with open("encrypted_proof.bin", "r") as fp: | |
payload = json.load(fp) | |
payload = {k: b64decode(v) for k, v in payload.items()} | |
cipher = AES.new(aes_key, AES.MODE_EAX, nonce=payload["nonce"]) | |
cipher.update(payload["header"]) | |
plaintext = cipher.decrypt(payload["ciphertext"]) | |
try: | |
cipher.verify(payload["tag"]) | |
print(f"The message is authentic:\n{plaintext}") | |
except ValueError: | |
print("Key incorrect or message corrupted") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment