16 min read

Cryptography
Intermediate
A04

Key Management

Almost every cryptographic finding that matters in practice is not a broken algorithm. It is a key in the wrong place: in a repository, in an image layer, in a log line, or hashed with a function fast enough to try billions of guesses a second. The primitive was fine; the handling was not.

Two different findings that look alike

A committed credential is an incident — it is live until revoked, and the clock started when it was pushed. A weak password hash is a hygiene finding — exploitable only after a database read. They appear in the same scanner report and need different responses: revocation today versus a migration plan. Sorting them before triage is most of the work.

Hardcoded secrets

The pattern is always the same: a value that had to be somewhere got typed into the file that was easiest to edit. The interesting question is not how to grep for it — that is a solved problem — but what the value grants, because that decides whether the answer is a rotation or an incident.

settings.py
# settings.py - committed to the repository in 2019 and still there
AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"
AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
DATABASE_URL = "postgresql://app:S3cr3t-Passw0rd@db.internal:5432/app"
JWT_SIGNING_KEY = "change-me-in-production"
# settings.py - committed to the repository in 2019 and still there
AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"
AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
DATABASE_URL = "postgresql://app:S3cr3t-Passw0rd@db.internal:5432/app"
JWT_SIGNING_KEY = "change-me-in-production"

Environment variables are the floor, not the goal

Reading a secret from os.environ is a real improvement over hardcoding, and it is not a secret store. The process environment is dumped by crash reporters, printed by debug pages, captured by telemetry agents, readable from /proc/<pid>/environ on the same host, and inherited by every child process including shells. It raises the bar; it does not hold a long-lived key.

Secret scanning

A scanner that only looks at the working tree finds the secrets that are still there. The ones that matter were committed three years ago and removed in the next commit — still in the history, still valid. History is the target.

secret-scan.sh
# gitleaks 8.19+ replaced "detect" with explicit subcommands.
# "detect" still runs but is hidden from --help and prints no warning.
gitleaks git .                      # scan a repository's history
gitleaks dir ./src                  # scan a directory with no git history
gitleaks stdin < payload.txt        # scan a stream, e.g. in a pipeline

# CI: fail the job on findings, and keep the report for the ticket
gitleaks git . --redact --report-format sarif --report-path gitleaks.sarif

# pre-commit: staged changes only
gitleaks git --pre-commit --staged

# triage a hit without re-reading the diff
git log -p -S "$MATCH" --all -- .

gitleaks changed its commands

Since v8.19.0, detect and protect are deprecated in favour of gitleaks git, gitleaks dir and gitleaks stdin. The old commands still run but are hidden from the help output and print no warning — a pipeline that uses them looks healthy and is not on the supported path.

Password hashing

A password hash is judged by one number: how much it costs to test a guess. Any function designed to be fast at hashing files is a few orders of magnitude too cheap here, and a single round of SHA-256 is not a password hash no matter how long the output is.

auth.py
import hashlib

# fast, unsalted, and identical for two users with the same password
def hash_password(password: str) -> str:
    return hashlib.sha256(password.encode()).hexdigest()

# 1,000 iterations looks defensive and is not: it is a few milliseconds
def hash_password_slow(password: str) -> str:
    return hashlib.pbkdf2_hmac(
        "sha256", password.encode(), b"static-salt", 1000
    ).hex()
import hashlib

# fast, unsalted, and identical for two users with the same password
def hash_password(password: str) -> str:
    return hashlib.sha256(password.encode()).hexdigest()

# 1,000 iterations looks defensive and is not: it is a few milliseconds
def hash_password_slow(password: str) -> str:
    return hashlib.pbkdf2_hmac(
        "sha256", password.encode(), b"static-salt", 1000
    ).hex()
Algorithm Current parameters Note
Argon2id m=19456 KiB, t=2, p=1 First choice. Memory cost is the property that defeats GPUs and ASICs.
scrypt N=2^17, r=8, p=1 Requires raising maxmem; N=2^17 is 128 MiB per hash.
bcrypt cost >= 10 Truncates input at 72 bytes — pre-hash anything longer.
PBKDF2-HMAC-SHA256 600,000 iterations The compliant fallback when nothing memory-hard is available.
PBKDF2-HMAC-SHA1 1,400,000 iterations Legacy only — kept for compatibility with existing hashes.
MD5 / SHA-1 / SHA-256 single round not a password hash A finding on sight, whatever the input length.
scrypt-passwords.py
import hashlib, os

# hashlib.scrypt is keyword-only after the password, and dklen defaults
# to 64. N=2^17 allocates 128 MiB, so maxmem must be raised or OpenSSL
# aborts with "memory limit exceeded".
def hash_password(password: str) -> str:
    salt = os.urandom(16)
    n, r, p = 2 ** 17, 8, 1
    dk = hashlib.scrypt(
        password.encode(),
        salt=salt,
        n=n,
        r=r,
        p=p,
        maxmem=256 * 1024 * 1024,
        dklen=32,
    )
    return f"scrypt${n}${r}${p}${salt.hex()}${dk.hex()}"

def verify_password(stored: str, password: str) -> bool:
    scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
    assert scheme == "scrypt"
    dk = hashlib.scrypt(
        password.encode(),
        salt=bytes.fromhex(salt_hex),
        n=int(n), r=int(r), p=int(p),
        maxmem=256 * 1024 * 1024,
        dklen=len(bytes.fromhex(dk_hex)),
    )
    return dk.hex() == dk_hex       # use hmac.compare_digest in real code

Store the parameters, not just the hash

A hash string that carries its algorithm and cost — the way Argon2 and bcrypt do natively — is the difference between raising the cost next year and forcing a password reset. If the format is algorithm$params$salt$digest, verification reads the parameters from the record and re-hashes on successful login at the current cost.

Encryption keys

Every secret class needs different handling, and the most common mistake is treating them all the same. A user password never needs to be recoverable; a data encryption key does; a signing key should never leave the device that uses it.

Secret Where it belongs Threat it answers
User password Slow hash, per-user salt, parameters stored with the hash Offline cracking after a database read
Data encryption key KMS or HSM; envelope encryption with a per-object data key Database read, backup theft, insider access
Service credentials Secret manager with an identity-based policy, short-lived where possible Repository read, image layer read, log scrape
Signing private key HSM, never exportable; signing is an API call Forgery of tokens or artefacts, which survives rotation of everything else
Third-party API token Secret manager, per-environment, scoped to the minimum the integration needs A leaked token usually grants the integration, not the tenant

Rotation

A key you cannot rotate is a key you cannot revoke, which means a leak is permanent. Rotation is a design property, and it is decided by one question: does the ciphertext say which key produced it?

Envelope encryption answers it. Each object is encrypted with its own data key; the data key is encrypted with a long-lived master key in the KMS; the stored blob carries the wrapped data key and its identifier. Rotating the master key rewraps the data keys — a metadata operation — instead of re-encrypting the data. If the ciphertext carries no key identifier, rotation means re-encrypting everything while the application is running, which in practice means it never happens.

The signing key is the one that survives everything else

Rotating a database password revokes access. Rotating a token signing key invalidates every session, so teams put it off — and a leaked signing key lets an attacker mint an administrator token that outlives every other remediation. Give the signing key its own key identifier in the token header, publish both keys during a rollover window, and accept one forced re-login.

What actually happens

The committed key is rarely the interesting finding on its own. What makes it worth reporting is the path it represents — a route to the metadata service, a directory served by the web server, a build log that prints the environment, a public bucket nobody remembers. The key is the proof that the path exists.

The .env file inside the web root

A deployment that copies the project directory into a static host or a PHP document root serves /.env as a text file. The credential and the delivery mechanism are the same finding, and the second one is worse.

The metadata service

An SSRF that reaches 169.254.169.254 on a workload with an attached role returns credentials that need no repository at all. A page about key management is the right place to say it: the key never had to be committed for this to work.

The image layer

A key copied in during a build and deleted in a later layer is still in the image. Container registries serving that image to a wider audience than the repository is the usual reason a private repository still counts as public.

The CI log

A debug step that prints the environment, or a failing command that echoes its arguments, writes the secret into a log that is readable by everyone with repository access — retained for months, and frequently mirrored into a third-party observability platform.

Check Expected Where to look
A committed secret was rotated before the commit was removed New credential live, old credential revoked and observed failing The provider audit log
The scanner runs on history, not just the working tree The old commit still matches when scanned, and is allowlisted with a reason after rotation The scanning job output
Password hashing parameters match current OWASP guidance Argon2id m=19456 t=2 p=1, or scrypt N=2^17 r=8 p=1, or bcrypt cost 10 or more The user table / the auth configuration
Encryption keys are labelled with an identifier and a creation date Ciphertext records which key it needs, so rotation is possible without re-encrypting everything The ciphertext envelope
No key is read from an environment variable that is logged Process environment is dumped by the crash reporter, the debug page or the telemetry agent The crash dump and the logging configuration

Evidence for a Secret Finding

A committed key is easy to report and easy to report badly. Five things make it actionable:

Where it is, and whether it is live: File, line and commit, plus the result of a read-only call with the credential. A dead key in an old commit is a hygiene finding; a live key is an incident.

What it grants: The permission set, not the key type. An access key with full account access and one scoped to a single bucket are the same string and different incidents.

The first commit that contains it: git log -S gives it. This decides whether rotation is urgent and whether the history rewrite is worth doing at all.

Whether it is in a built artefact: A key in a frontend bundle or an image layer is public even if the repository is private. Check the deployed artefact, not just the source.

The provider audit window: How far back the logs go, so the response can say whether the key was used. Without this, every answer to the incident review is a guess.

When a Match Is Not a Secret

Scanner output and hash findings both generate noise. Four of the usual shapes:

  • Documented example credentials: AWS publishes AKIAIOSFODNN7EXAMPLE precisely so that it appears in documentation. It is not a key; allowlist the exact string, not the pattern.
  • A hash of a known value: A SHA-256 in a test fixture is a test fixture. A SHA-256 in the users table is a finding — the location is the finding, not the algorithm.
  • Placeholder values: change-me, your-key-here, and empty strings fail loudly by design. A placeholder that fails closed is a control, not a defect.
  • A public key that looks like a private one: Base64 blobs are indistinguishable by pattern. Check the PEM header before writing the ticket.

Key Management Checklist

Per secret class, the questions that decide whether the control is real:

  • ☐ Scanning covers history, not just HEAD
  • ☐ Scanning covers built artefacts and image layers
  • ☐ Every suppression has a reason and an owner
  • ☐ The scanner runs in CI and blocks the merge, not just the nightly report
  • ☐ User passwords use Argon2id, scrypt or bcrypt at the current parameters
  • ☐ Encryption keys live in a KMS or HSM and are never in the application config
  • ☐ Ciphertext names the key that produced it
  • ☐ No secret is readable from an environment dump, a debug page or a log line
  • ☐ Every key has an owner and a creation date
  • ☐ Rotation is possible without downtime, and has been performed at least once
  • ☐ Revocation has been tested, not assumed
  • ☐ The blast radius of a leaked key is documented

What Actually Happens After the Finding

The order of operations is the part that decides whether the finding recurs:

Rewriting history is not remediation

Removing a secret from a repository with git filter-repo changes what the repository contains. It does not change what the secret can do, it does not reach the clones other people made, it does not reach the forks, and it does not reach the artefact that was built from the old commit. Rotation is the remediation; rewriting is the cleanup. Doing the second before the first is the single most common way a leaked key stays live while the team believes it is handled — and the old key remains valid until someone revokes it, which nobody now has a reason to remember.

Why the same key keeps coming back

A secret that reappears after being removed is a process, not an accident. The usual ones: a scaffolding template that ships a placeholder key into every new service, a developer who keeps a local .env in a directory that is later committed, a configuration generator that writes defaults into the file it edits, and a CI job that echoes credentials into a log the scanner reads back. Each has the same fix shape — remove the default, and make the missing value fail at startup rather than fall back to something that works.

Key Management Practice

Exercises that separate the two findings — a live credential and a weak hash — and practise the response for each.

OWASP WrongSecrets Custom Lab easy
Find secrets in a container image and its environmentPractise rotation and understand why deletion is not revocationWrite the detection that would have caught each challenge
gitleaks against a real repository Custom Lab easy
Scan history, not just the working treeTriage a hit to a decision: live, dead, or documented exampleWrite a suppression with a reason and an owner
OWASP Juice Shop Custom Lab medium
Walk from a leaked credential to the account it opensCompare the password hash format with the current OWASP parametersWrite the migration that raises the cost without a reset