A Recomputed Checksum Can Pass an Altered Message

Download and extract the reader ZIP archive (a compressed collection of files). Links labelled โ€œreader ZIP; extract โ€ฆโ€ download this archive; after extraction, open the named file. It includes the offline article, full-size Portable Network Graphics (PNG) images, editable Scalable Vector Graphics (SVG) diagrams, complete source code, tests and worksheets.

A receiver reports โ€œchecksum OKโ€ after a message changes. This is possible without a rare collision: someone able to replace the message can also calculate its new public checksum. Here you will change one constructed reading, recompute its CRC, and compare that result with a retained keyed authentication tag.

CRC means cyclic redundancy check, a checksum suited to detecting specified patterns of accidental damage. HMAC is a hash-based message authentication code. With SHA-256, the Secure Hash Algorithm with a 256-bit result, it produces a keyed tag over the message bytes. Message authentication concerns agreement with a key, while encryption concerns hiding content. They are different properties.

Outcome: demonstrate why public integrity checks do not establish authenticity, then isolate replay from tag verification. Every message is a local constructed example. The hard-coded key is public teaching material, not a secret or a real credential. No network traffic, device command or production service is involved.

Materials and assumptions

Use the reader directory, a text editor and a Python interpreter with its standard-library hmac, hashlib, zlib and unittest modules. Actual host execution used CPython 3.9.6 (CPython is the reference implementation of Python). That interpreter is now unsupported according to its documentation; recording what ran is not a deployment recommendation. Run your own exercise in a supported environment and keep this public example key out of real applications.

Our thought experiment gives a sender and receiver the same key, but withholds that key from one narrowly defined rewrite function. In the distributed demonstration, everybody can read the constant; anyone who uses it can generate a valid new tag. The function boundary isolates the computation for teaching, not a real security boundary.

ASCII means American Standard Code for Information Interchange, a byte character encoding. A record has exactly three fields: device is one to sixteen uppercase ASCII letters, digits, underscores or hyphens; reading is an integer from 0 to 9999; sequence is an integer from 0 to 232โˆ’1. Boolean values are not integers for this schema. JSON means JavaScript Object Notation. The program serializes these fields in sorted-key order, with no optional spaces, as ASCII bytes. This canonical encoding is a lesson convention, not a universal canonical-JSON standard.

Follow the bytes, not the appearance

payload bytes โ†’ public CRC-32
payload bytes + shared key โ†’ full HMAC-SHA256 tag

keyless rewrite:
    parse and validate original payload
    replace reading 1234 with 9876
    serialize the same canonical field format
    calculate new CRC-32
    retain the old HMAC tag

The keyless function has no key parameter and never calls the HMAC generator. The receiver independently checks the new bytes against the two received values. The Python CRC documentation explicitly excludes CRC-32 as an authentication mechanism. RFC means Request for Comments, the document series used for the cited technical specification. The keyed construction follows RFC 2104; the code uses the existing library rather than inventing a cryptographic primitive.

Sender, keyless message rewrite and receiver distinguish a public CRC from a retained HMAC tag.
Original constructed transfer/geometry figure. Pan the diagram on a narrow screen, or open the full vector figure โ€” reader ZIP; extract assets/crc-hmac-boundary.svg.

Run the control, chosen fault and keyless rewrite

  1. Predict the outcomes in data/blank-observations.csv. Keep the CRC and HMAC predictions in different columns.
  2. Run python3 -m unittest discover -s code -v, then python3 code/auth_lab.py --output my-run. Inspect packets.json, outcomes.json and outcomes.csv. No sender or receiver socket exists in this program.
  3. Start with the unchanged control record: device PAPER_A, reading 1234, sequence 7. Both checks pass.
  4. Inspect the chosen-fault case. Its reading becomes 1235 while the original CRC and tag remain. Both checks fail for these specific bytes. This single result does not prove a CRC catches every possible alteration.
  5. Inspect the keyless rewrite to 9876. Its newly calculated CRC passes, while the retained HMAC fails. Compare actual payload strings and checksum values; do not infer the result from labels alone.
  6. Inspect the key-holder rewrite. The same changed reading with a new tag generated using the example key passes. A shared-key tag cannot distinguish which holder of that shared key created the message.
  7. Restore the unchanged control and rerun. Its two checks pass again. Change one tag character, truncate it, add an unexpected field or duplicate a JSON key: the verifier must reject malformed input rather than repair it silently.

Calculated verification outcomes

Constructed case CRC-32 check HMAC check
Unchanged control Pass Pass
Chosen change, old CRC and tag Fail Fail
Change and recomputed public CRC, old tag Pass Fail
Key holder supplies a new tag Pass Pass

The following numeric graph shows which actual bytes changed. XOR means exclusive OR: each plotted byte is the control byte XOR the corresponding case byte, so zero means unchanged. Payload offsets are ASCII byte offsets; CRC and HMAC offsets are decoded bytes in the left-to-right order of their hexadecimal strings. The keyless-rewrite row intentionally shows the unchanged received HMAC bytes. Verification compares that retained tag with a freshly computed expected tag for the changed payload, so unchanged received tag bytes do not mean that the HMAC check passes. These byte changes do not themselves prove cryptographic security, collision resistance or an avalanche property.

Calculated per-byte XOR difference graph compares payload, four CRC bytes and thirty-two HMAC bytes with the control packet for four constructed cases.
Original calculated comparison; no measured data. Pan the diagram on a narrow screen, or open the full vector figure โ€” reader ZIP; extract assets/byte-difference-graph.svg.

Replay is another question

A replay is an old authentic message presented again. The control packet’s tag passes verification on both presentations because its bytes and key are unchanged. A separate in-memory sequence window accepts only a strictly greater sequence for each device, after authentication succeeds. A failed tag with a high sequence cannot advance that window. Wraparound is refused rather than guessed.

The second presentation is rejected while this state is retained. Starting a new empty window accepts the old packet again. Consequently, this tiny checker does not establish freshness after a process restart, across multiple receivers, after state loss or against a key holder. It has no durable storage, time policy, key rotation, device provisioning, encrypted transport or reliable-delivery design. The sequence is authenticated because it is inside the payload, but the receiver still needs an appropriate state and lifecycle policy.

Checks and their practical limits

Actual host execution passed 16 tests. These include six full SHA-256 known-answer cases from RFC 4231 and its truncated-prefix reference, the CRC-32 value for the conventional numeric test string, malformed schemas and JSON, wrong-key failure, the keyless rewrite, and replay-state poisoning and reset controls. Our packet format deliberately requires the full 32-byte tag, encoded as 64 lowercase hexadecimal characters; the RFC’s truncated example is a primitive reference, not our packet policy.

The verifier uses hmac.compare_digest with same-type, fixed-size strings, following Python’s comparison guidance. This avoids a content-based short-circuit equality check; it does not make the whole parser, operating system or application timing independent. Size limits and duplicate-key refusal make this local exercise less ambiguous, but are not a security audit.

Source status was checked on November 30, 2026. The National Institute of Standards and Technology (NIST) Federal Information Processing Standard (FIPS) 198-1 record still describes a proposed withdrawal in its planning note. The linked Special Publication (SP) 800-224 record is explicitly an Initial Public Draft. This lesson does not relabel that draft as a final standard or claim conformance certification.

Challenge and worked answer

If the unchanged packet passes its tag check a thousand times, has it proved that the reading is recent, secret or true? What changes if a second device shares the same key?

Worked answer

The tag only checks the bytes against the key under the algorithm’s assumptions. Repetition provides no time evidence. The payload is visible, and a dishonest or compromised key holder can authenticate a fabricated reading. Another holder of the same key can produce tags too. The local window adds a narrow ordering rule while its state survives; it does not independently validate a sensor or identify one individual sender.

For accidental channel damage and missing messages, compare the framed Pico link lesson. For a distinct freshness problem, see GPS checksums, fix state and observation age. This experiment adds the intentional rewrite and shared-key boundary; it does not turn those earlier integrity checks into authentication.

Primary sources and source conditions

  • RFC 2104: HMAC: Keyed message authentication construction; shared-key assumptions and scope.
  • RFC 4231: HMAC test vectors: SHA-256 cases1โ€“4,6โ€“7 full tags and case5 truncated reference are exercised as known-answer data.
  • Python hmac documentation: HMAC interface and same-type compare_digest guidance; no production security conclusion from this lesson.
  • Python zlib documentation: CRC-32 checksum API and explicit exclusion of authentication use.
  • NIST FIPS 198-1 record: Viewed2026-11-30: planning note describes proposed withdrawal, not a completed withdrawal.
  • NIST SP 800-224 record: Viewed2026-11-30: record labels this Initial Public Draft; no final-standard claim.

Sources were checked on November 30, 2026. Figures, calculations, lesson text and experiment code are original work for this lesson. Linked third-party material is not bundled in the reader.

Complete reproducible code and checks

Both complete files below are also supplied as editable reader files. Commands create new local output directories. PNG means Portable Network Graphics; SVG means Scalable Vector Graphics. These original figure formats preserve the constructed diagrams; the explanatory text remains Hypertext Markup Language (HTML).

auth_lab.py โ€” complete file
"""Local constructed CRC/HMAC comparison. PUBLIC demo key is not a credential."""
import argparse,csv,hashlib,hmac,json,re,zlib
from pathlib import Path
PUBLIC_KEY=b'PUBLIC-EXAMPLE-KEY-NOT-A-SECRET'
MAX_JSON=16384

def unique(pairs):
 result={}
 for k,v in pairs:
  if k in result:raise ValueError('duplicate JSON key')
  result[k]=v
 return result

def load_json(raw):
 if not isinstance(raw,str) or len(raw)>MAX_JSON:raise ValueError('JSON text too large or wrong type')
 try:r=json.loads(raw,object_pairs_hook=unique,parse_constant=lambda x:(_ for _ in ()).throw(ValueError('nonfinite JSON')))
 except (ValueError,RecursionError) as exc:raise ValueError('invalid JSON') from exc
 if not isinstance(r,dict):raise ValueError('expected a JSON object')
 return r

def record(value):
 if not isinstance(value,dict) or set(value)!={'device','reading','sequence'}:raise ValueError('record fields must be device, reading, sequence')
 if not isinstance(value['device'],str) or re.fullmatch(r'[A-Z0-9_-]{1,16}',value['device']) is None:raise ValueError('bad device label')
 for name,limit in [('reading',9999),('sequence',2**32-1)]:
  if type(value[name]) is not int or not 0<=value[name]<=limit:raise ValueError('bad '+name)
 return dict(value)

def payload_bytes(value):return json.dumps(record(value),sort_keys=True,separators=(',',':'),ensure_ascii=True).encode('ascii')

def crc(data):
 if not isinstance(data,bytes):raise ValueError('CRC input must be bytes')
 return format(zlib.crc32(data)&0xffffffff,'08x')

def mac(key,data):
 if not isinstance(key,bytes) or not key or not isinstance(data,bytes):raise ValueError('MAC requires nonempty byte key and byte message')
 return hmac.new(key,data,hashlib.sha256).hexdigest()

def make_packet(value,key):
 data=payload_bytes(value)
 return {'payload':data.decode('ascii'),'crc32':crc(data),'hmac_sha256':mac(key,data)}

def inspect_packet(packet):
 if not isinstance(packet,dict) or set(packet)!={'payload','crc32','hmac_sha256'}:raise ValueError('bad packet fields')
 for name,length in [('crc32',8),('hmac_sha256',64)]:
  if not isinstance(packet[name],str) or re.fullmatch('[0-9a-f]{'+str(length)+'}',packet[name]) is None:raise ValueError('bad '+name+' format')
 r=record(load_json(packet['payload']));data=payload_bytes(r)
 if data.decode('ascii')!=packet['payload']:raise ValueError('payload is not in the lesson canonical encoding')
 return r,data

def verify_packet(packet,key):
 r,data=inspect_packet(packet)
 return {'record':r,'crc_ok':hmac.compare_digest(crc(data),packet['crc32']),'hmac_ok':hmac.compare_digest(mac(key,data),packet['hmac_sha256'])}

def rewrite_without_key(packet,new_reading):
 """Intentionally has no key argument. Retain old MAC; replace public CRC."""
 r,unused=inspect_packet(packet);r['reading']=new_reading;data=payload_bytes(r)
 return {'payload':data.decode('ascii'),'crc32':crc(data),'hmac_sha256':packet['hmac_sha256']}

class SequenceWindow:
 """In-memory strict high-water mark, not a production replay protocol."""
 def __init__(self):self.highest={}
 def accept(self,value):
  r=record(value);old=self.highest.get(r['device'],-1)
  if r['sequence']<=old:return False
  self.highest[r['device']]=r['sequence'];return True

def accept_authenticated(packet,key,window):
 v=verify_packet(packet,key)
 return v['crc_ok'] and v['hmac_ok'] and window.accept(v['record'])

def demo(output):
 control=make_packet({'device':'PAPER_A','reading':1234,'sequence':7},PUBLIC_KEY)
 stale=dict(control);stale['payload']=stale['payload'].replace('1234','1235')
 rewritten=rewrite_without_key(control,9876)
 holder=make_packet({'device':'PAPER_A','reading':9876,'sequence':7},PUBLIC_KEY)
 packets={'control':control,'chosen_fault_old_crc':stale,'rewritten':rewritten,'key_holder_rewrite':holder}
 cases={name:verify_packet(p,PUBLIC_KEY) for name,p in packets.items()}
 window=SequenceWindow();first=accept_authenticated(control,PUBLIC_KEY,window);second=accept_authenticated(control,PUBLIC_KEY,window)
 result={'kind':'constructed local demonstration','physical_measurement':False,'network_sent':False,'public_key':True,'public_key_hex':PUBLIC_KEY.hex(),'cases':cases,'replay_first_accepted':first,'replay_second_accepted':second,'new_state_accepts_old_packet':accept_authenticated(control,PUBLIC_KEY,SequenceWindow()),'production_security_proven':False}
 dest=Path(output);dest.mkdir(parents=True,exist_ok=True)
 (dest/'packets.json').write_text(json.dumps(packets,indent=2)+'\n');(dest/'outcomes.json').write_text(json.dumps(result,indent=2)+'\n')
 with (dest/'outcomes.csv').open('w',newline='') as f:
  w=csv.writer(f);w.writerow(['constructed_case','crc_ok','hmac_ok']);w.writerows((k,v['crc_ok'],v['hmac_ok']) for k,v in cases.items())
 return result

def main():
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output');p.add_argument('--verify-file',help='local packet JSON; verification uses PUBLIC demo key')
 args=p.parse_args()
 if bool(args.output)==bool(args.verify_file):p.error('choose exactly one mode')
 try:
  if args.output:result=demo(args.output)
  else:
   path=Path(args.verify_file)
   if path.stat().st_size>MAX_JSON:p.error('file too large')
   result=verify_packet(load_json(path.read_text(encoding='utf-8')),PUBLIC_KEY)
 except (ValueError,OSError,UnicodeError) as exc:p.error(str(exc))
 print(json.dumps(result,sort_keys=True))
if __name__=='__main__':main()
test_auth_lab.py โ€” complete file
import json,subprocess,sys,tempfile,unittest
from pathlib import Path
import auth_lab as a
class AuthTests(unittest.TestCase):
 def setUp(self):self.key=b'PUBLIC-EXAMPLE-KEY-NOT-A-SECRET';self.r={'device':'PAPER_A','reading':1234,'sequence':7}
 def test_control(self):self.assertIsInstance(a.make_packet(self.r,self.key),dict)
 def test_crc_known_answer(self):self.assertEqual(a.crc(b'123456789'),'cbf43926')
 def test_rfc4231(self):
  vectors=[('0b'*20,'4869205468657265','b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7'),('4a656665','7768617420646f2079612077616e7420666f72206e6f7468696e673f','5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843'),('aa'*20,'dd'*50,'773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe'),(bytes(range(1,26)).hex(),'cd'*50,'82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b'),('aa'*131,'54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a65204b6579202d2048617368204b6579204669727374','60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54'),('aa'*131,'5468697320697320612074657374207573696e672061206c6172676572207468616e20626c6f636b2d73697a65206b657920616e642061206c6172676572207468616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565647320746f20626520686173686564206265666f7265206265696e6720757365642062792074686520484d414320616c676f726974686d2e','9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2')]
  for k,d,w in vectors:self.assertEqual(a.mac(bytes.fromhex(k),bytes.fromhex(d)),w)
 def test_truncation_reference_not_packet_policy(self):
  self.assertEqual(a.mac(b'\x0c'*20,bytes.fromhex('546573742057697468205472756e636174696f6e'))[:32],'a3b6167473100ee06e0c796c2955552b')
  p=a.make_packet(self.r,self.key);p['hmac_sha256']=p['hmac_sha256'][:32]
  with self.assertRaises(ValueError):a.verify_packet(p,self.key)
 def test_keyless_rewrite(self):
  p=a.make_packet(self.r,self.key);q=a.rewrite_without_key(p,9876);v=a.verify_packet(q,self.key)
  self.assertEqual(q['hmac_sha256'],p['hmac_sha256']);self.assertNotEqual(q['crc32'],p['crc32']);self.assertTrue(v['crc_ok']);self.assertFalse(v['hmac_ok'])
 def test_chosen_fault(self):
  p=a.make_packet(self.r,self.key);p['payload']=p['payload'].replace('1234','1235');v=a.verify_packet(p,self.key);self.assertFalse(v['crc_ok']);self.assertFalse(v['hmac_ok'])
 def test_key_holder_and_wrong_key(self):
  p=a.make_packet(dict(self.r,reading=9876),self.key);self.assertTrue(a.verify_packet(p,self.key)['hmac_ok']);v=a.verify_packet(p,b'WRONG');self.assertTrue(v['crc_ok']);self.assertFalse(v['hmac_ok'])
 def test_replay_separate(self):
  p=a.make_packet(self.r,self.key)
  for i in range(2):self.assertTrue(a.verify_packet(p,self.key)['hmac_ok'])
  w=a.SequenceWindow();self.assertTrue(a.accept_authenticated(p,self.key,w));self.assertFalse(a.accept_authenticated(p,self.key,w));self.assertTrue(a.accept_authenticated(p,self.key,a.SequenceWindow()))
 def test_unauthenticated_sequence_cannot_poison_window(self):
  w=a.SequenceWindow();bad=a.make_packet(dict(self.r,sequence=999),b'WRONG');self.assertFalse(a.accept_authenticated(bad,self.key,w));self.assertTrue(a.accept_authenticated(a.make_packet(self.r,self.key),self.key,w))
 def test_devices_and_no_wrap(self):
  w=a.SequenceWindow();self.assertTrue(w.accept(self.r));self.assertFalse(w.accept(dict(self.r,sequence=6)));self.assertTrue(w.accept(dict(self.r,device='PAPER_B',sequence=0)));self.assertTrue(w.accept(dict(self.r,sequence=2**32-1)));self.assertFalse(w.accept(dict(self.r,sequence=0)))
 def test_canonical_bytes(self):self.assertEqual(a.payload_bytes(self.r),b'{"device":"PAPER_A","reading":1234,"sequence":7}')
 def test_bad_records(self):
  for r in [{},dict(self.r,extra=1),dict(self.r,device='a b'),dict(self.r,device=''),dict(self.r,device='รฉ'),dict(self.r,reading=True),dict(self.r,reading=-1),dict(self.r,reading=10000),dict(self.r,sequence=True),dict(self.r,sequence=2**32),dict(self.r,reading=1.0)]:
   with self.assertRaises(ValueError):a.make_packet(r,self.key)
 def test_bad_key_types(self):
  for k in ['',b'',None,True]:
   with self.assertRaises(ValueError):a.mac(k,b'data')
  with self.assertRaises(ValueError):a.mac(self.key,'data')
 def test_packet_shape(self):
  base=a.make_packet(self.r,self.key)
  for f,v in [('crc32','FFFFFFFF'),('crc32','1'),('hmac_sha256','z'*64),('payload',{}),('payload','{}'),('payload',base['payload']+' ')]:
   p=dict(base);p[f]=v
   with self.assertRaises(ValueError):a.verify_packet(p,self.key)
  with self.assertRaises(ValueError):a.verify_packet(dict(base,extra=1),self.key)
 def test_json_refusal(self):
  for raw in ['{"x":1,"x":2}','{','NaN','[]','x'*20000]:
   with self.assertRaises(ValueError):a.load_json(raw)
 def test_cli(self):
  with tempfile.TemporaryDirectory() as td:
   r=subprocess.run([sys.executable,a.__file__,'--output',td],capture_output=True,text=True);self.assertEqual(r.returncode,0,r.stderr);o=json.loads((Path(td)/'outcomes.json').read_text());self.assertFalse(o['physical_measurement']);self.assertFalse(o['network_sent']);self.assertTrue(o['public_key']);self.assertTrue(o['cases']['rewritten']['crc_ok']);self.assertFalse(o['cases']['rewritten']['hmac_ok']);self.assertFalse(o['replay_second_accepted'])
if __name__=='__main__':unittest.main()

Open the offline reader and reproduction instructions โ€” reader ZIP; extract README.txt. The delivered reader ZIP contains this article, preview, original figures, code, tests and blank and constructed data. The blank worksheet is intentionally empty; generated outputs are explicitly constructed.

๐Ÿ“กBroadcast the signal โ€” amplify the connection.

Leave a Reply