Password Security: Hashing, Salting, MFA and Passkeys

Passwords are the oldest and still the most common way to prove identity online, and they remain one of the weakest links in security. Most breaches involve stolen or reused credentials in some way. This lesson covers how passwords should be stored, how credential attacks work in principle, how to defend against them, and how multi-factor authentication and passkeys change the picture.

How Not to Store Passwords

MethodProblem
PlaintextAnyone who reads the database reads every password
Reversible encryptionIf the key is stolen with the database, all passwords are exposed
Fast hash (MD5, SHA-1, plain SHA-256)Billions of guesses per second are possible on commodity hardware
Unsalted hashIdentical passwords produce identical hashes; precomputed (rainbow) tables work

How to Store Passwords Correctly

Use a purpose-built password hashing function: deliberately slow, memory-hungry and salted.

  • Argon2id: the modern recommendation; tunable for time, memory and parallelism.
  • scrypt and bcrypt: well-established and acceptable.
  • PBKDF2: acceptable where compliance requires it, with a high iteration count.

A salt is a unique random value stored beside each hash. It ensures that two users with the same password have different hashes and defeats precomputed tables. A pepper is an additional secret kept outside the database (for example in a hardware module) that raises the cost of attack further. Always check OWASP’s Password Storage Cheat Sheet for current recommended parameters, as these settings rise over time.

Practice: hashing with a salt in Python

import hashlib, hmac, os

def hash_password(password: str):
    salt = os.urandom(16)
    digest = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
    return salt, digest

def verify_password(password: str, salt: bytes, expected: bytes) -> bool:
    digest = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
    return hmac.compare_digest(digest, expected)   # constant-time comparison

salt, stored = hash_password("correct horse battery staple")
print("salt:  ", salt.hex())
print("hash:  ", stored.hex())
print(verify_password("correct horse battery staple", salt, stored))  # True
print(verify_password("wrong guess", salt, stored))                   # False

Run it twice. The salt and hash differ every time even though the password is identical. In production, use a maintained library for Argon2id or bcrypt rather than writing your own wrapper.

Why Weak Passwords Fall: The Maths

The time to guess depends on how many possibilities exist and how fast an attacker can test them. Consider this simplified table, for an attacker with a stolen, fast-hashed database testing a very large number of guesses per second (the exact rate varies with hardware and hash type):

Password typePossibilities (approx.)Observation
6 lowercase letters266 ≈ 309 millionTrivial at high guess rates
8 mixed characters (about 95 symbols)958 ≈ 6.6 quadrillionFeasible for fast hashes; humans pick predictable patterns anyway
4 random common wordsabout (7,776 words)4 ≈ 3.7 × 1015 using a Diceware listStrong and memorable
6 random common wordsabout 2.2 × 1023Very strong passphrase

Human-chosen passwords are far weaker than the maths suggests, because people choose predictable words, names, dates and substitutions such as P@ssw0rd!. Attackers try the most likely passwords first. This is why length and randomness beat clever-looking complexity.

Credential Attacks: How They Work and How to Stop Them

AttackIdea (conceptual)Main defences
Brute forceTry many passwords against one accountAccount lockout or throttling, MFA, monitoring
Password sprayingTry a few common passwords across many accounts to avoid lockoutsMFA, blocking common passwords, detecting many accounts failing from one source
Credential stuffingUse username-password pairs leaked from other sitesUnique passwords, breached-password checks, MFA, bot detection, rate limits
Offline crackingGuess against a stolen hash database without rate limitsSlow salted hashes (Argon2id, bcrypt), long passwords
Phishing and keyloggersCapture the password directly from the userPhishing-resistant MFA, awareness, endpoint protection
Password reset abuseTake over accounts through weak recovery processesStrong recovery verification, notifications, MFA on reset

For legal practice, you can observe lockout and throttling behaviour on your own lab web application, and test hash speed differences with your own generated hashes. Do not attempt guessing attacks on accounts or services you do not own.

Modern Password Policy (NIST-Aligned)

NIST’s Digital Identity Guidelines (SP 800-63B) reflect research on what works:

  • Prefer length over complexity rules. Allow long passphrases (and all printable characters, including spaces).
  • Check new passwords against lists of breached and commonly used passwords.
  • Do not force periodic changes without evidence of compromise; forced rotation produces predictable patterns like Summer2026!.
  • Do not impose composition rules (must contain a symbol and a capital) that push users to predictable choices.
  • Allow paste and password managers.
  • Rate-limit attempts and monitor for abuse.
  • Offer multi-factor authentication and make strong options easy.

Multi-Factor Authentication (MFA)

MFA requires two or more factors from different categories: something you know, have or are. Not all MFA is equal:

MethodStrengthNotes
SMS codesWeakest MFAVulnerable to SIM swapping and interception, but still far better than a password alone
Email codesWeak to moderateOnly as secure as the mailbox
Authenticator app (TOTP)GoodTime-based codes; can still be phished in real time
Push notificationsGood, with number matchingVulnerable to “MFA fatigue” if users approve unexpected prompts
Hardware security keys (FIDO2/WebAuthn)StrongestPhishing-resistant; the key verifies the website’s real origin
PasskeysStrongest, user-friendlyFIDO2 credentials synced or device-bound; phishing-resistant

Passkeys

A passkey is a cryptographic key pair created for a specific website. The private key stays on your device (protected by a fingerprint, face or PIN) and the website stores only the public key. Logging in means your device signs a challenge from the site. There is no shared secret to steal from a server breach, nothing to guess and nothing to type into a fake site, because the credential only works for the genuine domain. Passkeys are the most promising replacement for passwords and are increasingly supported by major platforms.

Password Managers

A reputable password manager generates and stores unique, random passwords for every account, so a breach at one site cannot unlock others. Protect the manager itself with a long passphrase and MFA, keep recovery information safe, and review its breach alerts. For most people, it is the single most effective upgrade.

Practice Exercises

  1. Run the Python hashing example, then change n=2**14 to n=2**16 and time both. How does the cost change?
  2. Use a Diceware method (roll dice or use a trustworthy random word picker) to create a five-word passphrase and calculate its approximate possibilities.
  3. Check which of your accounts support passkeys or hardware keys and enable one on your most important account.
  4. In your lab web application, configure account lockout or rate limiting and describe the trade-off between security and the risk of users being locked out by attackers.
  5. Explain why SHA-256 alone is a bad password storage method even though SHA-256 is secure for other purposes.

Mentor tip: Teach everyone you know two habits: use a password manager so no two accounts share a password, and turn on the strongest MFA available on email accounts, because email controls every password reset.

Educational use only: practise security techniques only on systems you own or have explicit written permission to test.

Key takeaways
  • Store passwords with Argon2id, bcrypt or scrypt, using unique salts; never plaintext or fast hashes.
  • Length and randomness beat complexity rules; block breached passwords and avoid forced rotation.
  • Brute force, spraying and credential stuffing are stopped by throttling, unique passwords and MFA.
  • Phishing-resistant MFA (security keys and passkeys) is the strongest option.
  • Password managers make unique passwords practical for everyone.

Related Lessons