from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.hazmat.backends import default_backend import sys CHUNK = 64 * 1024 # plaintext bytes per chunk (must match src/crypto.ts) TAG = 16 ENC_CHUNK = CHUNK + TAG # ciphertext bytes for a full chunk HEADER = 16 + 7 # salt[16] | noncePrefix[7] def decrypt(data: bytes, password: str) -> bytes: """ Decrypts content produced by encrypt.py / the server / browser. Uses chunked AES-256-GCM with a PBKDF2-HMAC-SHA512 derived key, matching the implementation in src/crypto.ts. Wire format: salt[16] | noncePrefix[7] | encChunk_0 | encChunk_1 | ... where encChunk_i = AES-GCM(key, nonce_i, plaintext_i) (16-byte tag appended) and nonce_i = noncePrefix[7] || uint32_be(i) || flag, flag=1 on the final chunk else 0. Each non-final plaintext chunk is exactly CHUNK bytes, so chunk boundaries (and which chunk is last) follow from the total length. Args: data (bytes): The encrypted wire format. password (str): The password used for encryption. Returns: bytes: the decrypted content Raises: Exception: if the password is wrong or the data is corrupt/truncated (the AES-GCM tag, chunk counter, and final-chunk flag are all authenticated). """ if len(data) < HEADER + TAG: raise ValueError("ciphertext too short") salt = data[:16] prefix = data[16:HEADER] body = data[HEADER:] kdf = PBKDF2HMAC( algorithm=hashes.SHA512(), length=32, salt=salt, iterations=210000, backend=default_backend() ) aes = AESGCM(kdf.derive(password.encode())) out = bytearray() offset = 0 i = 0 while offset < len(body): enc_len = min(ENC_CHUNK, len(body) - offset) last = 1 if offset + enc_len >= len(body) else 0 nonce = prefix + i.to_bytes(4, "big") + bytes([last]) out += aes.decrypt(nonce, body[offset:offset + enc_len], None) offset += enc_len i += 1 return bytes(out) if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: decrypt.py ") sys.exit(1) data = decrypt(open(sys.argv[1], "rb").read(), sys.argv[2]) open(sys.argv[3], "wb").write(data)