Generate random password

Asked

Viewed 2,461 times

4

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

  • +1. There are also cases that I agree that, libraries for simple things, are unnecessary.

2 answers

6


There is a known and referred technique for example here who does it in a practical way:

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

In this case it generates 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: https://jsfiddle.net/wwrgmf7L/

  • I answered first! I’m more ninja!

  • 1

    @Wallacemaxters you answered with 2 lines and then edited with the rest of the content. I answered with the full answer and with jsFiddle... who is the ninja? :)

  • You’re the ninja, for fixing it :D+1

2

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

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

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

When 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

Browser other questions tagged

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