UNPKG

876 BJavaScriptView Raw
1var crypto = require('crypto')
2
3if (crypto.randomFill) {
4 // `crypto.randomFill()` is a little fatser than `crypto.randomBytes()`,
5 // because we can use faster `Buffer.allocUnsafe()`.
6 module.exports = function (bytes) {
7 return new Promise(function (resolve, reject) {
8 // `Buffer.allocUnsafe()` faster because it don’t clean memory.
9 // We do not need it, since we will fill memory with new bytes anyway.
10 crypto.randomFill(Buffer.allocUnsafe(bytes), function (err, buf) {
11 if (err) {
12 reject(err)
13 } else {
14 resolve(buf)
15 }
16 })
17 })
18 }
19} else {
20 module.exports = function (bytes) {
21 return new Promise(function (resolve, reject) {
22 crypto.randomBytes(bytes, function (err, buf) {
23 if (err) {
24 reject(err)
25 } else {
26 resolve(buf)
27 }
28 })
29 })
30 }
31}