Rahul
Rahul

Reputation: 1110

How to generate a Random token of 32 bit in Javascript?

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

Upvotes: 2

Views: 16606

Answers (5)

Jonathan
Jonathan

Reputation: 1419

This will generate the 32 bit random alphanumeric string as requested:

crypto.getRandomValues(new Uint8Array(4)).reduce((p,c)=>p+String.fromCharCode(c))

Upvotes: 0

Empowerful
Empowerful

Reputation: 21

Inspired by Paul S.'s answer but a little simpler:

const Token = () => {
  const array = new Uint32Array(1)
  window.crypto.getRandomValues(array)
  return array[0].toString(36)
}

Upvotes: 2

Paul S.
Paul S.

Reputation: 66334

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

Upvotes: 9

Bubble Hacker
Bubble Hacker

Reputation: 6723

You can use this function:

function returnHash(){
    abc = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
    var token=""; 
    for(i=0;i<32;i++){
         token += abc[Math.floor(Math.random()*abc.length)];
    }
    return token; //Will return a 32 bit "hash"
}

Use by calling returnHash()

Upvotes: 0

guest271314
guest271314

Reputation: 1

I need to generate an accurate 32 bits random alphanumeric string in JavaScript.

If you mean 32 characters, you can use URL.createObjectURL, String.prototype.slice(), String.prototype.replace()

var rand = URL.createObjectURL(new Blob([])).slice(-36).replace(/-/g, "")

Upvotes: 2

Related Questions