"""Password hashing and token helpers. Standard library only.""" from __future__ import annotations import base64 import hashlib import hmac import secrets # scrypt parameters: ~16 MiB memory, tens of milliseconds per hash. _N, _R, _P = 2**14, 8, 1 _DKLEN = 32 def _b64(b: bytes) -> str: return base64.urlsafe_b64encode(b).decode().rstrip("=") def _unb64(s: str) -> bytes: return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) def hash_password(password: str) -> str: salt = secrets.token_bytes(16) dk = hashlib.scrypt(password.encode(), salt=salt, n=_N, r=_R, p=_P, dklen=_DKLEN) return f"scrypt${_N}${_R}${_P}${_b64(salt)}${_b64(dk)}" def verify_password(password: str, stored: str) -> bool: try: scheme, n, r, p, salt, dk = stored.split("$") if scheme != "scrypt": return False expected = _unb64(dk) actual = hashlib.scrypt( password.encode(), salt=_unb64(salt), n=int(n), r=int(r), p=int(p), dklen=len(expected), ) except (ValueError, TypeError): return False return hmac.compare_digest(actual, expected) # Used to equalise timing when a login names a user that doesn't exist. DUMMY_HASH = hash_password(secrets.token_urlsafe(16)) def new_token() -> str: """A high-entropy secret for host tokens and session IDs.""" return secrets.token_urlsafe(32) def token_hash(token: str) -> str: # Tokens are 256-bit random, so a fast hash is fine; we only store this. return hashlib.sha256(token.encode()).hexdigest()