I want to make random bytes and turn it into hexadecimal.
I had used it earlier in php as the id of a database table.
if in php, the code like this
function rand_id(){
return bin2hex(random_bytes(3));
}
how to do that in jquery
The following will work on client-side, however will not be cryptographically secure by any means.
function random_hexadecimal(length) {
var result = '';
var characters = 'abcdef0123456789';
var charactersLength = characters.length;
for (i = 0; i < length; i++) result += characters.charAt(Math.floor(Math.random() * charactersLength));
return result;
}
Or for a one-liner (or just shorter and more clean solution):
const size = 20;
let id = [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
// "6b6a3edaf6f1cbaaf107"
For server-side, you can use the following, it is cryptographically secure.
const crypto = require("crypto");
let id = crypto.randomBytes(20).toString('hex');
// "bb5dc8842ca31d4603d6aa11448d1654"
a
org
or3
or{
, so just place those in an array and use Math.random to get a random byte.