Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Stanford PRNG to generate a random string?

I need to generate a secure 50 characters random string in the users browsers.

Looking at sjcl.prng I've got this so far:

$(document).ready(function () {

    sjcl.random = new sjcl.prng(8);

    sjcl.random.startCollectors();

    $("body").on('mousemove', function() {
        console.log(sjcl.random.getProgress(8));

        if(sjcl.random.isReady(8) === 2) {
            sjcl.random.stopCollectors();
            console.log(sjcl.random.randomWords(5,8));
        }
    });

});

After moving the mouse around for a while I get a byte array like this: [-579285364, 1099191484, 94979086, -1572161987, -570940948].

But what I'm looking for is a 50 character alphanumeric string. My knowledge on this topic is limited and I'm looking for some help here.

like image 797
Martijn19 Avatar asked Jun 13 '14 18:06

Martijn19


People also ask

How do you generate random strings in C sharp?

We can generate a random string using the Next() method.

How do you generate random alphanumeric strings?

Another way to generate random Strings in Java both alphanumeric and numeric is to use the Math. random() class just like we used it for generating random numbers and pick a random character from a defined character set like a set of uppercase and lowercase alphabets and numbers.


2 Answers

Here's how I solved it:

function createRandomString (callback, length) {
  var randomBase64String = '',
  checkReadyness;

  checkReadyness = setInterval(function () {
    console.log(length);
    if(sjcl.random.isReady(10)) {
      while(randomBase64String.length < length) {
        randomInt = sjcl.random.randomWords(1, 10)[0];
        randomBase64String += btoa(randomInt);
      }
      randomBase64String = randomBase64String.substr(0, length);
      callback(randomBase64String);
      clearInterval(checkReadyness);
    }
  }, 1);
}

This doesn't work in older browsers though. Because I used window.btoa().

like image 133
halbgut Avatar answered Oct 12 '22 13:10

halbgut


  1. Generate an array of 39 random bytes, each 0..255.

  2. Express your array as a Base64 string. This will be 52 characters long. There will be a Javascript Base64 encoder available on the internet.

  3. Chop off the last two characters (or the first two or the first and the last characters) of your string.

If you want to use the resulting random string in a browser, then you might need the browser-safe version of Base64: a-z A-Z 0-9 -_ instead: of a-z A-Z 0-9 +/

See RFC 4648 for details of Base64.

like image 24
rossum Avatar answered Oct 12 '22 12:10

rossum