class SecureRandom {
Mathx.Random rng;
SecureRandom() {
rng = new Mathx.Random();
rng_pool_init();
}
// Pool size must be a multiple of 4 and greater than 32.
// An array of bytes the size of the pool will be passed to init()
var rng_psize = 256;
// 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
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
rng_seed_time() {
// Use pre-computed date to avoid making the benchmark
// results dependent on the current date.
rng_seed_int(1122926989487);
}
// TODO: this must get called at some point
rng_pool_init() {
// Initialize the pool with junk if needed.
if(rng_pool == null) {
rng_pool = new Map();
rng_pptr = 0;
var t;
while(rng_pptr < rng_psize) { // extract some randomness from Mathx.random()
//t = (65536 * Mathx.random()).floor();
t = (65536 * rng.nextDouble()).floor();
rng_pool[rng_pptr++] = t.toInt() >> 8;
rng_pool[rng_pptr++] = t.toInt() & 255;
}
rng_pptr = 0;
rng_seed_time();
//rng_seed_int(window.screenX);
//rng_seed_int(window.screenY);
}
}
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();
}
//rng_get_bytes(ba) {
nextBytes(ba) {
var i;
for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
}
}