random.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /**
  2. * An API for getting cryptographically-secure random bytes. The bytes are
  3. * generated using the Fortuna algorithm devised by Bruce Schneier and
  4. * Niels Ferguson.
  5. *
  6. * Getting strong random bytes is not yet easy to do in javascript. The only
  7. * truish random entropy that can be collected is from the mouse, keyboard, or
  8. * from timing with respect to page loads, etc. This generator makes a poor
  9. * attempt at providing random bytes when those sources haven't yet provided
  10. * enough entropy to initially seed or to reseed the PRNG.
  11. *
  12. * @author Dave Longley
  13. *
  14. * Copyright (c) 2009-2014 Digital Bazaar, Inc.
  15. */
  16. var forge = require('./forge');
  17. require('./aes');
  18. require('./sha256');
  19. require('./prng');
  20. require('./util');
  21. (function() {
  22. // forge.random already defined
  23. if(forge.random && forge.random.getBytes) {
  24. module.exports = forge.random;
  25. return;
  26. }
  27. (function(jQuery) {
  28. // the default prng plugin, uses AES-128
  29. var prng_aes = {};
  30. var _prng_aes_output = new Array(4);
  31. var _prng_aes_buffer = forge.util.createBuffer();
  32. prng_aes.formatKey = function(key) {
  33. // convert the key into 32-bit integers
  34. var tmp = forge.util.createBuffer(key);
  35. key = new Array(4);
  36. key[0] = tmp.getInt32();
  37. key[1] = tmp.getInt32();
  38. key[2] = tmp.getInt32();
  39. key[3] = tmp.getInt32();
  40. // return the expanded key
  41. return forge.aes._expandKey(key, false);
  42. };
  43. prng_aes.formatSeed = function(seed) {
  44. // convert seed into 32-bit integers
  45. var tmp = forge.util.createBuffer(seed);
  46. seed = new Array(4);
  47. seed[0] = tmp.getInt32();
  48. seed[1] = tmp.getInt32();
  49. seed[2] = tmp.getInt32();
  50. seed[3] = tmp.getInt32();
  51. return seed;
  52. };
  53. prng_aes.cipher = function(key, seed) {
  54. forge.aes._updateBlock(key, seed, _prng_aes_output, false);
  55. _prng_aes_buffer.putInt32(_prng_aes_output[0]);
  56. _prng_aes_buffer.putInt32(_prng_aes_output[1]);
  57. _prng_aes_buffer.putInt32(_prng_aes_output[2]);
  58. _prng_aes_buffer.putInt32(_prng_aes_output[3]);
  59. return _prng_aes_buffer.getBytes();
  60. };
  61. prng_aes.increment = function(seed) {
  62. // FIXME: do we care about carry or signed issues?
  63. ++seed[3];
  64. return seed;
  65. };
  66. prng_aes.md = forge.md.sha256;
  67. /**
  68. * Creates a new PRNG.
  69. */
  70. function spawnPrng() {
  71. var ctx = forge.prng.create(prng_aes);
  72. /**
  73. * Gets random bytes. If a native secure crypto API is unavailable, this
  74. * method tries to make the bytes more unpredictable by drawing from data that
  75. * can be collected from the user of the browser, eg: mouse movement.
  76. *
  77. * If a callback is given, this method will be called asynchronously.
  78. *
  79. * @param count the number of random bytes to get.
  80. * @param [callback(err, bytes)] called once the operation completes.
  81. *
  82. * @return the random bytes in a string.
  83. */
  84. ctx.getBytes = function(count, callback) {
  85. return ctx.generate(count, callback);
  86. };
  87. /**
  88. * Gets random bytes asynchronously. If a native secure crypto API is
  89. * unavailable, this method tries to make the bytes more unpredictable by
  90. * drawing from data that can be collected from the user of the browser,
  91. * eg: mouse movement.
  92. *
  93. * @param count the number of random bytes to get.
  94. *
  95. * @return the random bytes in a string.
  96. */
  97. ctx.getBytesSync = function(count) {
  98. return ctx.generate(count);
  99. };
  100. return ctx;
  101. }
  102. // create default prng context
  103. var _ctx = spawnPrng();
  104. // add other sources of entropy only if window.crypto.getRandomValues is not
  105. // available -- otherwise this source will be automatically used by the prng
  106. var getRandomValues = null;
  107. if(typeof window !== 'undefined') {
  108. var _crypto = window.crypto || window.msCrypto;
  109. if(_crypto && _crypto.getRandomValues) {
  110. getRandomValues = function(arr) {
  111. return _crypto.getRandomValues(arr);
  112. };
  113. }
  114. }
  115. if(forge.options.usePureJavaScript ||
  116. (!forge.util.isNodejs && !getRandomValues)) {
  117. // if this is a web worker, do not use weak entropy, instead register to
  118. // receive strong entropy asynchronously from the main thread
  119. if(typeof window === 'undefined' || window.document === undefined) {
  120. // FIXME:
  121. }
  122. // get load time entropy
  123. _ctx.collectInt(+new Date(), 32);
  124. // add some entropy from navigator object
  125. if(typeof(navigator) !== 'undefined') {
  126. var _navBytes = '';
  127. for(var key in navigator) {
  128. try {
  129. if(typeof(navigator[key]) == 'string') {
  130. _navBytes += navigator[key];
  131. }
  132. } catch(e) {
  133. /* Some navigator keys might not be accessible, e.g. the geolocation
  134. attribute throws an exception if touched in Mozilla chrome://
  135. context.
  136. Silently ignore this and just don't use this as a source of
  137. entropy. */
  138. }
  139. }
  140. _ctx.collect(_navBytes);
  141. _navBytes = null;
  142. }
  143. // add mouse and keyboard collectors if jquery is available
  144. if(jQuery) {
  145. // set up mouse entropy capture
  146. jQuery().mousemove(function(e) {
  147. // add mouse coords
  148. _ctx.collectInt(e.clientX, 16);
  149. _ctx.collectInt(e.clientY, 16);
  150. });
  151. // set up keyboard entropy capture
  152. jQuery().keypress(function(e) {
  153. _ctx.collectInt(e.charCode, 8);
  154. });
  155. }
  156. }
  157. /* Random API */
  158. if(!forge.random) {
  159. forge.random = _ctx;
  160. } else {
  161. // extend forge.random with _ctx
  162. for(var key in _ctx) {
  163. forge.random[key] = _ctx[key];
  164. }
  165. }
  166. // expose spawn PRNG
  167. forge.random.createInstance = spawnPrng;
  168. module.exports = forge.random;
  169. })(typeof(jQuery) !== 'undefined' ? jQuery : null);
  170. })();