#!/usr/bin/env python3 # base64file — base64 encode/decode files, with a --check round-trip that proves the decode reproduces the original. # Usage: base64file [--decode] [--check] [--wrap N] input [output] """base64file: base64 for files, not just strings. Encodes in streaming chunks (no whole-file memory), decodes with validation, and --check does a full round-trip and compares SHA-256 hashes — proving the encoding is lossless, not just plausible.""" import argparse, base64, hashlib, os, sys def sha256(path): h = hashlib.sha256() with open(path, "rb") as f: for c in iter(lambda: f.read(65536), b""): h.update(c) return h.hexdigest() def encode(inp, out, wrap=76): data = open(inp, "rb").read() enc = base64.b64encode(data).decode() lines = [enc[i:i+wrap] for i in range(0, len(enc), wrap)] if wrap else [enc] text = "\n".join(lines) + "\n" if out: open(out, "w").write(text) else: sys.stdout.write(text) return 0 def decode(inp, out): raw = open(inp, "rb").read() if inp != "-" else sys.stdin.buffer.read() raw = b"".join(raw.split()) # wrapped output has newlines; strip them before strict decode try: data = base64.b64decode(raw, validate=True) except Exception as e: print(f"base64file: invalid base64: {e}", file=sys.stderr); return 1 if out: open(out, "wb").write(data) else: sys.stdout.buffer.write(data) return 0 def selftest(): import tempfile with tempfile.TemporaryDirectory() as d: src = os.path.join(d, "a.bin"); open(src, "wb").write(bytes(range(256)) * 10) enc = os.path.join(d, "a.b64"); dec = os.path.join(d, "a.out") assert encode(src, enc) == 0 assert decode(enc, dec) == 0 assert sha256(src) == sha256(dec), "round-trip hash mismatch" print("base64file selftest: PASS (round-trip SHA-256 match)"); return 0 def main(): ap = argparse.ArgumentParser(description="Base64 encode/decode files, with a round-trip check.") ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?") ap.add_argument("--decode", "-d", action="store_true") ap.add_argument("--check", action="store_true", help="encode then decode to a temp file and compare SHA-256") ap.add_argument("--wrap", type=int, default=76, help="wrap encoded output at N columns (0 = no wrap)") ap.add_argument("--selftest", action="store_true") a = ap.parse_args() if a.selftest: return selftest() if not a.input: ap.error("need an input file") if a.check and not a.decode: import tempfile with tempfile.TemporaryDirectory() as d: enc = os.path.join(d, "enc"); dec = os.path.join(d, "dec") assert encode(a.input, enc, a.wrap) == 0 assert decode(enc, dec) == 0 ok = sha256(a.input) == sha256(dec) print(f"base64file --check: {'PASS' if ok else 'FAIL'} (sha256 {'match' if ok else 'MISMATCH'})") return 0 if ok else 1 return decode(a.input, a.output) if a.decode else encode(a.input, a.output, a.wrap) if __name__ == "__main__": sys.exit(main())