Generate random characters securely

Asked

Viewed 701 times

5

Hello, I’m new to javascript and am using the following function to shuffle characters from a string in a password generator that 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 told, use Math.random() is not very safe for that purpose. I would like to know how I can adapt my function then using window.crypto.getRandomValues() who informed me to be safer.

Grateful for any help!

1 answer

3


Searching a little more I ended up finding the solution. Follows 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: https://stackoverflow.com/questions/13694626/generating-random-numbers-0-to-1-with-crypto-generatevalues

Browser other questions tagged

You are not signed in. Login or sign up in order to post.