Generate random password

4

Hello, I noticed that there are generate-password libraries and password-generator for random password generation. But importing a library just for this might not be a good idea. Is there any way in the node itself to do this?

    
asked by anonymous 10.08.2016 / 14:18

2 answers

6

There is a well-known known technique that does this in a practical way:

function gerarPassword() {
    return Math.random().toString(36).slice(-10);
}

In this case, you generate a password by converting to base36 and then using only the last 10 characters.

An example application and 10 tests would look like this:

var testes = Array.apply(null, Array(10)).map(gerarPassword);
console.log(JSON.stringify(testes));
// dá 
[
    "ywnfa5g66r",
    "0go0d1v2t9",
    "s52wukgldi",
    "t9c8hvvx6r",
    "z5ygvw8kt9",
    "uazwcanhfr",
    "g91b5wxw29",
    "lbn4hg2e29",
    "ey101thuxr",
    "eo62fswcdi"
]

jsFiddle: link

    
10.08.2016 / 14:24
2

I would use Math.random combined with toString(36)

Math.random().toString(36).substring(0, 7)

Parameter 36 passed to toString , must be an integer between 2 and 36 specifying the basis used to represent numeric values.

Using substring we are limiting the number of characters that will be returned. That is, I generated a random password with a maximum of 7 characters.

See an example on IDEONE

    
10.08.2016 / 14:21