repl.it
@nwtgck/

secure-random-number

Nodejs

No description

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const crypto = require('crypto');

const nBytes   = 4;
// Max value
// (= 4294967295) (= (1 << 4*8) - 1)
const maxValue = new Buffer(Array(nBytes).fill(0xff)).readUIntBE(0, nBytes); 

function secureRandom() {
  const randomBytes = crypto.randomBytes(nBytes);
  const r = randomBytes.readUIntBE(0, nBytes);
  return r / maxValue;
}

for(let i = 0; i < 100; i++) {
  const r = secureRandom();
  console.log(r);
}
node v10.16.0