|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +from typing import Union |
| 5 | + |
| 6 | +from cryptography.hazmat.backends import default_backend |
| 7 | +from cryptography.hazmat.primitives import hashes |
| 8 | +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
| 9 | +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC |
| 10 | + |
| 11 | + |
| 12 | +_CHUNK_SIZE = 4096 |
| 13 | +_SALT_SIZE = 16 |
| 14 | +_NONCE_SIZE = 12 |
| 15 | +_TAG_SIZE = 16 |
| 16 | + |
| 17 | + |
| 18 | +def _derive_key(password: Union[str, bytes], salt: bytes) -> bytes: |
| 19 | + """Derive a 256-bit key from the given password and salt.""" |
| 20 | + if isinstance(password, str): |
| 21 | + password = password.encode() |
| 22 | + kdf = PBKDF2HMAC( |
| 23 | + algorithm=hashes.SHA256(), |
| 24 | + length=32, |
| 25 | + salt=salt, |
| 26 | + iterations=390000, |
| 27 | + backend=default_backend(), |
| 28 | + ) |
| 29 | + return kdf.derive(password) |
| 30 | + |
| 31 | + |
| 32 | +def encrypt_file( |
| 33 | + in_path: str, |
| 34 | + out_path: str, |
| 35 | + password: Union[str, bytes], |
| 36 | + chunk_size: int = _CHUNK_SIZE, |
| 37 | +) -> None: |
| 38 | + """Encrypt ``in_path`` to ``out_path`` using AES-GCM. |
| 39 | +
|
| 40 | + The output file layout is ``salt`` + ``nonce`` + ciphertext + ``tag``. Data |
| 41 | + is processed in chunks so large files do not need to be fully loaded into |
| 42 | + memory. |
| 43 | + """ |
| 44 | + salt = os.urandom(_SALT_SIZE) |
| 45 | + key = _derive_key(password, salt) |
| 46 | + nonce = os.urandom(_NONCE_SIZE) |
| 47 | + cipher = Cipher( |
| 48 | + algorithms.AES(key), |
| 49 | + modes.GCM(nonce), |
| 50 | + backend=default_backend(), |
| 51 | + ) |
| 52 | + encryptor = cipher.encryptor() |
| 53 | + |
| 54 | + try: |
| 55 | + with open(in_path, "rb") as fin, open(out_path, "wb") as fout: |
| 56 | + fout.write(salt) |
| 57 | + fout.write(nonce) |
| 58 | + while True: |
| 59 | + chunk = fin.read(chunk_size) |
| 60 | + if not chunk: |
| 61 | + break |
| 62 | + data = encryptor.update(chunk) |
| 63 | + if data: |
| 64 | + fout.write(data) |
| 65 | + encryptor.finalize() |
| 66 | + fout.write(encryptor.tag) |
| 67 | + except Exception: |
| 68 | + if os.path.exists(out_path): |
| 69 | + os.remove(out_path) |
| 70 | + raise |
| 71 | + |
| 72 | + |
| 73 | +def decrypt_file( |
| 74 | + in_path: str, |
| 75 | + out_path: str, |
| 76 | + password: Union[str, bytes], |
| 77 | + chunk_size: int = _CHUNK_SIZE, |
| 78 | +) -> None: |
| 79 | + """Decrypt ``in_path`` to ``out_path`` verifying the authentication tag.""" |
| 80 | + total_size = os.path.getsize(in_path) |
| 81 | + if total_size < _SALT_SIZE + _NONCE_SIZE + _TAG_SIZE: |
| 82 | + raise ValueError("Ciphertext too small") |
| 83 | + |
| 84 | + with open(in_path, "rb") as fin: |
| 85 | + salt = fin.read(_SALT_SIZE) |
| 86 | + nonce = fin.read(_NONCE_SIZE) |
| 87 | + key = _derive_key(password, salt) |
| 88 | + cipher = Cipher( |
| 89 | + algorithms.AES(key), |
| 90 | + modes.GCM(nonce), |
| 91 | + backend=default_backend(), |
| 92 | + ) |
| 93 | + decryptor = cipher.decryptor() |
| 94 | + |
| 95 | + ciphertext_len = total_size - _SALT_SIZE - _NONCE_SIZE - _TAG_SIZE |
| 96 | + remaining = ciphertext_len |
| 97 | + try: |
| 98 | + with open(out_path, "wb") as fout: |
| 99 | + while remaining > 0: |
| 100 | + chunk = fin.read(min(chunk_size, remaining)) |
| 101 | + if not chunk: |
| 102 | + break |
| 103 | + remaining -= len(chunk) |
| 104 | + data = decryptor.update(chunk) |
| 105 | + if data: |
| 106 | + fout.write(data) |
| 107 | + tag = fin.read(_TAG_SIZE) |
| 108 | + decryptor.finalize_with_tag(tag) |
| 109 | + except Exception: |
| 110 | + if os.path.exists(out_path): |
| 111 | + os.remove(out_path) |
| 112 | + raise |
0 commit comments