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 os import sys CHUNK = 64 * 1024 # plaintext bytes per chunk (must match src/crypto.ts) def encrypt(content: bytes, password: str) -> bytes: """ Encrypts the given content using the provided password. Uses chunked AES-256-GCM with a PBKDF2-HMAC-SHA512 derived key, matching the server/browser 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. Args: content (bytes): The content to be encrypted. password (str): The password used for encryption. Returns: bytes: the wire format described above """ # Generate a random nonce prefix and salt prefix = os.urandom(7) salt = os.urandom(16) # Derive a key from the password using PBKDF2 kdf = PBKDF2HMAC( algorithm=hashes.SHA512(), length=32, salt=salt, iterations=210000, backend=default_backend() ) aes = AESGCM(kdf.derive(password.encode())) # Always emit at least one (possibly empty) final chunk so empty input still # round-trips and the final-chunk flag is always present. chunks = max(1, -(-len(content) // CHUNK)) # ceil division out = bytearray(salt + prefix) for i in range(chunks): piece = content[i * CHUNK:(i + 1) * CHUNK] last = 1 if i == chunks - 1 else 0 nonce = prefix + i.to_bytes(4, "big") + bytes([last]) out += aes.encrypt(nonce, piece, None) return bytes(out) if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: encrypt.py ") sys.exit(1) data = encrypt(open(sys.argv[1], "rb").read(), sys.argv[2]) open(sys.argv[3], "wb").write(data)