Argon2 Hash & Verify — Python source
Hash passwords with Argon2id — the winner of the Password Hashing Competition. Configure memory, iterations, and parallelism. WASM-powered, client-side.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""argon2 — Argon2id password hashing (PHC parse/format logic in pure Python;
the KDF itself via the reference argon2(1) CLI).
Language: Python 3 (standard library only — subprocess drives the `argon2`
binary, the same reference C library the TS build reaches through WASM).
CosmoDev polyglot showcase port of the `argon2` tool, ported from
src/lib/argon2.ts (the canonical TypeScript implementation).
The TS build drives the reference C library compiled to WASM
(argon2-browser), but hashlib has no Argon2. Like the JavaScript / Ruby /
Swift siblings, this port keeps the PHC parser, validator and Base64 codec
pure Python and delegates the KDF itself to that same library through its
CLI: `argon2` (https://github.com/P-H-C/phc-winner-argon2) must be on PATH
for argon2_hash / argon2_verify (argv ARRAY, shell=False; its salt is an
argv *string* that must be valid UTF-8, so salts travel as 32-char hex).
PHC format: $argon2id$v=19$m=65536,t=3,p=1$<b64 salt>$<b64 digest> — the self-contained string you store in a DB; unpadded standard Base64 fields.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import base64
import math
import re
import secrets
import subprocess
ARGON2_DEFAULTS = {"memory": 65_536, "iterations": 3, "parallelism": 1, "hashLength": 32} # OWASP profile.
SALT_BYTES = 16 # Random salt size in bytes (128 bits - the PHC recommendation).
_CLI_FLAG = {"argon2d": "-d", "argon2i": "-i", "argon2id": "-id"} # CLI flag per PHC "type".
_PHC_RE = re.compile(r"^\$(argon2(?:d|i|id))\$v=(\d+)\$m=(\d+),t=(\d+),p=(\d+)"
r"\$([A-Za-z0-9+/]+)(?:\$([A-Za-z0-9+/]+))?$")
def _phc_base64_to_bytes(b64: str) -> bytes:
"""Unpadded standard Base64 (the PHC encoding) -> bytes; the '=' padding
PHC strips is re-added. ValueError on a non-alphabet char or bad length."""
if not b64:
raise ValueError("Invalid Argon2 string: empty Base64 field")
if not re.fullmatch(r"[A-Za-z0-9+/]+", b64):
raise ValueError("Invalid Argon2 string: non-Base64 characters")
if len(b64) % 4 == 1:
raise ValueError("Invalid Argon2 string: impossible Base64 length")
return base64.b64decode(b64 + "=" * (-len(b64) % 4), validate=True)
def parse_argon2(encoded: str) -> dict:
"""Parse a PHC-format Argon2 string into its typed parameters (any of
argon2d/i/id; digest optional); salt and hash come back as lowercase hex."""
m = _PHC_RE.match(encoded.strip())
if not m:
raise ValueError("Invalid Argon2 string: expected $argon2id$v=19$m=…,t=…,p=…$salt$hash")
return {"type": m[1], "version": int(m[2]), "memory": int(m[3]), "iterations": int(m[4]),
"parallelism": int(m[5]), "salt": _phc_base64_to_bytes(m[6]).hex(),
"hash": _phc_base64_to_bytes(m[7]).hex() if m[7] else ""}
def _normalize_options(options: dict | None) -> dict:
"""Validate + normalise hashing parameters, raising with a clear message."""
opts = {**ARGON2_DEFAULTS, **(options or {})}
for key, low, high, message in (
("memory", 1024, None, "Memory must be at least 1024 KiB"),
("iterations", 1, None, "Iterations must be at least 1"),
("parallelism", 1, None, "Parallelism must be at least 1"),
("hashLength", 16, 64, "Hash length must be between 16 and 64 bytes"),
):
if not (isinstance(v := opts[key], (int, float)) and math.isfinite(v)
and low <= v and (high is None or v <= high)):
raise ValueError(message)
return opts
def _run_argon2(args: list[str], password: str) -> str:
"""Run `argon2` with `password` on stdin; return its trimmed stdout (the PHC string)."""
proc = subprocess.run(["argon2", *args], input=password.encode("utf-8"), capture_output=True)
if proc.returncode != 0:
message = proc.stderr.decode("utf-8", "replace").strip()
raise RuntimeError(f"argon2 failed: {message or f'exit code {proc.returncode}'}")
return proc.stdout.decode("utf-8").strip()
def argon2_hash(password: str, options: dict | None = None) -> dict:
"""Hash a password with Argon2id; returns the digest (hex), the salt
(hex), and the self-contained PHC string. A fresh random 16-byte salt is
generated per call unless `options["salt"]` (bytes) is given."""
opts = _normalize_options(options)
explicit = (options or {}).get("salt")
salt_text = (bytes(explicit) if explicit is not None else secrets.token_bytes(SALT_BYTES)).hex()
encoded = _run_argon2(
[salt_text, _CLI_FLAG["argon2id"], "-v", "13", "-e", "-k", str(opts["memory"]),
"-t", str(opts["iterations"]), "-p", str(opts["parallelism"]), "-l", str(opts["hashLength"])],
password,
)
# The digest is the final PHC segment, read back so hash/encoded agree.
return {"hash": _phc_base64_to_bytes(encoded.split("$")[-1]).hex(), "encoded": encoded,
"salt": salt_text.encode("ascii").hex()}
def argon2_verify(encoded: str, password: str) -> bool:
"""Verify a password against a PHC-format encoded hash: True on match,
False on mismatch; raises only on malformed input or a runtime error.
The CLI has no verify mode, so the hash is recomputed with the embedded
parameters + salt and compared (what argon2_verify does in C)."""
params = parse_argon2(encoded) # validate format up front
segments = encoded.strip().split("$")
try: # argv must be valid UTF-8: raw-byte salts cannot round-trip.
salt_text = _phc_base64_to_bytes(segments[4]).decode("utf-8")
except UnicodeDecodeError as exc:
raise ValueError("Salt is not ASCII; the argon2 CLI takes its salt as an argv string") from exc
recomputed = _run_argon2(
[salt_text, _CLI_FLAG[params["type"]], "-v", "13", "-e", "-k", str(params["memory"]),
"-t", str(params["iterations"]), "-p", str(params["parallelism"]),
"-l", str(len(params["hash"]) // 2 or ARGON2_DEFAULTS["hashLength"])],
password,
)
if params["hash"]:
return recomputed.split("$")[-1] == segments[5]
return recomputed == encoded.strip() # No digest: compare whole PHC strings.
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 →