"""Password KDF and HTTP credential parsing (Basic / opaque Bearer).""" import base64 import binascii import hashlib import hmac import os import re USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z") SCRYPT_N = 2 ** 14 SCRYPT_R = 8 SCRYPT_P = 1 SCRYPT_LEN = 32 def hash_password(password): salt = os.urandom(16) derived = hashlib.scrypt( password.encode("utf-8"), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P, dklen=SCRYPT_LEN ) return "scrypt$%d$%d$%d$%s$%s" % ( SCRYPT_N, SCRYPT_R, SCRYPT_P, salt.hex(), derived.hex() ) def verify_password(password, stored): try: scheme, n, r, p, salt_hex, digest_hex = stored.split("$") if scheme != "scrypt": return False derived = hashlib.scrypt( password.encode("utf-8"), salt=bytes.fromhex(salt_hex), n=int(n), r=int(r), p=int(p), dklen=len(bytes.fromhex(digest_hex)), ) return hmac.compare_digest(derived, bytes.fromhex(digest_hex)) except (ValueError, TypeError): return False def token_hash(token): return hashlib.sha256(token.encode("utf-8")).hexdigest() def parse_basic(header): """Return (username, password) or None. Colon inside the password is allowed.""" if not header or not header.lower().startswith("basic "): return None encoded = header[6:].strip() try: raw = base64.b64decode(encoded, validate=True).decode("utf-8") except (ValueError, UnicodeDecodeError, binascii.Error): return None if ":" not in raw: return None username, password = raw.split(":", 1) if not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128: return None return username, password def bearer_token(header): if not header or not header.lower().startswith("bearer "): return None token = header[7:].strip() return token or None