Home » Javascript » javascript password generator

javascript password generator

Posted by: admin February 12, 2018 Leave a comment

Questions:

What would be the best approach to creating a 8 character random password containing a-z, A-Z and 0-9?

Absolutely no security issues, this is merely for prototyping, I just want data that looks realistic.

I was thinking a for (0 to 7) Math.random to produce ASCII codes and convert them to characters. Do you have any other suggestions?

Answers:

I would probably use something like this:

function generatePassword() {
    var length = 8,
        charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}

That can then be extended to have the length and charset passed by a parameter.

Questions:
Answers:
        function password_generator( len ) {
            var length = (len)?(len):(10);
            var string = "abcdefghijklmnopqrstuvwxyz"; //to upper 
            var numeric = '0123456789';
            var punctuation = '!@#$%^&*()_+~`|}{[]\:;?><,./-=';
            var password = "";
            var character = "";
            var crunch = true;
            while( password.length<length ) {
                entity1 = Math.ceil(string.length * Math.random()*Math.random());
                entity2 = Math.ceil(numeric.length * Math.random()*Math.random());
                entity3 = Math.ceil(punctuation.length * Math.random()*Math.random());
                hold = string.charAt( entity1 );
                hold = (entity1%2==0)?(hold.toUpperCase()):(hold);
                character += hold;
                character += numeric.charAt( entity2 );
                character += punctuation.charAt( entity3 );
                password = character;
            }
            return password;
        }

        console.log( password_generator() );

This generates a little more robust password that should pass any password strength test. eg; f1&d2?I4(h1&, C1^y1)j1@G2#, j2{h6%b5@R2)

Questions:
Answers:

This is the quickest and easiest way I know of:

Math.random().toString(36).slice(2)

The idea is to cast a random number (in the range 0..1) to a base36 string (lowercase a-z plus 0-9) and remove the leading zero and decimal point.

Please note that all passwords that is pseudo-generated have some form of vulnerability. However, I would say it is good enough for all normal use-cases. Furthermore, the theoretical length if this password is not guaranteed. It is 16 characters maximum and 0 characters minimum. When run in a loop 1 million times its average length is 15.67 characters with a minimum length of 5. However if you join two of these passwords together, you will get a maximum length of 32 characters, with an average length of 31.33 chars and a minimum length of 20.

Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)

Personally I use this as a chrome bookmarklet in my browser bookmarks bar to speedily generate passwords:

javascript:(
    function(){
        prompt('Here is your shiny new password:', 
            Math.random().toString(36).slice(2) + 
            Math.random().toString(36).slice(2)
        );
    }
)();

Questions:
Answers:
function generatePass(plength){

    var keylistalpha="abcdefghijklmnopqrstuvwxyz";
    var keylistint="123456789";
    var keylistspec="!@#_";
    var temp='';
    var len = plength/2;
    var len = len - 1;
    var lenspec = plength-len-len;

    for (i=0;i<len;i++)
        temp+=keylistalpha.charAt(Math.floor(Math.random()*keylistalpha.length));

    for (i=0;i<lenspec;i++)
        temp+=keylistspec.charAt(Math.floor(Math.random()*keylistspec.length));

    for (i=0;i<len;i++)
        temp+=keylistint.charAt(Math.floor(Math.random()*keylistint.length));

        temp=temp.split('').sort(function(){return 0.5-Math.random()}).join('');

    return temp;
}

Questions:
Answers:

This is my function for generating a 8-character crypto-random password:

function generatePassword() {
    var buf = new Uint8Array(6);
    window.crypto.getRandomValues(buf);
    return btoa(String.fromCharCode.apply(null, buf));
}

What it does: Retrieves 6 crypto-random 8-bit integers and encodes them with Base64.

Since the result is in the Base64 character set the generated password may consist of AZ, az, 09, + and /.

Questions:
Answers:

If you have lodash >= 4.0 in place there is a more elegant way of doing it

var chars = 'abcdefghkmnpqrstuvwxyz23456789';
function generatePassword(length) {
  return _.sampleSize(chars, length).join('');
}

Questions:
Answers:

Gumbo’s solution does not work. This one does though:

function makePasswd() {
  var passwd = '';
  var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  for (i=1;i<8;i++) {
    var c = Math.floor(Math.random()*chars.length + 1);
    passwd += chars.charAt(c)
  }

  return passwd;

}

Questions:
Answers:

This will produce a realistic password if having characters [\]^_ is fine. Requires lodash and es7

String.fromCodePoint(...range(8).map(() => Math.floor(Math.random() * 57) + 0x41))

and here’s without lodash

String.fromCodePoint(...Array.from({length: 8}, () => Math.floor(Math.random() * 57) + 65))

Questions:
Answers:

Here’s a free, configurable Javascript class generating random passwords: Javascript Random Password Generator.

Examples

Password consisting of Lower case + upper case + numbers, 8 characters long:

var randomPassword = new RandomPassword();
document.write(randomPassword.create());

Password consisting of Lower case + upper case + numbers, 20 characters long:

var randomPassword = new RandomPassword();
document.write(randomPassword.create(20));

Password consisting of Lower case + upper case + numbers + symbols, 20 characters long:

var randomPassword = new RandomPassword();
document.write(randomPassword.create(20,randomPassword.chrLower+randomPassword.chrUpper+randomPassword.chrNumbers+randomPassword.chrSymbols));  

Questions:
Answers:

even shorter:

Array.apply(null, Array(8)).map(function() { 
    var c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    return c.charAt(Math.random() * c.length);
}).join('');

or as function:

function generatePassword(length, charSet) {
    charSet = charSet ? charSet : 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789^°!"§$%&/()=?`*+~\'#,;.:-_';
    return Array.apply(null, Array(length || 10)).map(function() { 
        return charSet.charAt(Math.random() * charSet.length);
    }).join(''); 
}

Questions:
Answers:

here is a simply smart code :

function generate(l) {
    if (typeof l==='undefined'){var l=8;}
    /* c : alphanumeric character string */
    var c='abcdefghijknopqrstuvwxyzACDEFGHJKLMNPQRSTUVWXYZ12345679',
    n=c.length,
    /* p : special character string */
    p='!@#$+-*&_',
    o=p.length,
    r='',
    n=c.length,
    /* s : determinate the position of the special character */
    s=Math.floor(Math.random() * (p.length-1));

    for(var i=0; i<l; ++i){
        if(s == i){
            /* special charact insertion (random position s) */
            r += p.charAt(Math.floor(Math.random() * o));
        }else{
            /* alphanumeric insertion */
            r += c.charAt(Math.floor(Math.random() * n));
        }
    }
    return r;
}

Simply call generate(), and it do key containing one special character (!@#$+-*&_) for security.

Possible results : WJGUk$Ey, gaV7#fF7, ty_T55DD, YtrQMWveZqYyYKo_

There is more details and example in my website : https://www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-en-javascript/

Questions:
Answers:

Randomly assigns Alpha, Numeric, Caps and Special per character then validates the password. If it doesn’t contain each of the above, randomly assigns a new character from the missing element to a random existing character then recursively validates until a password is formed:

function createPassword(length) {
    var alpha = "abcdefghijklmnopqrstuvwxyz";
    var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var numeric = "0123456789";
    var special = "!$^&*-=+_?";

    var options = [alpha, caps, numeric, special];

    var password = "";
    var passwordArray = Array(length);

    for (i = 0; i < length; i++) {
        var currentOption = options[Math.floor(Math.random() * options.length)];
        var randomChar = currentOption.charAt(Math.floor(Math.random() * currentOption.length));
        password += randomChar;
        passwordArray.push(randomChar);
    }

    checkPassword();

    function checkPassword() {
        var missingValueArray = [];
        var containsAll = true;

        options.forEach(function (e, i, a) {
            var hasValue = false;
            passwordArray.forEach(function (e1, i1, a1) {
                if (e.indexOf(e1) > -1) {
                    hasValue = true;
                }
            });

            if (!hasValue) {
                missingValueArray = a;
                containsAll = false;
            }
        });

        if (!containsAll) {
            passwordArray[Math.floor(Math.random() * passwordArray.length)] = missingValueArray.charAt(Math.floor(Math.random() * missingValueArray.length));
            password = "";
            passwordArray.forEach(function (e, i, a) {
                password += e;
            });
            checkPassword();
        }
    }

    return password;
}

Questions:
Answers:

Here’s another approach based off Stephan Hoyer’s solution

getRandomString (length) {
  var chars = 'abcdefghkmnpqrstuvwxyz23456789';
  return times(length, () => sample(chars)).join('');
}

Questions:
Answers:

Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number

function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
    let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
        A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
        a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
        zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
        specials = chars.replace(/\w/g, '')
    if (minSpecial < 0) chars = zero2nine + A2Z + a2z
    if (minNumber < 0) chars = chars.replace(zero2nine, '')
    let minRequired = minSpecial + minUpper + minLower + minNumber
    let rs = [].concat(
        Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
        Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
        Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
        Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
        Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
    )
    return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7

Questions:
Answers:
var createPassword = function() {
  var passAt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  var passArray = Array.from({length: 15})

  return passArray.map(function(_, index) { 
    return index % 4 == 3 ? '-' : passAt.charAt(Math.random() * passAt.length)
  }).join('')
}

result like:

L5X-La0-bN0-UQO
9eW-svG-OdS-8Xf
ick-u73-2s0-TMX
5ri-PRP-MNO-Z1j