Age File Encryption — Python source
Encrypt and decrypt files with age — a modern, simple alternative to PGP. Password-based encryption runs entirely in your browser.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""age-encryption — passphrase-based file encryption in the spirit of the
age format (age-encryption.org/v1).
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `age-encryption` tool, ported from
src/lib/age-encryption.ts (the canonical TypeScript implementation).
CPython's stdlib ships PBKDF2 (hashlib) but no AES-GCM, so this port keeps the
lib's security shape — 100k-iteration key stretch, fresh random salt + nonce
per encryption, authenticated encryption with a truncated 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
(header || 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
AGE_HEADER = b"cosmodev-age-v1"
SALT_LENGTH = 16
IV_LENGTH = 12
ITERATIONS = 100_000
TAG_LENGTH = 16
# Smallest possible encrypted payload: header + salt + IV + tag = 59 bytes.
HEADER_LENGTH = len(AGE_HEADER)
OVERHEAD = HEADER_LENGTH + SALT_LENGTH + IV_LENGTH + TAG_LENGTH
def is_age_encrypted(data: bytes) -> bool:
"""True when ``data`` starts with the cosmodev-age-v1 magic header."""
return data.startswith(AGE_HEADER)
def _derive_keys(passphrase: str, salt: bytes) -> tuple[bytes, bytes]:
"""Stretch the passphrase 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", passphrase.encode("utf-8"), salt, ITERATIONS
)
return material[:16], material[16:]
def _xor_keystream(key: bytes, nonce: 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 || nonce || i), so the pad is
unpredictable and never repeats within a nonce.
"""
out = bytearray()
for counter in range((len(data) + 31) // 32):
pad = hashlib.sha256(key + nonce + 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, nonce: bytes, ciphertext: bytes) -> bytes:
"""Encrypt-then-MAC tag over header || salt || nonce || ciphertext.
Covers the magic header too (the role GCM's GHASH plays in the TS
reference), truncated to 16 bytes as Web Crypto's GCM tag is.
"""
return hmac.new(
mac_key, AGE_HEADER + salt + nonce + ciphertext, "sha256"
).digest()[:TAG_LENGTH]
def age_encrypt(data: bytes, passphrase: str) -> bytes:
"""Encrypt ``data`` under ``passphrase``.
Returns header || salt || nonce || ciphertext + tag.
"""
if not passphrase:
raise ValueError("Passphrase must not be empty.")
if not data:
raise ValueError("Input data is empty - nothing to encrypt.")
salt = os.urandom(SALT_LENGTH)
nonce = os.urandom(IV_LENGTH)
enc_key, mac_key = _derive_keys(passphrase, salt)
ciphertext = _xor_keystream(enc_key, nonce, data)
tag = _tag(mac_key, salt, nonce, ciphertext)
return AGE_HEADER + salt + nonce + ciphertext + tag
def age_decrypt(data: bytes, passphrase: str) -> bytes:
"""Decrypt a payload produced by ``age_encrypt``.
Raises ``ValueError`` when the data lacks the cosmodev-age-v1 header, the
passphrase is wrong, or the payload was corrupted/tampered (MAC tag
verification failure).
"""
if not passphrase:
raise ValueError("Passphrase must not be empty.")
if not is_age_encrypted(data):
raise ValueError("Not an age-encrypted file (missing cosmodev-age-v1 header).")
if len(data) < OVERHEAD:
raise ValueError(
f"Input is too short to be an age-encrypted file (needs at least "
f"{OVERHEAD} bytes: header + salt + IV + auth tag)."
)
salt = data[HEADER_LENGTH : HEADER_LENGTH + SALT_LENGTH]
nonce = data[
HEADER_LENGTH + SALT_LENGTH : HEADER_LENGTH + SALT_LENGTH + IV_LENGTH
]
body = data[HEADER_LENGTH + SALT_LENGTH + IV_LENGTH :]
ciphertext, tag = body[:-TAG_LENGTH], body[-TAG_LENGTH:]
enc_key, mac_key = _derive_keys(passphrase, salt)
expected = _tag(mac_key, salt, nonce, ciphertext)
if not hmac.compare_digest(tag, expected):
raise ValueError("Decryption failed: wrong passphrase or corrupted file.")
return _xor_keystream(enc_key, nonce, 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 →