Skip to content

File Encryptor — Python source

Encrypt or decrypt any file with AES-256-GCM in your browser. Password-based, zero server contact. Drag, drop, done.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""file-encryptor — password-based file encryption (PBKDF2 + AEAD shape).

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `file-encryptor` tool, ported from
src/lib/file-encryptor.ts (the canonical TypeScript implementation).

CPython's stdlib ships PBKDF2 (hashlib) and a CSPRNG (os.urandom) but no
AES-GCM, so — like the age-encryption port — this file keeps the lib's
security shape (100k-iteration key stretch, fresh random salt + IV per
encryption, authenticated encryption with a 16-byte tag) and swaps the AEAD
for a stdlib-only equivalent: a SHA-256 counter-mode keystream plus an
encrypt-then-MAC HMAC-SHA256 tag. The wire layout matches the TS reference
(salt || IV || ciphertext || tag) but the bytes are NOT interchangeable with
it, because the AEAD differs.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import hashlib
import hmac
import os

SALT_LENGTH = 16
IV_LENGTH = 12
ITERATIONS = 100_000
TAG_LENGTH = 16
# Smallest possible encrypted payload: salt + IV + tag = 44 bytes.
MIN_LENGTH = SALT_LENGTH + IV_LENGTH + TAG_LENGTH


def _derive_keys(password: str, salt: bytes) -> tuple[bytes, bytes]:
    """Stretch the password into (encryption key, MAC key).

    PBKDF2-SHA256 over 100k iterations — the same stretch the TS reference
    performs via Web Crypto — split into two independent 128-bit halves so
    the stream cipher and the MAC never share a key.
    """
    material = hashlib.pbkdf2_hmac(
        "sha256", password.encode("utf-8"), salt, ITERATIONS
    )
    return material[:16], material[16:]


def _xor_keystream(key: bytes, iv: bytes, data: bytes) -> bytes:
    """XOR ``data`` with a SHA-256 counter-mode keystream.

    This is the stream-cipher half of what AES-GCM does in the TS reference:
    block i of the pad is SHA-256(key || iv || i), so the pad is
    unpredictable and never repeats within an IV.
    """
    out = bytearray()
    for counter in range((len(data) + 31) // 32):
        pad = hashlib.sha256(key + iv + counter.to_bytes(4, "big")).digest()
        chunk = data[counter * 32 : (counter + 1) * 32]
        out.extend(b ^ k for b, k in zip(chunk, pad))
    return bytes(out)


def _tag(mac_key: bytes, salt: bytes, iv: bytes, ciphertext: bytes) -> bytes:
    """Encrypt-then-MAC tag over salt || IV || ciphertext, truncated to 16
    bytes (the role GCM's GHASH tag plays in the TS reference)."""
    return hmac.new(mac_key, salt + iv + ciphertext, "sha256").digest()[:TAG_LENGTH]


def encrypt_file(data: bytes, password: str) -> bytes:
    """Encrypt ``data`` under ``password``. Returns salt || IV || ciphertext+tag."""
    if not password:
        raise ValueError("Password must not be empty.")
    if not data:
        raise ValueError("Input data is empty - nothing to encrypt.")
    salt = os.urandom(SALT_LENGTH)
    iv = os.urandom(IV_LENGTH)
    enc_key, mac_key = _derive_keys(password, salt)
    ciphertext = _xor_keystream(enc_key, iv, data)
    tag = _tag(mac_key, salt, iv, ciphertext)
    return salt + iv + ciphertext + tag


def decrypt_file(data: bytes, password: str) -> bytes:
    """Decrypt a payload produced by ``encrypt_file``.

    Raises ``ValueError`` when the password is wrong or the payload was
    corrupted/tampered (MAC tag verification failure).
    """
    if not password:
        raise ValueError("Password must not be empty.")
    if len(data) < MIN_LENGTH:
        raise ValueError(
            f"Input is too short to be an encrypted file (needs at least "
            f"{MIN_LENGTH} bytes: salt + IV + auth tag)."
        )
    salt = data[:SALT_LENGTH]
    iv = data[SALT_LENGTH : SALT_LENGTH + IV_LENGTH]
    body = data[SALT_LENGTH + IV_LENGTH :]
    ciphertext, tag = body[:-TAG_LENGTH], body[-TAG_LENGTH:]
    enc_key, mac_key = _derive_keys(password, salt)
    expected = _tag(mac_key, salt, iv, ciphertext)
    if not hmac.compare_digest(tag, expected):
        raise ValueError("Decryption failed: wrong password or corrupted file.")
    return _xor_keystream(enc_key, iv, ciphertext)

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →