user2799983
user2799983

Reputation: 71

Creating a strong password with javascript

I have a function as below, which creates a strong password, however it does not always add a special character and a number or a capital letter to it, how do i ensure that it always has these requirements included in it.

The password requirements are that it has to

8 or more characters long and has to have a special character,a capital letter and a number included to it.

the function i have right now is displayed below

function GenPwd(nMinimumLength,bIsRequired,sNameoftheButton){
            var end=0;
            var index=0;
            var sPassCharactersWithoutSpeacil="!#$@*123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
            var sSpecialCharacters="!#$@*";
            var nSrngLen=sStrgStrAddOnChrs
            var sNumbers="123456789";
            var nMinimunLen=Math.round(nBaseLen/2);
            var PassWordDLength=Math.round((Math.random()*nMinLen)+nMinimumLength+nMinimumLength); //Make sure it is atleadt 8 characters long
            var Password="";
            var PasswordTemporary="";
            for(index = 1; index <= PassWordDLength; index++) {

                nCharacter = Math.round(Math.random()*65);

                 PasswordTemporary = sPassCharactersWithoutSpeacil.charAt(nCharacter);

                while (PWD.indexOf(PasswordTemporary) > -1) {
                    nCharacter = '';
                    nCharacter = Math.round(Math.random()*65);
                    PasswordTemporary = sPassCharactersWithoutSpeacil.charAt(nChar);
                }
                FinalPWD = Password + PasswordTemporary;
            }

this is what i have to use

function GenPwd(nBaseLen,bIsStrong,sBtnName){

        var end=0;
        var index=0;
        var sPassStr="!#$@*123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
        var sStrgStrAddOnChrs="!#$@*";
        var nSrngLen=sStrgStrAddOnChrs
        var sStrgStrAddOnNum="123456789";
        var nMinLen=Math.round(nBaseLen/2);
        var PWDLen=Math.round((Math.random()*nMinLen)+nBaseLen); 
        var PWD="";
        var PWDTmp="";
        //Generate the password
        for(index = 1; index <= PWDLen; index++) {

            nChar = Math.round(Math.random()*65);

            PWDTmp = sPassStr.charAt(nChar);

            while (PWD.indexOf(PWDTmp) > -1) {
                nChar = '';
                nChar = Math.round(Math.random()*65);
                PWDTmp = sPassStr.charAt(nChar);
            }
            PWD = PWD + PWDTmp;
        }

            document.getElementById("pwd").value=PWD;
        EnableBtn(sBtnName);
        return true;
    }

Upvotes: 4

Views: 757

Answers (1)

jfriend00
jfriend00

Reputation: 707406

You can create a function that ensures your pwd contains at least one of a specific set of chars:

function ensurePwdContains(pwd, regexListOfChars, listOfChars) {
    if (!regexListOfChars.test(pwd)) {
        // select random char from listOfChars
        var newChar = listOfChars.charAt(Math.floor(Math.random() * listOfChars.length));

        // insert it into the current pwd in a random location
        // must do +1 to include the location at the end of the string
        var pos = Math.floor(Math.random() * (pwd.length + 1));
        pwd = pwd.slice(0, pos) + newChar + pwd.slice(pos);
    }
    return pwd;
}

This function will test to see if the password contains at least one instance of the regex passed in. If not, it will select a random character from the listOfChars argument and then insert that into the existing password in a random location.

And, then you call this function at the end of your function for each of your two cases:

FinalPwd = ensurePwdContains(FinalPwd, /[!#\$@*]/, sSpecialCharacters);
FinalPwd = ensurePwdContains(FinalPwd, /[A-Z]/, "ABCDEFGHIJKLMNOPQRSTUWXYZ");

Demo: http://jsfiddle.net/jfriend00/ur9FL/


And, here's a cleaned up version of your overall implementation. You were referring to a number of variables in your function that either aren't defined in your post or aren't used in your function so I removed those (since I don't know what they are or how they're used). Here's a bit cleaner implementation:

function generatePwd(minLen) {
    // create a pwd that is between minLen and ((2 * minLen) + 2) long
    // don't repeat any characters
    // require at least one special char and one capital char
    function rand(max) {
        return Math.floor(Math.random() * max);
    }

    function ensurePwdContains(pwd, regexListOfChars, listOfChars) {
        if (!regexListOfChars.test(pwd)) {
            var newChar = listOfChars.charAt(rand(listOfChars.length));
            var pos = rand(pwd.length + 1);
            pwd = pwd.slice(0, pos) + newChar + pwd.slice(pos);
        }
        return pwd;
    }

    var legalChars = "!#$@*123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
    var specialChars = "!#$@*";
    var specialRegex = /[!#\$@*]/;
    var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var capsRegex = /[A-Z]/;
    var nums = "123456789";
    var numRegex = /[1-9]/;

    // make legalChars into an array of chars (easier to deal with)
    legalChars = legalChars.split("");
    var pwd = "", len = minLen + rand(minLen), index;

    // ensure len is not too long
    len = Math.min(legalChars.length, len);

    // now add chars to the pwd string until it is of the desired length
    while (pwd.length < len) {
        index = rand(legalChars.length);
        pwd += legalChars[index];
        // remove the char we just used
        legalChars.splice(index, 1);
    }
    // ensure we have at least one special character and one caps char and one 1-9
    pwd = ensurePwdContains(pwd, specialRegex, specialChars);
    pwd = ensurePwdContains(pwd, capsRegex, caps);
    pwd = ensurePwdContains(pwd, numRegex, nums);
    return pwd;    
}

And, a working demo that generates a whole bunch of passwords so you can see what type of variation you get: http://jsfiddle.net/jfriend00/7dReY/


To put the password into place, I'd suggest you make a second function that calls the first function to generate the password and puts it into the field of choice:

function putPasswordInPlace(pwdId, sBtnName) {
     var pwd = generatePwd(8);
     document.getElementById(pwdId).value = pwd;
     EnableButton(sBtnName);
}

Upvotes: 3

Related Questions