Generate random characters safely

5

Hello, I'm new to javascript and I'm using the following function to shuffle characters from a string into a password generator I'm trying to develop:

function shuffle(string) {
    "use strict";
    var parts = string.split('');
    for (var i = parts.length; i > 0;) {
        var random = parseInt(Math.random() * i);
        var temp = parts[--i];
        parts[i] = parts[random];
        parts[random] = temp;
    }
    return parts.join('');
}

But as I was informed, using Math.random() is not very secure for this purpose. I would like to know how I can tailor my role then using window.crypto.getRandomValues() who told me to be more secure.

Thanks for any help!

    
asked by anonymous 29.03.2017 / 23:05

1 answer

2

Searching a little more I found the solution. Here is the code:

function generateRandomNumber(){
    "use strict";

    // se o browser tiver suporte à getRandomValues()
    if (Uint32Array && window.crypto && window.crypto.getRandomValues) { 
        var numbers = new Uint32Array(1);
        window.crypto.getRandomValues(numbers);
        return numbers[0] * Math.pow(2,-32);

    // caso não tenha, é utilizado Math.random
    } else {
        return Math.random();
    }
}

function shuffle(string) {
    "use strict";
    var parts = string.split('');

    for (var i = parts.length; i > 0;) {
        var random = parseInt(generateRandomNumber() * i); // aqui é chamada a função que gera o número aleatório
        var temp = parts[--i];
        parts[i] = parts[random];
        parts[random] = temp;
    }

    return parts.join('');
}

Reference: link

    
30.03.2017 / 01:16