encrypt.py
| 1 | from cryptography.hazmat.primitives import hashes |
| 2 | from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC |
| 3 | from cryptography.hazmat.primitives.ciphers.aead import AESGCM |
| 4 | from cryptography.hazmat.backends import default_backend |
| 5 | import os |
| 6 | import sys |
| 7 | |
| 8 | CHUNK = 64 * 1024 # plaintext bytes per chunk (must match src/crypto.ts) |
| 9 | |
| 10 | |
| 11 | def encrypt(content: bytes, password: str) -> bytes: |
| 12 | """ |
| 13 | Encrypts the given content using the provided password. |
| 14 | |
| 15 | Uses chunked AES-256-GCM with a PBKDF2-HMAC-SHA512 derived key, matching the |
| 16 | server/browser implementation in src/crypto.ts. |
| 17 | |
| 18 | Wire format: salt[16] | noncePrefix[7] | encChunk_0 | encChunk_1 | ... |
| 19 | where encChunk_i = AES-GCM(key, nonce_i, plaintext_i) (16-byte tag appended) |
| 20 | and nonce_i = noncePrefix[7] || uint32_be(i) || flag, flag=1 on the final |
| 21 | chunk else 0. Each non-final plaintext chunk is exactly CHUNK bytes. |
| 22 | |
| 23 | Args: |
| 24 | content (bytes): The content to be encrypted. |
| 25 | password (str): The password used for encryption. |
| 26 | |
| 27 | Returns: |
| 28 | bytes: the wire format described above |
| 29 | """ |
| 30 | |
| 31 | # Generate a random nonce prefix and salt |
| 32 | prefix = os.urandom(7) |
| 33 | salt = os.urandom(16) |
| 34 | |
| 35 | # Derive a key from the password using PBKDF2 |
| 36 | kdf = PBKDF2HMAC( |
| 37 | algorithm=hashes.SHA512(), |
| 38 | length=32, |
| 39 | salt=salt, |
| 40 | iterations=210000, |
| 41 | backend=default_backend() |
| 42 | ) |
| 43 | aes = AESGCM(kdf.derive(password.encode())) |
| 44 | |
| 45 | # Always emit at least one (possibly empty) final chunk so empty input still |
| 46 | # round-trips and the final-chunk flag is always present. |
| 47 | chunks = max(1, -(-len(content) // CHUNK)) # ceil division |
| 48 | out = bytearray(salt + prefix) |
| 49 | for i in range(chunks): |
| 50 | piece = content[i * CHUNK:(i + 1) * CHUNK] |
| 51 | last = 1 if i == chunks - 1 else 0 |
| 52 | nonce = prefix + i.to_bytes(4, "big") + bytes([last]) |
| 53 | out += aes.encrypt(nonce, piece, None) |
| 54 | return bytes(out) |
| 55 | |
| 56 | |
| 57 | if __name__ == "__main__": |
| 58 | if len(sys.argv) != 4: |
| 59 | print("Usage: encrypt.py <file> <password> <outfile>") |
| 60 | sys.exit(1) |
| 61 | data = encrypt(open(sys.argv[1], "rb").read(), sys.argv[2]) |
| 62 | open(sys.argv[3], "wb").write(data) |
| 63 |