简体   繁体   中英

how get random bytes, and convert it to hex in jquery

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

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;
}

You can use the above

Edit:

If you would like to do this server side, you can use the crypto module

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

Edit2:

You can also use this: 
var size = 20;
var id = [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');


// "6b6a3edaf6f1cbaaf107"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM