browser.js 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict'
  2. function oldBrowser () {
  3. throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
  4. }
  5. var Buffer = require('safe-buffer').Buffer
  6. var crypto = global.crypto || global.msCrypto
  7. if (crypto && crypto.getRandomValues) {
  8. module.exports = randomBytes
  9. } else {
  10. module.exports = oldBrowser
  11. }
  12. function randomBytes (size, cb) {
  13. // phantomjs needs to throw
  14. if (size > 65536) throw new Error('requested too many random bytes')
  15. // in case browserify isn't using the Uint8Array version
  16. var rawBytes = new global.Uint8Array(size)
  17. // This will not work in older browsers.
  18. // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
  19. if (size > 0) { // getRandomValues fails on IE if size == 0
  20. crypto.getRandomValues(rawBytes)
  21. }
  22. // XXX: phantomjs doesn't like a buffer being passed here
  23. var bytes = Buffer.from(rawBytes.buffer)
  24. if (typeof cb === 'function') {
  25. return process.nextTick(function () {
  26. cb(null, bytes)
  27. })
  28. }
  29. return bytes
  30. }