1

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

4

1 Answer 1

0

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"
2
  • Highly inefficient solution. Randomizing per character, which stands for 4 bits, is totally unnecessary. Commented Jun 24, 2021 at 13:09
  • Flagging your solution as highly inefficient is a positive contribution to whoever reads your advice. But it's not truly your solution, having copied it from stackoverflow.com/a/1349426/5524100 (before doing a minor adjustment). Commented Jun 24, 2021 at 14:52