Password Hashing Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Password Hashing runs in O(n) time and O(1) space, in Python as in every other language.
- ✓hashlib carries two password KDFs directly: hashlib.scrypt(password, salt=..., n=..., r=..., p=..., dklen=..., maxmem=...) and hashlib.pbkdf2_hmac('sha256', pw, salt, iterations).
- ✓Reviewers want the parameters stored next to the digest, not baked into a constant that nobody can change: an argon2-cffi PHC string, or your own alg$params$salt$dk.
- ✓The Python trap: hashlib.scrypt is capped by OpenSSL's memory ceiling through maxmem, which defaults to 0, meaning roughly 32 MiB.
- ✓pbkdf2_hmac, scrypt and argon2-cffi all execute inside C and release the GIL, so a thread pool genuinely parallelises logins on multiple cores; pure-Python KDF loops do not and are hundreds of times slower.
What Password Hashing actually is
Password Hashing in Python: what you actually reach for
Python implementation
import base64
import hashlib
import hmac
import os
import unicodedata
MAXMEM = 128 * 1024 * 1024
def hash_password(password: str) -> str:
pw = unicodedata.normalize("NFKC", password).encode("utf-8")
salt = os.urandom(16)
n, r, p = 2 ** 15, 8, 1
dk = hashlib.scrypt(pw, salt=salt,
n=n, r=r, p=p, dklen=32, maxmem=MAXMEM)
return "scrypt${}${}${}${}${}".format(
n, r, p,
base64.b64encode(salt).decode(),
base64.b64encode(dk).decode(),
)
def verify_password(password: str, stored: str) -> bool:
try:
alg, n, r, p, salt_b64, dk_b64 = stored.split("$")
except ValueError:
return False
if alg != "scrypt":
return False
pw = unicodedata.normalize("NFKC", password).encode("utf-8")
expected = base64.b64decode(dk_b64)
dk = hashlib.scrypt(pw,
salt=base64.b64decode(salt_b64),
n=int(n), r=int(r), p=int(p),
dklen=len(expected), maxmem=MAXMEM)
return hmac.compare_digest(dk, expected)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Password Hashing?
hashlib carries two password KDFs directly: hashlib.scrypt(password, salt=..., n=..., r=..., p=..., dklen=..., maxmem=...) and hashlib.pbkdf2_hmac('sha256', pw, salt, iterations). Both are thin wrappers over OpenSSL. Compare with hmac.compare_digest, salt with os.urandom or secrets.token_bytes. There is no Argon2 or bcrypt in the standard library: use argon2-cffi (argon2.PasswordHasher, which emits and parses PHC strings and offers check_needs_rehash) or the bcrypt package. The crypt module was deprecated and removed in Python 3.13, so crypt.crypt-based code no longer runs on current interpreters.
What is the most common Python mistake when implementing Password Hashing?
hashlib.scrypt is capped by OpenSSL's memory ceiling through maxmem, which defaults to 0, meaning roughly 32 MiB. Realistic parameters such as n=2**17, r=8 need about 128 MiB, so the call raises ValueError('memory limit exceeded') on the exact machine you tuned it for, while a lower n on your laptop passed. You must pass maxmem explicitly, at least 128*n*r bytes plus slack. The other Python-only break is the removal of the crypt module in 3.13: code doing crypt.crypt(pw, crypt.mksalt(crypt.METHOD_SHA512)) and older passlib handlers built on it stop importing after an interpreter upgrade.
How does Password Hashing actually perform in Python?
pbkdf2_hmac, scrypt and argon2-cffi all execute inside C and release the GIL, so a thread pool genuinely parallelises logins on multiple cores; pure-Python KDF loops do not and are hundreds of times slower. The real cost is architectural: a 150 ms hash on a synchronous WSGI worker holds that worker for 150 ms, so a handful of concurrent logins exhausts a small worker pool. Under asyncio, wrap the call in loop.run_in_executor or you block the whole event loop, not just one request. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.