random.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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, ty = 0, tmp,
  75. t = (new Date()).valueOf(),
  76. robin = this._robins[source],
  77. oldReady = this.isReady();
  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. data=[data];
  85. ty=1;
  86. break;
  87. case "object":
  88. if (estimatedEntropy === undefined) {
  89. /* horrible entropy estimator */
  90. estimatedEntropy = 0;
  91. for (i=0; i<data.length; i++) {
  92. tmp= data[i];
  93. while (tmp>0) {
  94. estimatedEntropy++;
  95. tmp = tmp >>> 1;
  96. }
  97. }
  98. }
  99. this._pools[robin].update([id,this._eventId++,ty||2,estimatedEntropy,t,data.length].concat(data));
  100. break;
  101. case "string":
  102. if (estimatedEntropy === undefined) {
  103. /* English text has just over 1 bit per character of entropy.
  104. * But this might be HTML or something, and have far less
  105. * entropy than English... Oh well, let's just say one bit.
  106. */
  107. estimatedEntropy = data.length;
  108. }
  109. this._pools[robin].update([id,this._eventId++,3,estimatedEntropy,t,data.length]);
  110. this._pools[robin].update(data);
  111. break;
  112. default:
  113. throw new sjcl.exception.bug("random: addEntropy only supports number, array or string");
  114. }
  115. /* record the new strength */
  116. this._poolEntropy[robin] += estimatedEntropy;
  117. this._poolStrength += estimatedEntropy;
  118. /* fire off events */
  119. if (oldReady === this._NOT_READY) {
  120. if (this.isReady() !== this._NOT_READY) {
  121. this._fireEvent("seeded", Math.max(this._strength, this._poolStrength));
  122. }
  123. this._fireEvent("progress", this.getProgress());
  124. }
  125. },
  126. /** Is the generator ready? */
  127. isReady: function (paranoia) {
  128. var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ];
  129. if (this._strength && this._strength >= entropyRequired) {
  130. return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?
  131. this._REQUIRES_RESEED | this._READY :
  132. this._READY;
  133. } else {
  134. return (this._poolStrength >= entropyRequired) ?
  135. this._REQUIRES_RESEED | this._NOT_READY :
  136. this._NOT_READY;
  137. }
  138. },
  139. /** Get the generator's progress toward readiness, as a fraction */
  140. getProgress: function (paranoia) {
  141. var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ];
  142. if (this._strength >= entropyRequired) {
  143. return 1.0;
  144. } else {
  145. return (this._poolStrength > entropyRequired) ?
  146. 1.0 :
  147. this._poolStrength / entropyRequired;
  148. }
  149. },
  150. /** start the built-in entropy collectors */
  151. startCollectors: function () {
  152. if (this._collectorsStarted) { return; }
  153. if (window.addEventListener) {
  154. window.addEventListener("load", this._loadTimeCollector, false);
  155. window.addEventListener("mousemove", this._mouseCollector, false);
  156. } else if (document.attachEvent) {
  157. document.attachEvent("onload", this._loadTimeCollector);
  158. document.attachEvent("onmousemove", this._mouseCollector);
  159. }
  160. else {
  161. throw new sjcl.exception.bug("can't attach event");
  162. }
  163. this._collectorsStarted = true;
  164. },
  165. /** stop the built-in entropy collectors */
  166. stopCollectors: function () {
  167. if (!this._collectorsStarted) { return; }
  168. if (window.removeEventListener) {
  169. window.removeEventListener("load", this._loadTimeCollector);
  170. window.removeEventListener("mousemove", this._mouseCollector);
  171. } else if (window.detachEvent) {
  172. window.detachEvent("onload", this._loadTimeCollector);
  173. window.detachEvent("onmousemove", this._mouseCollector);
  174. }
  175. this._collectorsStarted = false;
  176. },
  177. /* use a cookie to store entropy.
  178. useCookie: function (all_cookies) {
  179. throw new sjcl.exception.bug("random: useCookie is unimplemented");
  180. },*/
  181. /** add an event listener for progress or seeded-ness. */
  182. addEventListener: function (name, callback) {
  183. this._callbacks[name][this._callbackI++] = callback;
  184. },
  185. /** remove an event listener for progress or seeded-ness */
  186. removeEventListener: function (name, cb) {
  187. var i, j, cbs=this._callbacks[name], jsTemp=[];
  188. /* I'm not sure if this is necessary; in C++, iterating over a
  189. * collection and modifying it at the same time is a no-no.
  190. */
  191. for (j in cbs) {
  192. if (cbs.hasOwnProperty[j] && cbs[j] === cb) {
  193. jsTemp.push(j);
  194. }
  195. }
  196. for (i=0; i<jsTemp.length; i++) {
  197. j = jsTemp[i];
  198. delete cbs[j];
  199. }
  200. },
  201. /* private */
  202. _pools : [new sjcl.hash.sha256()],
  203. _poolEntropy : [0],
  204. _reseedCount : 0,
  205. _robins : {},
  206. _eventId : 0,
  207. _collectorIds : {},
  208. _collectorIdNext : 0,
  209. _strength : 0,
  210. _poolStrength : 0,
  211. _nextReseed : 0,
  212. _key : [0,0,0,0,0,0,0,0],
  213. _counter : [0,0,0,0],
  214. _cipher : undefined,
  215. _defaultParanoia : 6,
  216. /* event listener stuff */
  217. _collectorsStarted : false,
  218. _callbacks : {progress: {}, seeded: {}},
  219. _callbackI : 0,
  220. /* constants */
  221. _NOT_READY : 0,
  222. _READY : 1,
  223. _REQUIRES_RESEED : 2,
  224. _MAX_WORDS_PER_BURST : 65536,
  225. _PARANOIA_LEVELS : [0,48,64,96,128,192,256,384,512,768,1024],
  226. _MILLISECONDS_PER_RESEED : 30000,
  227. _BITS_PER_RESEED : 80,
  228. /** Generate 4 random words, no reseed, no gate.
  229. * @private
  230. */
  231. _gen4words: function () {
  232. for (var i=0; i<4; i++) {
  233. this._counter[i] = this._counter[i]+1 | 0;
  234. if (this._counter[i]) { break; }
  235. }
  236. return this._cipher.encrypt(this._counter);
  237. },
  238. /* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.
  239. * @private
  240. */
  241. _gate: function () {
  242. this._key = this._gen4words().concat(this._gen4words());
  243. this._cipher = new sjcl.cipher.aes(this._key);
  244. },
  245. /** Reseed the generator with the given words
  246. * @private
  247. */
  248. _reseed: function (seedWords) {
  249. this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));
  250. this._cipher = new sjcl.cipher.aes(this._key);
  251. for (var i=0; i<4; i++) {
  252. this._counter[i] = this._counter[i]+1 | 0;
  253. if (this._counter[i]) { break; }
  254. }
  255. },
  256. /** reseed the data from the entropy pools
  257. * @param full If set, use all the entropy pools in the reseed.
  258. */
  259. _reseedFromPools: function (full) {
  260. var reseedData = [], strength = 0, i;
  261. this._nextReseed = reseedData[0] =
  262. (new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;
  263. for (i=0; i<16; i++) {
  264. /* On some browsers, this is cryptographically random. So we might
  265. * as well toss it in the pot and stir...
  266. */
  267. reseedData.push(Math.random()*0x100000000|0);
  268. }
  269. for (i=0; i<this._pools.length; i++) {
  270. reseedData = reseedData.concat(this._pools[i].finalize());
  271. strength += this._poolEntropy[i];
  272. this._poolEntropy[i] = 0;
  273. if (!full && (this._reseedCount & (1<<i))) { break; }
  274. }
  275. /* if we used the last pool, push a new one onto the stack */
  276. if (this._reseedCount >= 1 << this._pools.length) {
  277. this._pools.push(new sjcl.hash.sha256());
  278. this._poolEntropy.push(0);
  279. }
  280. /* how strong was this reseed? */
  281. this._poolStrength -= strength;
  282. if (strength > this._strength) {
  283. this._strength = strength;
  284. }
  285. this._reseedCount ++;
  286. this._reseed(reseedData);
  287. },
  288. _mouseCollector: function (ev) {
  289. var x = ev.x || ev.clientX || ev.offsetX, y = ev.y || ev.clientY || ev.offsetY;
  290. sjcl.random.addEntropy([x,y], 2, "mouse");
  291. },
  292. _loadTimeCollector: function (ev) {
  293. var d = new Date();
  294. sjcl.random.addEntropy(d, 2, "loadtime");
  295. },
  296. _fireEvent: function (name, arg) {
  297. var j, cbs=sjcl.random._callbacks[name], cbsTemp=[];
  298. /* TODO: there is a race condition between removing collectors and firing them */
  299. /* I'm not sure if this is necessary; in C++, iterating over a
  300. * collection and modifying it at the same time is a no-no.
  301. */
  302. for (j in cbs) {
  303. if (cbs.hasOwnProperty(j)) {
  304. cbsTemp.push(cbs[j]);
  305. }
  306. }
  307. for (j=0; j<cbsTemp.length; j++) {
  308. cbsTemp[j](arg);
  309. }
  310. }
  311. };