You can easily generate random strings in Node.js like this:
var crypto = require('crypto')
var str = crypto.randomBytes(8).toString('hex')
But that returns a hex value. Meanwhile, you can generate a non-cryptographically secure random integer like this:
Math.random() * Math.pow(36, 2) << 0
I'm wondering how to make a random integer like one generated from Math.random() * Math.pow(base, exponent) << 0
, but so that it is cryptographically secure, and works cross-platform. The math involved in this is over my head.
Here is what I have so far:
// browser:
// generates random 32 bit integer,
// not sure how a 32-bit integer relates to
// Math.random() * Math.pow(base, exponent) << 0
var array = new Uint32Array(1)
module.exports = function(){
window.crypto.getRandomValues(array)
var value = array[0]
array[0] = 0
return value
}
// node:
// generates random hex string,
// tried formatting to a decimal notation,
// but not sure how to determine the size of the integer
// (not sure if it's a 32-bit like the browser version,
// or within the range of
// Math.random() * Math.pow(base, exponent) << 0)
var crypto = require('crypto')
var biguint = require('biguint-format')
module.exports = function(){
return biguint.format(crypto.randomBytes(notSureWhatSize), 'dec')
}
Found that biguint-format from here.
Not sure what steps to do to convert the cases to an integer in the range of Math.pow(base, exponent)
.
Aucun commentaire:
Enregistrer un commentaire