Skip to content

Instantly share code, notes, and snippets.

@atoponce
Forked from PaulCapestany/oi.js
Last active January 8, 2024 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atoponce/84a8a0d9156d072196f4e17ee60f798a to your computer and use it in GitHub Desktop.
Save atoponce/84a8a0d9156d072196f4e17ee60f798a to your computer and use it in GitHub Desktop.
Dan Kaminsky's DefCon RNG challenge
#!/usr/bin/env node
/**
* Forked from https://gist.github.com/PaulCapestany/6148566. Changes:
* - Beautified code
* - NodeJS-specific (will not work in the browser)
* - Scope variables with let and const keywords
* - 256-bit RNG
* - Remove von Neumann debiasing
* - Remove byte assembly
* - Debiases output with SHA-256
*
* Theory:
* Coin flipping measures a slow system (how many seconds it takes a coin to
* rise and fall) against a fast system (how many spins a coin can complete
* before it lands).
*
* This can be done in code. The slow system is a millisecond timer of 1000
* cycles/second. The fast system is the CPU itself of billions of
* cycles/second. Because interrupts aren't cycle accurate, the bit flips are
* irregular and unpredictable.
*
* This RNG has precedence with Matt Blaze's Truerand and Dan Kaminsky's
* DakaRand. See:
* - https://github.com/ab300819/applied-cryptography/blob/master/Cryptix-1.16/Math-TrulyRandom/truerand.c
* - https://dankaminsky.com/2012/08/15/dakarand/
*
* Application:
* 256 "coin flips" are generated, hashed with SHA-256, encoded as
* hexadecimal, and printed to the screen.
*
* This code is slow, taking ~0.6 seconds on my Intel Core i7-8650 @ 1.90GHz.
*/
const { createHash } = require("crypto")
function millis() {
return Date.now()
}
function flip_coin() {
let n = 0
const then = millis() + 1
while(millis() <= then) n ^= 1
return n
}
function sha256_hash(str) {
return createHash("sha256").update(str).digest("hex")
}
function main() {
let n = 256
let flips = ""
while(n--) flips += flip_coin()
return sha256_hash(flips)
}
if (require.main === module) {
console.log(main())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment