Sub topic 10
Hashing and pseudonymizing identifiers and prompts
This chapter assumes you can write basic Python and have read the earlier chapters on redaction and metadata-first logging. Some fields are useless to redact because you need them to match records. A user ID, for example, lets you ask whether the same user hit the same error twice. Pseudonymization replaces the real value with a stable token, so you keep that matching ability without storing the original.
Hashing is not automatically anonymous
A hash is a one-way function. The same input always gives the same output, and you cannot run it backward. That does not make it safe for every value.
Anyone who can guess the input can hash their guesses and compare. Emails, phone numbers, and sequential user IDs have few possible values. An attacker with your logs can test a list of candidates against a plain SHA-256 digest quickly.
The fix is a keyed hash, called HMAC (hash-based message authentication code). It mixes a secret key into the hash. Without the key, guessing is no longer practical.
A pseudonymization helper
import hashlib
import hmac
def pseudonymize(value: str, key: bytes, prefix: str = "u") -> str:
normalized = value.strip().lower()
digest = hmac.new(key, normalized.encode("utf-8"), hashlib.sha256).hexdigest()
return f"{prefix}_{digest[:16]}"
key = b"demo-key-load-real-keys-from-a-secrets-manager"
print(pseudonymize("[email protected]", key))
print(pseudonymize(" [email protected] ", key))Both calls print the same token, because normalization removes case and whitespace differences. Without normalization, one person would get several tokens and your matching would silently break.
Three details matter:
- The key comes from a secrets manager or environment variable, never from source code. The key in the example is for demonstration only.
- Truncating to 16 hex characters (64 bits) keeps logs readable. It makes a collision unlikely at moderate volume, but not impossible at very large volume.
- The prefix (
u_,s_) tells readers what kind of identifier the token represents.
Hashing prompts
The metadata wrapper from earlier chapters logs prompt_sha256 instead of the prompt text. This hash is useful for three things:
- Spotting repeated prompts, such as retry loops.
- Checking whether two incidents involved identical input.
- Finding a cache hit rate.
A plain SHA-256 is acceptable here only when the prompts are long and varied. A short prompt such as "yes" or a templated prompt with one filled-in name can be guessed. If prompts may contain low-entropy secrets, use the HMAC helper instead.
A prompt hash also has limits. Changing one character produces a completely different hash, so it cannot find similar prompts, only identical ones.
Key management and rotation
The key is now sensitive data. Whoever holds it can confirm guesses about identifiers.
- Store it separately from the logs and limit who can read it.
- Rotating the key breaks matching across the rotation date, because the same user gets a new token. Plan rotation to coincide with your log retention window.
- Never reuse the pseudonymization key for signing or authentication.
Choosing a technique
| Value | Need to match records? | Approach |
|---|---|---|
| User email or ID | Yes | HMAC token |
| Long prompt text | Only identical prompts | SHA-256 or HMAC digest |
| Short or templated prompt | Yes | HMAC digest |
| Free-form personal text | No | Redact or do not log |
Exercise
A teammate logs sha256(user_email) as the user identifier. Why is this weak, and what two changes would you make?
Show answer
Emails come from a small, guessable set, so an attacker can hash candidate emails and compare them to the logged values. Replace the plain hash with HMAC-SHA256 using a secret key stored outside the logs, and normalize the email (strip whitespace, lowercase) before hashing so one person always maps to one token.