Dowemo
0 0 0 0


Question:

I need to generate an accurate 32 bits random alphanumeric string in JavaScript.
Is there any direct function to do it ?


Best Answer:


Using crypto and a typed array;

function random32bit() {
    let u = new Uint32Array(1);
    window.crypto.getRandomValues(u);
    let str = u[0].toString(16).toUpperCase();
    return '00000000'.slice(str.length) + str;
}

This gives us a 32-bit crypto-random number represented as a zero-padded string of 8 chars (base 16)

If you want to extend this to arbitrary numbers of chars;

function randomHash(nChar) {
    let nBytes = Math.ceil(nChar = (+nChar || 8) / 2);
    let u = new Uint8Array(nBytes);
    window.crypto.getRandomValues(u);
    let zpad = str => '00'.slice(str.length) + str;
    let a = Array.prototype.map.call(u, x => zpad(x.toString(16)));
    let str = a.join('').toUpperCase();
    if (nChar % 2) str = str.slice(1);
    return str;
}

In ES5, with comments

function randomHash(nChar) {
    // convert number of characters to number of bytes
    var nBytes = Math.ceil(nChar = (+nChar || 8) / 2);
    // create a typed array of that many bytes
    var u = new Uint8Array(nBytes);
    // populate it wit crypto-random values
    window.crypto.getRandomValues(u);
    // convert it to an Array of Strings (e.g. "01", "AF", ..)
    var zpad = function (str) {
        return '00'.slice(str.length) + str
    };
    var a = Array.prototype.map.call(u, function (x) {
        return zpad(x.toString(16))
    });
    // Array of String to String
    var str = a.join('').toUpperCase();
    // and snip off the excess digit if we want an odd number
    if (nChar % 2) str = str.slice(1);
    // return what we made
    return str;
}



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs