1 |
3a515b92
|
cagy
|
'use strict'
|
2 |
|
|
|
3 |
|
|
// limit of Crypto.getRandomValues()
|
4 |
|
|
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
|
5 |
|
|
var MAX_BYTES = 65536
|
6 |
|
|
|
7 |
|
|
// Node supports requesting up to this number of bytes
|
8 |
|
|
// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
|
9 |
|
|
var MAX_UINT32 = 4294967295
|
10 |
|
|
|
11 |
|
|
function oldBrowser () {
|
12 |
|
|
throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
|
13 |
|
|
}
|
14 |
|
|
|
15 |
|
|
var Buffer = require('safe-buffer').Buffer
|
16 |
|
|
var crypto = global.crypto || global.msCrypto
|
17 |
|
|
|
18 |
|
|
if (crypto && crypto.getRandomValues) {
|
19 |
|
|
module.exports = randomBytes
|
20 |
|
|
} else {
|
21 |
|
|
module.exports = oldBrowser
|
22 |
|
|
}
|
23 |
|
|
|
24 |
|
|
function randomBytes (size, cb) {
|
25 |
|
|
// phantomjs needs to throw
|
26 |
|
|
if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
|
27 |
|
|
|
28 |
|
|
var bytes = Buffer.allocUnsafe(size)
|
29 |
|
|
|
30 |
|
|
if (size > 0) { // getRandomValues fails on IE if size == 0
|
31 |
|
|
if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
|
32 |
|
|
// can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
|
33 |
|
|
for (var generated = 0; generated < size; generated += MAX_BYTES) {
|
34 |
|
|
// buffer.slice automatically checks if the end is past the end of
|
35 |
|
|
// the buffer so we don't have to here
|
36 |
|
|
crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
|
37 |
|
|
}
|
38 |
|
|
} else {
|
39 |
|
|
crypto.getRandomValues(bytes)
|
40 |
|
|
}
|
41 |
|
|
}
|
42 |
|
|
|
43 |
|
|
if (typeof cb === 'function') {
|
44 |
|
|
return process.nextTick(function () {
|
45 |
|
|
cb(null, bytes)
|
46 |
|
|
})
|
47 |
|
|
}
|
48 |
|
|
|
49 |
|
|
return bytes
|
50 |
|
|
}
|