scrypt Password Hash And Verify
Hash passwords with scrypt and a per-user salt, then verify them with a constant-time comparison.
Code
import hashlib
import hmac
import os
N = 2 ** 14
R = 8
P = 1
KEY_LEN = 32
SALT_LEN = 16
def hash_password(password: str) -> str:
salt = os.urandom(SALT_LEN)
digest = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=N, r=R, p=P, dklen=KEY_LEN)
return f'scrypt${N}${R}${P}${salt.hex()}${digest.hex()}'
def verify_password(password: str, encoded: str) -> bool:
parts = encoded.split('$')
if len(parts) != 5 or parts[0] != 'scrypt':
return False
_, n, r, p, rest = parts
salt_hex, digest_hex = rest[:SALT_LEN * 2], rest[SALT_LEN * 2:]
expected = bytes.fromhex(digest_hex)
digest = hashlib.scrypt(password.encode('utf-8'), salt=bytes.fromhex(salt_hex),
n=int(n), r=int(r), p=int(p), dklen=len(expected))
return hmac.compare_digest(digest, expected)How the snippet works
scrypt Password Hash And Verify is built around the functions hash_password and verify_password.
What to watch for
- Plan for an install step:
hmacis a real dependency, resolved by the package manager.
Applying it
The main signature reads def hash_password(password: str) -> str
hash_password is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def hash_password(password: str) -> str:
salt = os.urandom(SALT_LEN)
digest = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=N, r=R, p=P, dklen=KEY_LEN)
return f'scrypt${N}${R}${P}${salt.hex()}${digest.hex()}'
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Password Entropy EstimatorEstimate a password's alphabet size and Shannon entropy in bits, then translate that into offline crack times at realistic guessing rates.Password Strength MeterScore a password from 0 to 100 based on length and character classes, and get clear suggestions to make it stronger. Everything runs locally.
FAQ
- Do I need to install anything before running this?
- Yes: `hmac` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.