Audit evidence has two demands that pull in opposite directions. Auditors and supervisors want a record that nobody can quietly change. Data-protection law wants personal data to be erasable. This note shows a small pattern that satisfies both: a hash-chained append-only log and crypto-shredding. The code is a deliberately small sketch, not production code.
1. The problem with “we have an audit table”
An audit_log table protects nothing against someone with database access. UPDATE and DELETE work, and nothing tells you afterwards. “Append-only” enforced by application convention is a promise, not evidence.
2. Hash-chain the entries
Give every entry the hash of the previous one. Each entry’s hash covers the previous hash, its sequence number and a canonical form of its payload. Change any past entry and every later hash stops matching.
import hashlib, json, os
GENESIS = "0" * 64
def entry_hash(prev_hash: str, seq: int, payload: dict) -> str:
# Canonical JSON so the same payload always hashes the same way.
body = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return hashlib.sha256(f"{prev_hash}|{seq}|{body}".encode("utf-8")).hexdigest()
class Ledger:
def __init__(self):
self.entries = [] # append-only: no update, no delete
def append(self, payload: dict) -> dict:
prev = self.entries[-1]["hash"] if self.entries else GENESIS
seq = len(self.entries) + 1
e = {"seq": seq, "payload": payload, "prev": prev,
"hash": entry_hash(prev, seq, payload)}
self.entries.append(e)
return e
def verify(self):
"""Return None if the chain is intact, else the seq of the first broken entry."""
prev = GENESIS
for e in self.entries:
if e["prev"] != prev or e["hash"] != entry_hash(prev, e["seq"], e["payload"]):
return e["seq"]
prev = e["hash"]
return None
if __name__ == "__main__":
l = Ledger()
l.append({"event": "finding.created", "id": "F-1", "rating": "high"})
l.append({"event": "finding.approved", "id": "F-1", "by": "reviewer"})
l.append({"event": "action.deadline_extended", "id": "A-1", "reason": "vendor delay"})
print("intact:", l.verify())
l.entries[1]["payload"]["by"] = "someone-else" # tamper
print("first broken entry:", l.verify())
Running it prints:
intact: None
first broken entry: 2
The verifier does not just say “broken”. It names the first entry that fails, which is what an investigator needs. A system built on this idea can also react: for example, refuse writes and turn read-only until someone looks.
What a hash chain does not do
| Attack | Detected? |
|---|---|
| Edit an entry’s content | Yes, and the first broken entry is named |
| Delete or reorder an entry in the middle | Yes |
| Delete the tail of the chain | Only if the latest head hash is stored somewhere the attacker cannot reach (a second system, a signed checkpoint, a notary) |
| Rewrite the whole chain consistently | No. External anchoring of the head is the answer, not a bigger hash |
| Record a false event in the first place | No. The chain proves the record was not altered afterwards, not that it was true |
3. Do not put personal data in the chain in the clear
If the chain contains a client’s name, you have a record that must never change and must be erasable. That is a contradiction. Resolve it by never storing the personal fields themselves in the chain:
- Encrypt each person’s fields with a per-subject key.
- Put only the ciphertext in the log entry, so the hash covers the ciphertext.
- To erase the person, destroy that subject’s key. The ciphertext remains, the chain still verifies, and the data is permanently unreadable. No entry is rewritten.
# Crypto-shredding sketch: personal data sealed under a per-subject key; the chain stores only ciphertext.
# Requires: pip install cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
keys = {} # subject_id -> key (in real life: wrapped under a master key, in a KMS/HSM)
def seal(subject, plaintext: bytes) -> bytes:
key = keys.setdefault(subject, AESGCM.generate_key(bit_length=256))
nonce = os.urandom(12)
return nonce + AESGCM(key).encrypt(nonce, plaintext, subject.encode())
def open_(subject, blob: bytes):
key = keys.get(subject)
if key is None:
return None # erased: ciphertext stays in the chain, unreadable
return AESGCM(key).decrypt(blob[:12], blob[12:], subject.encode())
blob = seal("client-42", "Jane Doe".encode())
print(open_("client-42", blob))
del keys["client-42"] # erasure = destroy the key; no ledger entry is rewritten
print(open_("client-42", blob))
Running it prints b'Jane Doe' and then None.
Caveats worth stating plainly
- Keys must be stored outside the chain, ideally wrapped under a master key in a KMS or HSM. Lose the master key and you have erased everyone; leak it and you have lost the guarantee.
- Anything derived from the personal data in the clear (search indexes, logs, backups) is outside this protection. Plan those separately.
- Whether crypto-shredding satisfies erasure for your regulator and your retention rules is a question for your legal and compliance advisers, not for this note.
4. Where this fits
We use this family of ideas in the evidence trail of AbenAudit, our internal-audit software for banks: transitions, approvals and refused access are recorded in a hash-chained ledger, and the system turns read-only if the chain is found broken. There is a demo on synthetic data. The pattern itself does not need our software.
A slightly fuller, tested version of the sketch above (13 tests, optional head anchoring, a command-line verifier) is open source under Apache-2.0: ledger-verify on GitHub and on PyPI (pip install ledger-verify). It is a reference implementation, not a production library. If you think its threat model is wrong, please open an issue.
Published December 2026. Drafted with AI assistance, then reviewed and edited by the author. Code samples are illustrative and are not AbenAudit source code.