Sub topic 10
Hashing and pseudonymizing identifiers and prompts
Redaction removes sensitive text. Sometimes you still need to know that two log records involve the same user, or the same prompt, without storing the value itself. Hashing and pseudonymization cover that case. This chapter assumes you can write Python, have called an LLM API, know structured logging from the earlier chapters, and understand the metadata-first policy and redaction.
What you are trying to keep
A log record can be useful for three reasons:
- It shows that something happened (status, latency, token counts).
- It shows who or what was involved, for example which user hit an error.
- It shows how often something repeats, for example the same prompt sent 400 times in an hour.
Metadata covers the first reason. Raw identifiers and raw prompts would cover the second and third, but they put personal data and proprietary text in your logs. A pseudonym is a stable stand-in value. The same input always gives the same stand-in, so you can group and count records, but a reader of the log cannot read the original from it.
Hashing is not anonymization
A hash function such as SHA-256 turns any input into a fixed-size digest. It is one-way in principle: you cannot run it backwards. Beginners often conclude that a hashed email is safe to log. That is wrong whenever the set of possible inputs is small or guessable.
An attacker who sees a digest does not reverse it. They hash every plausible input and compare. User IDs, phone numbers, emails, and short prompts like "yes" or "reset my password" all come from small or predictable sets.
import hashlib
def sha(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
logged = sha("482915") # a 6-digit employee ID that ended up in a log
for n in range(1_000_000):
candidate = f"{n:06d}"
if sha(candidate) == logged:
print("recovered", candidate)
breakThis prints recovered 482915 in about a second on ordinary hardware. A million guesses is nothing for SHA-256, which is built to be fast.
Two terms matter here:
- Pseudonymization replaces an identifier with a different value and keeps a way to re-link it, for example by recomputing the pseudonym from a known ID. Under privacy laws such as the GDPR, pseudonymized data usually still counts as personal data.
- Anonymization removes the link so that no one can reasonably re-identify the person. Hashing alone almost never achieves this.
Treat a hashed or pseudonymized log field as lower-risk personal data, not as non-personal data. Access control and retention from later chapters still apply.
Use a keyed hash for identifiers
The fix for guessable inputs is a secret key. HMAC (hash-based message authentication code) mixes a secret key into the hash. Without the key, the attacker cannot test guesses, because they cannot compute the expected digest.
import hashlib
import hmac
import secrets
def pseudonymize(value: str, key: bytes, purpose: str, length: int = 16) -> str:
message = f"{purpose}:{value}".encode("utf-8")
digest = hmac.new(key, message, hashlib.sha256).hexdigest()
return digest[:length]
key = secrets.token_bytes(32) # in production, load from a secrets manager
a = pseudonymize("482915", key, purpose="user_id")
b = pseudonymize("482915", key, purpose="user_id")
c = pseudonymize("482915", key, purpose="tenant_id")
other_key = secrets.token_bytes(32)
d = pseudonymize("482915", other_key, purpose="user_id")
print(a == b) # True: same key, same purpose, same input
print(a == c) # False: different purpose
print(a == d) # False: different keyThe design choices in this function:
- Key management. Keep the key in a secrets manager or an environment variable populated by one. Never put it in source control, and never log it. If the key leaks, every pseudonym becomes guessable again, like the plain hash above.
- The purpose label. Prefixing the value with a label such as
user_idis called domain separation. The same raw value then produces different pseudonyms in different fields, so someone cannot joinuser_idandtenant_idcolumns just because the raw values collide. - Truncation. Sixteen hex characters keep 64 bits of the digest. For correlation in logs that is plenty. Random collisions become likely only after billions of distinct values. Shorter digests save space but raise collision risk, so do not go below about 12 characters for busy systems.
- A per-record random salt is the wrong tool here. A fresh random salt on every record gives a different digest each time, which destroys the correlation you wanted. A single secret key (sometimes called a pepper) keeps digests stable while still blocking guessing.
Fingerprinting prompts
The call wrapper from earlier in this tutorial logs prompt_sha256. That field lets you spot repeated prompts, detect a prompt template change, or match a failing call to a cached one, all without storing text.
Two details improve it. First, normalize the text before hashing so trivial differences do not create different fingerprints. Second, use a keyed hash, because prompts are often a fixed template with one small variable slot, and that makes them guessable in the same way as the employee ID above.
import hashlib
import hmac
import unicodedata
def prompt_fingerprint(prompt: str, key: bytes) -> str:
normalized = " ".join(unicodedata.normalize("NFC", prompt).split())
digest = hmac.new(key, normalized.encode("utf-8"), hashlib.sha256)
return digest.hexdigest()[:32]
key = b"demo-key-do-not-use-in-production"
p1 = prompt_fingerprint("Summarize this:\nHello", key)
p2 = prompt_fingerprint("Summarize this: Hello", key)
print(p1 == p2) # True: whitespace differences are ignoredHash the raw prompt, not the redacted one. If you hash after redaction, two prompts that differ only in an email address collapse into one fingerprint, and you lose the distinction you may want. The hash stays safe because the key protects it, and the raw text is never stored.
A fingerprint still leaks one fact: whether two prompts are identical. That is usually acceptable. It is not acceptable when equality itself is sensitive, for example when you log each user's medical questions under a user pseudonym, since a repeated fingerprint across users reveals shared content. In that case, include the user pseudonym in the hashed message or skip the fingerprint.
Rotation and erasure
Add a key identifier to each record so you know which key produced a pseudonym:
record = {
"event": "llm_call",
"user": pseudonymize("482915", key, purpose="user_id"),
"pseudonym_key_id": "2026-11",
}Rotating the key on a schedule, for example monthly, limits how long anyone can track a user across your logs. The cost is that correlation across a rotation boundary breaks, so choose the period to match how far back your debugging and analytics reach.
Keyed pseudonyms also help with deletion requests. You know the user's real ID, so you can recompute their pseudonym for each active key and search the logs for it. If you must wipe a whole period, destroying that period's key makes its pseudonyms unlinkable to anyone who later learns a user ID.
Choosing a technique
| Technique | Stable across records | Resists guessing | Typical use |
|---|---|---|---|
| Plain SHA-256 | Yes | No, for small input sets | Long, high-entropy values only |
| Salted hash, random salt per record | No | Yes | Rarely useful in logs |
| Keyed HMAC | Yes | Yes, while the key stays secret | User IDs, tenant IDs, prompt fingerprints |
| Redaction placeholder | No | Not applicable | Text you never need to correlate |
Common mistakes
- Hashing secrets. A hashed API key is still derived from the key. Log a key ID or the last four characters instead.
- Hashing low-entropy values with plain SHA-256. Emails, phone numbers, short IDs, and templated prompts fall to the guessing attack shown above.
- Logging the key. Include the key in a config dump or an exception message and every pseudonym is exposed. Treat it like any credential from the "Keeping credentials out of logs" chapter.
- Skipping normalization. Case, whitespace, and Unicode differences split one logical prompt into many fingerprints.
- Slow hashes for no reason. Password hashing functions like bcrypt or Argon2 slow guessing down, but they are too slow for every log line. A keyed HMAC gives the guessing protection you need here.
Exercise
A teammate logs sha256(user_email) as the user field so that logs contain no raw emails. An attacker obtains the logs and a list of 50,000 customer emails from an old breach. What can the attacker do, and what change would stop it?
Show answer
The attacker hashes each email in the breach list and matches the digests against the log field, which identifies which users made which calls. Plain SHA-256 offers no protection when the input set is small or known. Replace it with a keyed HMAC (for example pseudonymize(email, key, purpose="user_email")), keep the key in a secrets manager and out of the logs, and record a key ID so you can rotate it.
Exercise
Why should you hash the raw prompt, with the key, rather than the redacted prompt when you want to detect repeated prompts?
Show answer
Redaction replaces differing details such as emails with the same placeholder, so different prompts can produce the same redacted text and therefore the same fingerprint. Hashing the raw prompt keeps them distinct. Using a keyed hash and never storing the raw text means the fingerprint does not expose the content.