random.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /** @fileOverview Random number generator.
  2. *
  3. * @author Emily Stark
  4. * @author Mike Hamburg
  5. * @author Dan Boneh
  6. */
  7. /** @namespace Random number generator
  8. *
  9. * @description
  10. * <p>
  11. * This random number generator is a derivative of Ferguson and Schneier's
  12. * generator Fortuna. It collects entropy from various events into several
  13. * pools, implemented by streaming SHA-256 instances. It differs from
  14. * ordinary Fortuna in a few ways, though.
  15. * </p>
  16. *
  17. * <p>
  18. * Most importantly, it has an entropy estimator. This is present because
  19. * there is a strong conflict here between making the generator available
  20. * as soon as possible, and making sure that it doesn't "run on empty".
  21. * In Fortuna, there is a saved state file, and the system is likely to have
  22. * time to warm up.
  23. * </p>
  24. *
  25. * <p>
  26. * Second, because users are unlikely to stay on the page for very long,
  27. * and to speed startup time, the number of pools increases logarithmically:
  28. * a new pool is created when the previous one is actually used for a reseed.
  29. * This gives the same asymptotic guarantees as Fortuna, but gives more
  30. * entropy to early reseeds.
  31. * </p>
  32. *
  33. * <p>
  34. * The entire mechanism here feels pretty klunky. Furthermore, there are
  35. * several improvements that should be made, including support for
  36. * dedicated cryptographic functions that may be present in some browsers;
  37. * state files in local storage; cookies containing randomness; etc. So
  38. * look for improvements in future versions.
  39. * </p>
  40. */
  41. sjcl.random = {
  42. /** Generate several random words, and return them in an array
  43. * @param {Number} nwords The number of words to generate.
  44. */
  45. randomWords: function (nwords, paranoia) {
  46. var out = [], i, readiness = this.isReady(paranoia), g;
  47. if (readiness === this._NOT_READY) {
  48. throw new sjcl.exception.notReady("generator isn't seeded");
  49. } else if (readiness & this._REQUIRES_RESEED) {
  50. this._reseedFromPools(!(readiness & this._READY));
  51. }
  52. for (i=0; i<nwords; i+= 4) {
  53. if ((i+1) % this._MAX_WORDS_PER_BURST === 0) {
  54. this._gate();
  55. }
  56. g = this._gen4words();
  57. out.push(g[0],g[1],g[2],g[3]);
  58. }
  59. this._gate();
  60. return out.slice(0,nwords);
  61. },
  62. setDefaultParanoia: function (paranoia) {
  63. this._defaultParanoia = paranoia;
  64. },
  65. /**
  66. * Add entropy to the pools.
  67. * @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string
  68. * @param {Number} estimatedEntropy The estimated entropy of data, in bits
  69. * @param {String} source The source of the entropy, eg "mouse"
  70. */
  71. addEntropy: function (data, estimatedEntropy, source) {
  72. source = source || "user";
  73. var id,
  74. i, tmp,
  75. t = (new Date()).valueOf(),
  76. robin = this._robins[source],
  77. oldReady = this.isReady(), err = 0;
  78. id = this._collectorIds[source];
  79. if (id === undefined) { id = this._collectorIds[source] = this._collectorIdNext ++; }
  80. if (robin === undefined) { robin = this._robins[source] = 0; }
  81. this._robins[source] = ( this._robins[source] + 1 ) % this._pools.length;
  82. switch(typeof(data)) {
  83. case "number":
  84. if (estimatedEntropy === undefined) {
  85. estimatedEntropy = 1;
  86. }
  87. this._pools[robin].update([id,this._eventId++,1,estimatedEntropy,t,1,data|0]);
  88. break;
  89. case "object":
  90. if (Object.prototype.toString.call(data) !== "[object Array]") {
  91. err = 1;
  92. }
  93. for (i=0; i<data.length && !err; i++) {
  94. if (typeof(data[i]) != "number") {
  95. err = 1;
  96. }
  97. }
  98. if (!err) {
  99. if (estimatedEntropy === undefined) {
  100. /* horrible entropy estimator */
  101. estimatedEntropy = 0;
  102. for (i=0; i<data.length; i++) {
  103. tmp= data[i];
  104. while (tmp>0) {
  105. estimatedEntropy++;
  106. tmp = tmp >>> 1;
  107. }
  108. }
  109. }
  110. this._pools[robin].update([id,this._eventId++,2,estimatedEntropy,t,data.length].concat(data));
  111. }
  112. break;
  113. case "string":
  114. if (estimatedEntropy === undefined) {
  115. /* English text has just over 1 bit per character of entropy.
  116. * But this might be HTML or something, and have far less
  117. * entropy than English... Oh well, let's just say one bit.
  118. */
  119. estimatedEntropy = data.length;
  120. }
  121. this._pools[robin].update([id,this._eventId++,3,estimatedEntropy,t,data.length]);
  122. this._pools[robin].update(data);
  123. break;
  124. default:
  125. err=1;
  126. }
  127. if (err) {
  128. throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");
  129. }
  130. /* record the new strength */
  131. this._poolEntropy[robin] += estimatedEntropy;
  132. this._poolStrength += estimatedEntropy;
  133. /* fire off events */
  134. if (oldReady === this._NOT_READY) {
  135. if (this.isReady() !== this._NOT_READY) {
  136. this._fireEvent("seeded", Math.max(this._strength, this._poolStrength));
  137. }
  138. this._fireEvent("progress", this.getProgress());
  139. }
  140. },
  141. /** Is the generator ready? */
  142. isReady: function (paranoia) {
  143. var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ];
  144. if (this._strength && this._strength >= entropyRequired) {
  145. return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?
  146. this._REQUIRES_RESEED | this._READY :
  147. this._READY;
  148. } else {
  149. return (this._poolStrength >= entropyRequired) ?
  150. this._REQUIRES_RESEED | this._NOT_READY :
  151. this._NOT_READY;
  152. }
  153. },
  154. /** Get the generator's progress toward readiness, as a fraction */
  155. getProgress: function (paranoia) {
  156. var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ];
  157. if (this._strength >= entropyRequired) {
  158. return 1.0;
  159. } else {
  160. return (this._poolStrength > entropyRequired) ?
  161. 1.0 :
  162. this._poolStrength / entropyRequired;
  163. }
  164. },
  165. /** start the built-in entropy collectors */
  166. startCollectors: function () {
  167. if (this._collectorsStarted) { return; }
  168. if (window.addEventListener) {
  169. window.addEventListener("load", this._loadTimeCollector, false);
  170. window.addEventListener("mousemove", this._mouseCollector, false);
  171. } else if (document.attachEvent) {
  172. document.attachEvent("onload", this._loadTimeCollector);
  173. document.attachEvent("onmousemove", this._mouseCollector);
  174. }
  175. else {
  176. throw new sjcl.exception.bug("can't attach event");
  177. }
  178. this._collectorsStarted = true;
  179. },
  180. /** stop the built-in entropy collectors */
  181. stopCollectors: function () {
  182. if (!this._collectorsStarted) { return; }
  183. if (window.removeEventListener) {
  184. window.removeEventListener("load", this._loadTimeCollector, false);
  185. window.removeEventListener("mousemove", this._mouseCollector, false);
  186. } else if (window.detachEvent) {
  187. window.detachEvent("onload", this._loadTimeCollector);
  188. window.detachEvent("onmousemove", this._mouseCollector);
  189. }
  190. this._collectorsStarted = false;
  191. },
  192. /* use a cookie to store entropy.
  193. useCookie: function (all_cookies) {
  194. throw new sjcl.exception.bug("random: useCookie is unimplemented");
  195. },*/
  196. /** add an event listener for progress or seeded-ness. */
  197. addEventListener: function (name, callback) {
  198. this._callbacks[name][this._callbackI++] = callback;
  199. },
  200. /** remove an event listener for progress or seeded-ness */
  201. removeEventListener: function (name, cb) {
  202. var i, j, cbs=this._callbacks[name], jsTemp=[];
  203. /* I'm not sure if this is necessary; in C++, iterating over a
  204. * collection and modifying it at the same time is a no-no.
  205. */
  206. for (j in cbs) {
  207. if (cbs.hasOwnProperty(j) && cbs[j] === cb) {
  208. jsTemp.push(j);
  209. }
  210. }
  211. for (i=0; i<jsTemp.length; i++) {
  212. j = jsTemp[i];
  213. delete cbs[j];
  214. }
  215. },
  216. /* private */
  217. _pools : [new sjcl.hash.sha256()],
  218. _poolEntropy : [0],
  219. _reseedCount : 0,
  220. _robins : {},
  221. _eventId : 0,
  222. _collectorIds : {},
  223. _collectorIdNext : 0,
  224. _strength : 0,
  225. _poolStrength : 0,
  226. _nextReseed : 0,
  227. _key : [0,0,0,0,0,0,0,0],
  228. _counter : [0,0,0,0],
  229. _cipher : undefined,
  230. _defaultParanoia : 6,
  231. /* event listener stuff */
  232. _collectorsStarted : false,
  233. _callbacks : {progress: {}, seeded: {}},
  234. _callbackI : 0,
  235. /* constants */
  236. _NOT_READY : 0,
  237. _READY : 1,
  238. _REQUIRES_RESEED : 2,
  239. _MAX_WORDS_PER_BURST : 65536,
  240. _PARANOIA_LEVELS : [0,48,64,96,128,192,256,384,512,768,1024],
  241. _MILLISECONDS_PER_RESEED : 30000,
  242. _BITS_PER_RESEED : 80,
  243. /** Generate 4 random words, no reseed, no gate.
  244. * @private
  245. */
  246. _gen4words: function () {
  247. for (var i=0; i<4; i++) {
  248. this._counter[i] = this._counter[i]+1 | 0;
  249. if (this._counter[i]) { break; }
  250. }
  251. return this._cipher.encrypt(this._counter);
  252. },
  253. /* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.
  254. * @private
  255. */
  256. _gate: function () {
  257. this._key = this._gen4words().concat(this._gen4words());
  258. this._cipher = new sjcl.cipher.aes(this._key);
  259. },
  260. /** Reseed the generator with the given words
  261. * @private
  262. */
  263. _reseed: function (seedWords) {
  264. this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));
  265. this._cipher = new sjcl.cipher.aes(this._key);
  266. for (var i=0; i<4; i++) {
  267. this._counter[i] = this._counter[i]+1 | 0;
  268. if (this._counter[i]) { break; }
  269. }
  270. },
  271. /** reseed the data from the entropy pools
  272. * @param full If set, use all the entropy pools in the reseed.
  273. */
  274. _reseedFromPools: function (full) {
  275. var reseedData = [], strength = 0, i;
  276. this._nextReseed = reseedData[0] =
  277. (new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;
  278. for (i=0; i<16; i++) {
  279. /* On some browsers, this is cryptographically random. So we might
  280. * as well toss it in the pot and stir...
  281. */
  282. reseedData.push(Math.random()*0x100000000|0);
  283. }
  284. for (i=0; i<this._pools.length; i++) {
  285. reseedData = reseedData.concat(this._pools[i].finalize());
  286. strength += this._poolEntropy[i];
  287. this._poolEntropy[i] = 0;
  288. if (!full && (this._reseedCount & (1<<i))) { break; }
  289. }
  290. /* if we used the last pool, push a new one onto the stack */
  291. if (this._reseedCount >= 1 << this._pools.length) {
  292. this._pools.push(new sjcl.hash.sha256());
  293. this._poolEntropy.push(0);
  294. }
  295. /* how strong was this reseed? */
  296. this._poolStrength -= strength;
  297. if (strength > this._strength) {
  298. this._strength = strength;
  299. }
  300. this._reseedCount ++;
  301. this._reseed(reseedData);
  302. },
  303. _mouseCollector: function (ev) {
  304. var x = ev.x || ev.clientX || ev.offsetX, y = ev.y || ev.clientY || ev.offsetY;
  305. sjcl.random.addEntropy([x,y], 2, "mouse");
  306. },
  307. _loadTimeCollector: function (ev) {
  308. sjcl.random.addEntropy((new Date()).valueOf(), 2, "loadtime");
  309. },
  310. _fireEvent: function (name, arg) {
  311. var j, cbs=sjcl.random._callbacks[name], cbsTemp=[];
  312. /* TODO: there is a race condition between removing collectors and firing them */
  313. /* I'm not sure if this is necessary; in C++, iterating over a
  314. * collection and modifying it at the same time is a no-no.
  315. */
  316. for (j in cbs) {
  317. if (cbs.hasOwnProperty(j)) {
  318. cbsTemp.push(cbs[j]);
  319. }
  320. }
  321. for (j=0; j<cbsTemp.length; j++) {
  322. cbsTemp[j](arg);
  323. }
  324. }
  325. };
  326. (function(){
  327. try {
  328. // get cryptographically strong entropy in Webkit
  329. var ab = new Uint32Array(32);
  330. crypto.getRandomValues(ab);
  331. sjcl.random.addEntropy(ab, 1024, "crypto.getRandomValues");
  332. } catch (e) {
  333. // no getRandomValues :-(
  334. }
  335. })();