Diffie-Hellman

Big Numbers

The key exchange behind HTTPS, running on a Super Nintendo. Two parties each pick a secret, publish g^secret mod p, and — by raising the other's public value to their own secret — arrive at the same shared number without ever sending it. Here that number is a colour: the two public bands shift, but the shared band is always the colour both sides agree on. The maths is 64-bit modular exponentiation — which, fittingly, crashed the compiler until this demo found and fixed the bug. Runs on its own; no joypad needed. Written in C and compiled with the llvm-mos-based 65816 toolchain (+mos-a16, 16-bit accumulator mode).

loading core…

Self-running demo — the public colours shift; the shared secret is always agreed.

Click the screen to focus, then watch. Tab away and it pauses.

What it is

Diffie-Hellman lets two people who have never met agree on a secret over an open channel. It rests on modular exponentiation being easy to compute but hard to reverse:

A = g^a mod p;          // Alice publishes A
B = g^b mod p;          // Bob   publishes B
shared = B^a mod p;     // Alice computes the secret...
shared = A^b mod p;     // ...Bob gets the SAME number: g^(ab) mod p

Because (g^a)^b = (g^b)^a, both sides land on g^(ab) mod p — the shared secret — while an eavesdropper who sees only A and B cannot. The numbers here are 64-bit, and computing them stays bit-exact across every codegen mode (once the backend knew how to split a 64-bit value into 16-bit pieces — which it didn't, until this demo).

Compiler stress-test

ItemWhat it exercises
64-bit moduloModular exponentiation squares and multiplies a 64-bit number, taking the remainder mod p at every step. That 64-bit remainder (__umoddi3), after a 64-bit multiply, is the hot operation — a path no earlier demo runs.
found a compiler bugThe 64-bit math crashed the 16-bit-accumulator backend outright ("unable to legalize G_UNMERGE_VALUES (s64)") — a missing rule for splitting a 64-bit value into 16-bit pieces. This demo isolated it and it was fixed (patch 0017); the demo is now the regression guard.
no overflowThe modulus is kept just under 2^32 so the product of two residues stays under 2^64 — exactly representable — before the remainder is taken. All 64-bit, identical on host and console.
both sides agreeThe point of Diffie-Hellman is that Alice's B^a and Bob's A^b are the same number without ever sharing it. The self-check folds both and their XOR, which must be zero — the agreement, verified in hardware.

Written in C with the llvm-mos 65816 toolchain and verified against bsnes-jg (and MAME where the SPC700 IPL is present). Hit Verify fidelity to reproduce the build gate's WRAM assert (gate CRC 0x69AA — a fold of the exchanges plus the shared-secret agreement check) live in this tab. No far pointers — the same source passes every way: host == default == +mos-a16 == +mos-xy16 == bsnes-jg, -verify clean.