Python

Password Hashing with hashlib.scrypt

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Hash a password with the stdlib scrypt (memory-hard, slow by design — resistant to GPU/ASIC attacks). Stores salt + parameters inline so verification doesn't need a separate config.
Python
Raw
import base64
import hashlib
import os
import hmac

def hash_password(password: str) -> str:
    salt = os.urandom(16)
    n, r, p = 2 ** 14, 8, 1
    key = hashlib.scrypt(password.encode(), salt=salt, n=n, r=r, p=p, dklen=32)
    return f"scrypt${n}${r}${p}${base64.b64encode(salt).decode()}${base64.b64encode(key).decode()}"

def verify_password(password: str, stored: str) -> bool:
    try:
        algo, n, r, p, salt_b64, key_b64 = stored.split("$")
        if algo != "scrypt": return False
        salt = base64.b64decode(salt_b64)
        key  = base64.b64decode(key_b64)
        candidate = hashlib.scrypt(password.encode(), salt=salt, n=int(n), r=int(r), p=int(p), dklen=len(key))
        return hmac.compare_digest(candidate, key)
    except (ValueError, TypeError):
        return False

stored = hash_password("hunter2")
print(verify_password("hunter2", stored))   # True
print(verify_password("wrong",   stored))   # False
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.