index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var r;
  2. module.exports = function rand(len) {
  3. if (!r)
  4. r = new Rand(null);
  5. return r.generate(len);
  6. };
  7. function Rand(rand) {
  8. this.rand = rand;
  9. }
  10. module.exports.Rand = Rand;
  11. Rand.prototype.generate = function generate(len) {
  12. return this._rand(len);
  13. };
  14. // Emulate crypto API using randy
  15. Rand.prototype._rand = function _rand(n) {
  16. if (this.rand.getBytes)
  17. return this.rand.getBytes(n);
  18. var res = new Uint8Array(n);
  19. for (var i = 0; i < res.length; i++)
  20. res[i] = this.rand.getByte();
  21. return res;
  22. };
  23. if (typeof self === 'object') {
  24. if (self.crypto && self.crypto.getRandomValues) {
  25. // Modern browsers
  26. Rand.prototype._rand = function _rand(n) {
  27. var arr = new Uint8Array(n);
  28. self.crypto.getRandomValues(arr);
  29. return arr;
  30. };
  31. } else if (self.msCrypto && self.msCrypto.getRandomValues) {
  32. // IE
  33. Rand.prototype._rand = function _rand(n) {
  34. var arr = new Uint8Array(n);
  35. self.msCrypto.getRandomValues(arr);
  36. return arr;
  37. };
  38. // Safari's WebWorkers do not have `crypto`
  39. } else if (typeof window === 'object') {
  40. // Old junk
  41. Rand.prototype._rand = function() {
  42. throw new Error('Not implemented yet');
  43. };
  44. }
  45. } else {
  46. // Node.js or Web worker with no crypto support
  47. try {
  48. var crypto = require('crypto');
  49. if (typeof crypto.randomBytes !== 'function')
  50. throw new Error('Not supported');
  51. Rand.prototype._rand = function _rand(n) {
  52. return crypto.randomBytes(n);
  53. };
  54. } catch (e) {
  55. }
  56. }