Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Password Hashing Implementation in Python

14 min readintermediate
Website QA and SEO audits

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 stores a login credential as a deliberately slow, salted, one-way derivation instead of the password itself. You verify by re-deriving with the stored salt and parameters and comparing in constant time. The cost parameters (iterations, memory, parallelism) exist to make offline cracking of a stolen table expensive. The modern choices are Argon2id, scrypt, bcrypt and PBKDF2 with a high iteration count. A plain SHA-256 or MD5 digest is not password hashing: a GPU computes billions of those per second. You reach for this the moment you own a users table with a password column, and again every few years when you raise the cost and rehash on next login.

Password Hashing in Python: what you actually reach for

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.

Python implementation

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. They want hmac.compare_digest, never ==, and never a hexdigest compared with string equality. They reject hashlib.sha256(salt + pw). PasswordHasher.check_needs_rehash on every successful login is the expected upgrade path. Encode to bytes explicitly with .encode('utf-8') at the boundary rather than letting bytes and str mix.
python
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 Free

The Python-specific trap

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.

Performance in Python, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Password Hashing between languages.

Real-World Applications

Password Hashing is used extensively in production software: authentication systems, payment processing, encrypted communications, and data protection mechanisms depend on this technique. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Password Hashing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Password Hashing appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Password Hashing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Password Hashing to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.