diff options
| author | Guillaume Horel <guillaume.horel@gmail.com> | 2011-05-19 02:31:04 -0400 |
|---|---|---|
| committer | Guillaume Horel <guillaume.horel@gmail.com> | 2011-05-19 02:31:04 -0400 |
| commit | af055136c23652f1cf1ef0beac1b94d79cc1ddb6 (patch) | |
| tree | c4de7f3bfe91303423e19552f850d432b03133c6 /crypto/rng.js | |
| parent | 53fb8167efe4100bf20df3bec5d6b844f4bf1617 (diff) | |
| download | alias-af055136c23652f1cf1ef0beac1b94d79cc1ddb6.tar.gz | |
Started to play around with js crypto code
test.js implements the basic functionality
(recommand to load it in v8 (d8 test.js --shell)
Diffstat (limited to 'crypto/rng.js')
| -rw-r--r-- | crypto/rng.js | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/crypto/rng.js b/crypto/rng.js new file mode 100644 index 0000000..0063b5a --- /dev/null +++ b/crypto/rng.js @@ -0,0 +1,68 @@ +// Random number generator - requires a PRNG backend, e.g. prng4.js + +// For best results, put code like +// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'> +// in your main HTML document. + +var rng_state; +var rng_pool; +var rng_pptr; + +// Mix in a 32-bit integer into the pool +function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= (x >> 8) & 255; + rng_pool[rng_pptr++] ^= (x >> 16) & 255; + rng_pool[rng_pptr++] ^= (x >> 24) & 255; + if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; +} + +// Mix in the current time (w/milliseconds) into the pool +function rng_seed_time() { + rng_seed_int(new Date().getTime()); +} + +// Initialize the pool with junk if needed. +if(rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + //if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) { + // Extract entropy (256 bits) from NS4 RNG if available + // var z = window.crypto.random(32); + // for(t = 0; t < z.length; ++t) + // rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; + //} + while(rng_pptr < rng_psize) { // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; + } + rng_pptr = 0; + rng_seed_time(); + //rng_seed_int(window.screenX); + //rng_seed_int(window.screenY); +} + +function rng_get_byte() { + if(rng_state == null) { + rng_seed_time(); + rng_state = prng_newstate(); + rng_state.init(rng_pool); + for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) + rng_pool[rng_pptr] = 0; + rng_pptr = 0; + //rng_pool = null; + } + // TODO: allow reseeding after first request + return rng_state.next(); +} + +function rng_get_bytes(ba) { + var i; + for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); +} + +function SecureRandom() {} + +SecureRandom.prototype.nextBytes = rng_get_bytes; |
