index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*!
  2. * random-bytes
  3. * Copyright(c) 2016 Douglas Christopher Wilson
  4. * MIT Licensed
  5. */
  6. 'use strict'
  7. /**
  8. * Module dependencies.
  9. * @private
  10. */
  11. var crypto = require('crypto')
  12. /**
  13. * Module variables.
  14. * @private
  15. */
  16. var generateAttempts = crypto.randomBytes === crypto.pseudoRandomBytes ? 1 : 3
  17. /**
  18. * Module exports.
  19. * @public
  20. */
  21. module.exports = randomBytes
  22. module.exports.sync = randomBytesSync
  23. /**
  24. * Generates strong pseudo-random bytes.
  25. *
  26. * @param {number} size
  27. * @param {function} [callback]
  28. * @return {Promise}
  29. * @public
  30. */
  31. function randomBytes(size, callback) {
  32. // validate callback is a function, if provided
  33. if (callback !== undefined && typeof callback !== 'function') {
  34. throw new TypeError('argument callback must be a function')
  35. }
  36. // require the callback without promises
  37. if (!callback && !global.Promise) {
  38. throw new TypeError('argument callback is required')
  39. }
  40. if (callback) {
  41. // classic callback style
  42. return generateRandomBytes(size, generateAttempts, callback)
  43. }
  44. return new Promise(function executor(resolve, reject) {
  45. generateRandomBytes(size, generateAttempts, function onRandomBytes(err, str) {
  46. if (err) return reject(err)
  47. resolve(str)
  48. })
  49. })
  50. }
  51. /**
  52. * Generates strong pseudo-random bytes sync.
  53. *
  54. * @param {number} size
  55. * @return {Buffer}
  56. * @public
  57. */
  58. function randomBytesSync(size) {
  59. var err = null
  60. for (var i = 0; i < generateAttempts; i++) {
  61. try {
  62. return crypto.randomBytes(size)
  63. } catch (e) {
  64. err = e
  65. }
  66. }
  67. throw err
  68. }
  69. /**
  70. * Generates strong pseudo-random bytes.
  71. *
  72. * @param {number} size
  73. * @param {number} attempts
  74. * @param {function} callback
  75. * @private
  76. */
  77. function generateRandomBytes(size, attempts, callback) {
  78. crypto.randomBytes(size, function onRandomBytes(err, buf) {
  79. if (!err) return callback(null, buf)
  80. if (!--attempts) return callback(err)
  81. setTimeout(generateRandomBytes.bind(null, size, attempts, callback), 10)
  82. })
  83. }