PREP WITH PROOF
Menu
CYBERSECURITY / PRACTICAL GUIDE

Password Hashing: Salt, scrypt and Why SHA-256 Is Not Enough

Understand password salts and scrypt with a tested Python verifier. Check malformed records, UTF-8 handling, resource limits and safe password-hash migration.

THE QUICK ANSWER

Use a password hashing function with a fresh salt and an explicit cost policy. A salt separates records but does not make SHA-256 expensive to guess. Verification must reproduce the stored policy and reject unsupported formats before costly work.

A stolen database changes the password problem

A login endpoint can reject repeated guesses, but a stolen password table lets an attacker test candidates without calling that endpoint. The stored representation must make each offline guess expensive. Merely replacing a plaintext password with a SHA-256 digest leaves a fast guessing operation, even though the digest looks unreadable.

The goal is a verifier: enough information to check a supplied password without storing the password itself. Encryption solves a different requirement, because possession of the decryption key allows recovery of the original value. Ordinary password login should not need that recovery capability.

This guide separates three decisions that are often mixed together: the salt that separates records, the password hashing function that imposes work, and the record format that lets a verifier reproduce the calculation. The runnable Python lab makes those boundaries visible. It is a learning fixture, not a replacement for a maintained authentication framework or identity provider.

A salt can be public and still be useful

A salt is a fresh random value associated with one stored password verifier. Store it alongside the derived output. On a later login, retrieve that salt and use it again with the submitted password. Generating another salt during verification would calculate a different value and reject the correct password.

Two accounts using the same password should normally have different verifier records because their salts differ. This frustrates reuse of precomputed results across accounts. It does not make a weak password unpredictable, and an attacker who has the database also has its salts. Salting a fast hash therefore does not supply the deliberate computational cost of a password hashing function.

A pepper is a separate secret, kept outside the password database. It has its own storage and rotation problem. It is not a substitute for either the salt or the work factor. The lab omits a pepper so that no separate secret-management scheme is implied by the example.

Stored itemSecret?Purpose in this lab
Format identifierNoSelect the exact verification policy
SaltNoGive each record an independent input
Derived outputSensitive verifier dataCompare against the submitted password derivation
Plaintext passwordYes; never persisted hereTransient input to creation or verification

Choose an algorithm before inventing a record format

OWASP currently prefers Argon2id and recommends scrypt when Argon2id is unavailable. This lab uses scrypt because it is exposed by Python hashlib on supported OpenSSL builds. It uses N=131072, r=8 and p=1, a configuration listed in the OWASP guidance checked for this article. These are explicit lab settings, not a claim that every service can safely support unlimited simultaneous verifications.

The work factor determines the cost of a guess; output length is not a substitute for it. The 32-byte output in this example does not mean 32 bytes of memory are required. The main scrypt memory term for these parameters is about 128 MiB, plus implementation overhead. The code gives OpenSSL a 256 MiB per-call ceiling through maxmem.

Budget at service level as well as per request. Ten concurrent derivations can create very different resource pressure from one local test. Select a maintained integration, benchmark representative login traffic, and bound concurrency before enabling a new policy. No throughput or latency benchmark is claimed here.

Run the bounded verifier lab

Save the code as password_lab.py and run python3 password_lab.py on a Python build providing hashlib.scrypt. The process performs several memory-intensive derivations sequentially. It prints a single PASS line when every assertion succeeds; it does not print passwords or stored records.

The format is deliberately local to this demonstration. pwp-scrypt-v1 means exactly the fixed parameters declared above it. The record contains 16 salt bytes encoded as 32 hexadecimal characters and 32 derived bytes encoded as 64 hexadecimal characters. Including the identifier and separators gives a total length of 111 characters.

import hashlib
import hmac
import re
import secrets

# Educational, fixed-policy record. Not a general password-hash parser.
PREFIX = "pwp-scrypt-v1"
N, R, P = 131072, 8, 1
SALT_BYTES, KEY_BYTES = 16, 32
MAXMEM = 256 * 1024 * 1024
RECORD = re.compile(r"pwp-scrypt-v1\$[0-9a-f]{32}\$[0-9a-f]{64}", re.ASCII)


def password_bytes(password):
    if not isinstance(password, str):
        raise TypeError("password must be text")
    data = password.encode("utf-8")
    if not 1 <= len(data) <= 1024:
        raise ValueError("lab password must be 1..1024 UTF-8 bytes")
    return data


def derive(data, salt):
    return hashlib.scrypt(data, salt=salt, n=N, r=R, p=P,
                          dklen=KEY_BYTES, maxmem=MAXMEM)


def create_record(password):
    data = password_bytes(password)
    salt = secrets.token_bytes(SALT_BYTES)
    key = derive(data, salt)
    return f"{PREFIX}${salt.hex()}${key.hex()}"


def verify(password, record):
    # Validate before expensive work; never read cost parameters from input.
    if not isinstance(record, str):
        return False
    if len(record) != 111 or RECORD.fullmatch(record) is None:
        return False
    _, salt_hex, key_hex = record.split("$")
    try:
        data = password_bytes(password)
    except (TypeError, ValueError, UnicodeError):
        return False
    actual = derive(data, bytes.fromhex(salt_hex))
    return hmac.compare_digest(actual, bytes.fromhex(key_hex))


def main():
    password = "Example-only password 42!"
    first = create_record(password)
    second = create_record(password)
    assert first != second
    assert verify(password, first) and verify(password, second)
    assert not verify("wrong password", first)
    assert not verify(password + " ", first)  # No silent stripping.
    assert not verify("x" * 1025, first)
    assert not verify(password, first[:-1])
    assert not verify(password, first + "\n")
    assert not verify(password, first.replace(PREFIX, "unknown-v1"))
    salt, key = first.split("$")[1:]
    altered = ("0" if key[0] != "0" else "1") + key[1:]
    assert not verify(password, f"{PREFIX}${salt}${altered}")
    unicode_record = create_record("caf\u00e9 is an example")
    assert verify("caf\u00e9 is an example", unicode_record)
    print("PASS: salts, matches, mismatches, bounds, format and UTF-8")


if __name__ == "__main__":
    main()

What the assertions actually establish

The first two records exercise fresh salt generation for the same input. Both verify with the original password, while a different password and a trailing-space variant fail. The modified-output test changes one hexadecimal digit without breaking the record syntax; it checks a genuine digest mismatch rather than only parser rejection.

The truncated record, extra newline and unknown identifier test the format boundary. The oversized password is rejected before a derivation. The Unicode case confirms that creation and verification use the same UTF-8 byte representation. None of these tests proves that a complete login service is secure; they establish the specific behavior of this fixture.

The comparison uses hmac.compare_digest on two byte strings of the same expected length. This avoids relying on ordinary equality for the digest comparison. It does not make the whole authentication flow take identical time: malformed records are rejected early and resource failures remain possible. Treat account enumeration and timing at the endpoint level as separate design work.

Do not let a stored record choose unlimited work

A flexible password library usually stores an algorithm identifier, cost settings, salt and derived value together. That makes migration possible, but the verification path must have a policy for which settings it accepts. A parser that accepts arbitrary memory or iteration values can turn a corrupted or attacker-controlled record into expensive work.

The lab takes a narrower approach: only one identifier and one parameter set are accepted. It checks the complete length and lowercase hexadecimal alphabet before decoding anything. It never converts an input field into a cost factor. This trades migration flexibility for a simple, inspectable boundary suitable for a lesson.

For a real application, use the framework library format and its documented verification and rehash checks. Define a finite set of supported historical policies. An unknown version should create an operational signal, not trigger a guess about what the record probably meant. Never silently fall back to a cheaper algorithm after a resource or parsing error.

Make password text handling consistent

This demonstration preserves the exact text it receives and encodes it as UTF-8. It does not strip spaces, lowercase text or normalize Unicode. That is an explicit fixture choice, not a complete international password policy. Two visually similar strings can contain different code points and therefore produce different bytes.

A production service must define its text handling once and apply it consistently at enrollment, login, password change and recovery. If normalization is part of that policy, version and test it; introducing it only at login can prevent existing users from authenticating. The related Unicode normalization guide explains those representation differences.

The 1024-byte maximum is an input-resource bound for this lab, not a recommendation for minimum password strength or a universal character limit. Multi-byte text can reach a byte limit with fewer characters. A public product should explain its accepted limits and reject excess input clearly instead of truncating it.

Handle resource errors and upgrades deliberately

If hashlib.scrypt is unavailable, use a supported runtime or maintained authentication integration. If the call reports a memory-limit error, inspect the runtime policy and available resources. Do not remove work-factor settings until the code happens to run. maxmem limits one invocation; it does not reserve memory or protect the whole process against concurrent requests.

The verifier intentionally lets errors from the derivation engine propagate. A surrounding login service should return a generic operational failure, emit a redacted internal event and alert when verification infrastructure fails. Returning False for every infrastructure error would misleadingly classify outages as incorrect passwords. Logs should contain an error class and request correlation identifier, never the submitted password.

For migration, verify with an explicitly supported older policy first. After successful authentication, create a fresh record under the current policy and update the stored value safely. A compare-and-update against the old value can prevent that background upgrade from overwriting a concurrent password reset. Older records cannot generally be upgraded by recovering their original plaintext.

Keep offline and online defenses separate. An expensive verifier reduces offline guessing efficiency; endpoint rate limits, abuse detection, recovery controls and multifactor authentication address additional threats. A salt is not an access token, and a password verifier should not be reused as a session credential.

Review the verifier boundary, not just the hash call

A useful review follows the whole path: where the password arrives, how text becomes bytes, how a record is parsed, which cost policies are accepted, and what happens when the derivation fails. The hash function call is only one part of that path.

Use the lab to understand salts and reproducible verification. Use maintained authentication components for deployed login systems, and retain boundary tests when policies change. The strongest practical outcome is a record format and operational process that remain understandable when the first migration, malformed record or memory-pressure incident occurs.

KEEP THESE THREE THINGS

Your next steps

  1. Salts are stored with each verifier; they are not decryption keys.
  2. Choose password-specific work factors, then budget concurrent verification.
  3. Validate record formats and accepted policies before expensive derivation.
  4. Upgrade records after successful verification without overwriting password resets.

Sources & official resources

Linked resources checked on 2026-11-12. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →