5

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.

Martijn19
  • 189
  • 4
  • 13
  • [].slice.call( crypto.getRandomValues(new Uint32Array(999))).map(function(a,b){return a.toString(36);}).join("").replace(/\W/g,"").match(/\w{50}/g).slice(1,-1) – dandavis Jun 13 '14 at 18:21
  • Thanks for your comment. But I have honestly no idea what it means :( – Martijn19 Jun 13 '14 at 18:31

2 Answers2

5

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.substring(0, length);
      callback(randomBase64String);
      clearInterval(checkReadyness);
    }
  }, 1);
}

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

halbgut
  • 2,368
  • 17
  • 22
1
  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.

rossum
  • 15,344
  • 1
  • 24
  • 38