Password Hashing and Message Integrity

Learn why passwords need slow, salted hashes, how SHA-256 differs from a keyed MAC, and how to verify credentials and data safely.

published: reading time: 10 min read author: Geek Workbench
Quick Summary

Password hashing, integrity digests, and message authentication codes all use hash functions, but they solve different problems. This guide compares Argon2id, scrypt, bcrypt, SHA-256, HMAC, and digital signatures, with practical verification and key-handling guidance. Use its scenarios and checklist to select a suitable primitive, tune password-hash costs, and avoid confusing integrity with sender identity or replay protection.

Password Hashing and Message Integrity

Introduction

A hash function turns input into a fixed-size digest. That sounds like one tool with one job, but security systems use hashes in very different ways. Password storage needs a function that makes each guess costly. File integrity checks need a fast way to detect changes. Message authentication needs a secret key so that an attacker cannot forge a valid check value.

These mechanisms are related, but they are not interchangeable. If a database leaks, a fast SHA-256 digest makes password guessing easier. If a file hash is public, it does not prove who created the file. Choosing the right construction starts with asking what you need to protect.

Choosing the Right Primitive

graph TD
    A[What are you protecting?] --> B[User password]
    A --> C[File or message bytes]
    B --> D[Argon2id, scrypt, or bcrypt]
    D --> E[Store salt and parameters with hash]
    E --> F[Verify with the password-hashing library]
    C --> G{Need to authenticate a shared-key message?}
    G -->|No| H[Hash and compare with a trusted digest]
    G -->|Yes| I[HMAC or another reviewed MAC]
    I --> J[Verify tag in constant time]

The decision follows the threat. Password databases face offline guessing, so the password function should be deliberately costly. Data checks need speed, but the expected digest must come from somewhere an attacker cannot also rewrite. When a shared secret must authenticate a message, use a MAC and protect its key.

Safe Password Verification

On sign-up or password change, pass the password to a maintained password-hashing library configured with a unique random salt and an appropriate cost. Store the encoded result, which normally carries the algorithm name, salt, and parameters. Never log the plaintext password or the full encoded hash.

On login, pass the submitted password and stored encoded value to the library’s verify operation. Do not recompute a bare hash and compare strings yourself. A library can parse parameters, perform the expected derivation, and compare results safely. Treat malformed or unsupported stored values as verification failures; do not silently fall back to SHA-256 or plaintext comparison.

A successful check proves only that the submitted password matches the stored verifier. It does not prove the account owner is present or protect the session after login. Rate limits, monitoring, secure session handling, recovery controls, and stronger authentication options still matter. See Identity Lifecycle and Account Recovery for the surrounding account controls.

When to Use

  • Password storage: use Argon2id where available; use scrypt or bcrypt when a reviewed implementation and deployment constraints call for them. Select and benchmark a current cost profile rather than copying stale settings.
  • File or artifact checks: use SHA-256 or another approved general-purpose digest when the expected digest is distributed through a trusted, independent channel.
  • Authenticated messages between services: use HMAC or another reviewed MAC when both sides can protect a shared key.
  • Public verification: use a digital signature when verifiers need to check authenticity without sharing the signing secret.
  • Content identifiers: use a collision-resistant digest when a stable identifier is useful, while remembering that an identifier by itself is not proof of authorization or provenance.

These choices support different parts of the confidentiality, integrity, and availability model. The right primitive still depends on trust boundaries and on who can modify the data and its expected value.

Production Failure Scenarios

A database dump contains fast password hashes

If passwords were stored with SHA-256, MD5, or another fast general hash, an attacker can test huge numbers of guesses offline. Unique salts stop precomputed tables from applying across accounts, but they do not make each guess expensive. Migrate to a password-hashing function and reset passwords where exposure or risk warrants it.

Cost settings overload the login service

Increasing memory and time costs makes offline guesses more expensive, but every legitimate login also consumes those resources. An attacker may exploit that cost to exhaust application capacity with many requests. Benchmark under concurrency, rate-limit authentication attempts, and monitor latency and resource use. Keep the parameters strong enough for the threat while within a controlled service budget.

The expected file hash comes from the same untrusted source

A package and its checksum are downloaded from a compromised mirror. Comparing them confirms only that the two downloaded values agree. Retrieve a signature or digest from an independently trusted source, or verify a signature against a trusted public key.

A valid MAC is replayed

A receiver checks an HMAC correctly but accepts the exact same request multiple times. The tag protects authenticity and integrity; it does not provide freshness. Bind a unique request identifier or sequence value into the authenticated data and track its use according to the protocol.

Trade-Off Table

Mechanism Typical purpose Speed and cost What it does not provide
Argon2id, scrypt, bcrypt Password verification after a database leak Deliberately costly; tuned per deployment Encryption, protection from weak passwords, or login rate limiting
SHA-256 digest Fast content or integrity comparison Fast and inexpensive Sender authentication if the expected digest can be replaced
HMAC-SHA-256 Integrity and authentication between parties sharing a key Fast; requires secure key handling Public verification or replay prevention on its own
Digital signature Publicly verifiable message or artifact authenticity More key and protocol management Confidentiality or replay protection by itself

A “stronger” algorithm is not always the better fit. The desired property and attacker capability determine the choice. For CIA context and threat modeling, see Threat Modeling Basics.

Observability Checklist

  • Measure password verification latency and resource consumption under normal and peak concurrency.
  • Alert on unusual authentication volume, repeated failures, and rate-limit activity without logging submitted passwords.
  • Track the password-hash algorithm and parameter versions in a way that does not expose password material.
  • Record MAC verification failures and key-version usage, while avoiding logs that reveal secret keys or sensitive message contents.
  • Monitor key rotation and expiry events, and test that services can verify data made with still-supported key versions.
  • For file verification, record which trusted source or signing key supplied the reference digest.

Telemetry helps reveal operational trouble; it does not make a weak primitive safe. Keep logs access-controlled and retain only what supports detection and response.

Security and Compliance Notes

Use maintained cryptographic libraries and follow your platform’s approved algorithms and key-management requirements. Organizations operating under a compliance regime may have to use specific validated modules or approved configurations; an algorithm name alone does not establish compliance. Document the selected primitive, parameters, key owners, rotation plan, and recovery process.

Password-hash parameters need periodic review as hardware and workload change. Plan a gradual upgrade path and keep old settings only long enough to verify existing accounts and rehash them after successful login. If the database or pepper is exposed, assess the incident, invalidate affected credentials or sessions as appropriate, and follow the organization’s response process.

A checksum is not a substitute for a signature when provenance matters. A MAC is not encryption: observers can still read the message unless a separate encryption mechanism protects it. These are useful pieces of a broader security design, as described in Security Principles and Defense in Depth.

Common Pitfalls / Anti-Patterns

  • Using SHA-256 for passwords: it is intentionally fast. Adding a salt does not change that.
  • Using one static salt for every user: salts should be random and unique per password record.
  • Treating a salt as a secret: store it with the hash. Keep any optional pepper separate and carefully managed.
  • Rolling your own password scheme: use a maintained library with a supported password-hashing function.
  • Comparing MAC tags with ordinary early-exit string equality: use a constant-time verification API.
  • Assuming a checksum proves the publisher: integrity against a trusted value and authenticated provenance are different claims.
  • Ignoring resource abuse: expensive password checks still need sensible request limits and capacity planning.
  • Assuming a MAC prevents replay: freshness must be part of the protocol and authenticated data.

Quick Recap Checklist

  • Store passwords with Argon2id, scrypt, or bcrypt through a maintained library.
  • Give each password record a unique random salt and tune the work factor for the production workload.
  • Verify passwords through the library’s verification function; never switch to a fast hash as a fallback.
  • Use an unkeyed hash only when the expected digest is trusted independently.
  • Use a MAC for shared-key message authentication and a signature for public verification.
  • Protect keys, compare tags safely, and design replay defenses when the protocol needs freshness.

Interview Questions

1. Why should a password database use Argon2id instead of SHA-256?
SHA-256 is designed to be fast, which lets an attacker test guesses quickly after stealing the database. Argon2id is a password-hashing function with tunable time and memory costs. Those costs make each offline guess more expensive. A unique salt is still required, and the work factor must be tuned for the service.
2. What problem does a salt solve, and is it secret?
A random, unique salt makes the same password produce different stored values across accounts and defeats reusable precomputed tables. The salt is normally stored alongside the password hash. It is not a secret and does not make a weak password resistant to guessing by itself.
3. What is the difference between a hash and an HMAC?
A cryptographic hash produces a digest from data without a secret key. Anyone can calculate it, so it can detect changes only when the expected digest is trusted separately. HMAC uses a shared secret key, so a valid tag shows that a key holder created it. It does not identify which holder created the tag.
4. Does a valid HMAC stop an attacker from replaying a message?
No. HMAC authenticates the contents that were tagged, but a previously valid message and tag can be sent again. A protocol must include and validate freshness data, such as a nonce or sequence number, to reject replays.

Further Reading

Conclusion

Password hashes, integrity digests, and MACs all involve hash functions, but they answer different questions. Use a deliberately costly password-hashing function to store credentials, a fast digest to compare data against a trusted reference, and a keyed MAC when shared-secret authentication is required. Then protect the surrounding system: tune costs, manage keys, verify through reviewed APIs, and account for replay, resource abuse, and the limits of each primitive.

Category

Related Posts

Cryptography Concepts and Safe Algorithms

Understand encryption, hashes, digital signatures, keys, and secure randomness, then learn how to choose vetted cryptographic libraries for real systems.

#cryptography #cybersecurity #encryption

Public-Key Infrastructure and Certificates

Learn how public-key infrastructure uses certificates and trusted authorities to verify names, support TLS, and avoid common renewal and revocation failures.

#cybersecurity #pki #certificates

Merkle Trees in Git

Learn how Git commits, trees, and blobs form a content-addressed object graph, and what hashes can and cannot prove about repository integrity.

#git #version-control #merkle-tree