Using the following function, i'm able to generate random integers within a specific range:
function random_int(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
so if we use random_int(0,2)
we should expect to have the values 0,1 or 2 to be returned.
Tho, as some of you may already know, Math.random(); is not cryptographically secure. The reason i need unpredictable numbers is that I want to generate secure captchas as part of me learning how to use canvas and node.js. (Draw random lines and text, for example)
So i've been duckduckin' around the web for a solution, and found this:
const buf = crypto.randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
Which does works, but it also returns letters and I have absolutely no idea of how to implement this random "number" generator in my existing function...
I've also read about some people attempting to create number generators from this function but i'd like you guy's feedback on this as "my own Cryptography.random() function" sounds like a red flag in crypto, apparently.
Thanks in advance!
-- EDIT --
Thanks to Andre Nel, here is my new function for random numbers! Big thanks to him.
const crypto = require("crypto"); //import crypto
var converter = require('hex2dec');
// Cryptographically secure random integer
function random_int_c(min, max) {
const buf = crypto.randomBytes(1);
var dec = converter.hexToDec(buf.toString('hex')).substring(0, 2);
return Math.floor(Number("0."+dec) * (max - min + 1) + min);
}