-8

I was able to do this in C# but can't translate it to Javascript. I found this post "Generate random password string with requirements in javascript" but I can't customize this to my requirements:

A password should be at least 8 chracters in length and maximum of 13 characters and must contain at least one character from each of the following string collections:

string specialCharacters = "~!@#$%^&*()_+=-|\\}]{[\"':;?/>.<,";
string numbers = "0123456789";
string smallLetters = "abcdefghijklmnopqrstuvwxyz";
string capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Can you please help? Many thanks!

EDIT:

Here's my code in C#. Sorry, it's a bit lengthy:

private string CreateRandomPassword(int passwordLength)
        {
            string specialCharacters = "~!@#$%^&*()_+=-|\\}]{[\"':;?/>.<,";
            string numbers = "0123456789";
            string smallLetters = "abcdefghijklmnopqrstuvwxyz";
            string capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string allowedChars = "";

            char[] chars = new char[passwordLength];
            string password = String.Empty;
            Random rd = new Random();

            int ctr = 0;
            int prop = 4;

            if(!_password.ContainsSpecialCharacters && !_password.ContainsNumbers && !_password.ContainsSmallLetters && !_password.ContainsCapitalLetters)
                return String.Empty;

            string sc = "";
            string num = "";
            string sl = "";
            string cl = "";

            if(_password.ContainsSpecialCharacters)
            {
                // Get a special character randomly
                rd = new Random();
                sc = specialCharacters[rd.Next(0, specialCharacters.Length)].ToString();
                allowedChars += specialCharacters;
            }
            else
            {
                prop--;
            }

            if(_password.ContainsNumbers)
            {
                // Get a random number randomly
                rd = new Random();
                num = numbers[rd.Next(0, numbers.Length)].ToString();
                allowedChars += numbers;
            }
            else
            {
                prop--;
            }

            if(_password.ContainsSmallLetters)
            {
                // Get a small letter randomly
                rd = new Random();
                sl = smallLetters[rd.Next(0, smallLetters.Length)].ToString();
                allowedChars += smallLetters;
            }
            else
            {
                prop--;
            }

            if(_password.ContainsCapitalLetters)
            {
                // Get a capital letter randomly
                rd = new Random();
                cl = capitalLetters[rd.Next(0, capitalLetters.Length)].ToString();
                allowedChars += capitalLetters;

            }
            else
            {
                prop--;
            }

            for (; ctr < passwordLength - prop; ctr++)
                password += allowedChars[rd.Next(0, allowedChars.Length)];


            return password + sc + num + sl + cl;
        }
Community
  • 1
  • 1
yonan2236
  • 13,371
  • 33
  • 95
  • 141
  • 2
    What help do you want? What exactly is your problem? What have you tried? Why doesn't it work? Will this do: "~0aAAAAA" ? –  May 16 '13 at 12:39
  • I can't translate my C# code to Javascript – yonan2236 May 16 '13 at 12:39
  • So what is your set of all allowed characters? Is it just all the characters from those four sets? – Matt Burland May 16 '13 at 12:39
  • exact duplicate of [generate a secure password in javascript](http://stackoverflow.com/questions/12635652/generate-a-secure-password-in-javascript) (see also the questions linked there) – Bergi May 16 '13 at 12:41
  • also, if it needs to be random, how random?http://stackoverflow.com/questions/5651789/is-math-random-cryptographically-secure – penguat May 16 '13 at 12:41
  • 1
    @yonan2236: The code is pretty straightforward, just as your C# code was. What have you tried at translating, where do you have a problem? – Bergi May 16 '13 at 12:50
  • have a look at http://jsfiddle.net/arunpjohny/Yxe9c/3/ – Arun P Johny May 16 '13 at 12:51
  • I just lost 5 points of reputations for this question : ). I don't care actually for the points, just wondering why they down voted it. Does my question not making any sense at all? Maybe they should also take into consideration that this is a website visible to whole world, and not all users can't express themselves as good as native english speakers. I'm just trying to learn javascript by taking some examples. Anyway, many thanks for those who answered and tried to understand my question rather by judging it : ) – yonan2236 May 16 '13 at 13:02
  • 1
    That this site is visible to the world was considered when it was created and the FAQ constructed. Poor English is tolerated, but "I want this code from this site here, only I want it converted into this other language - please help" is not. –  May 16 '13 at 14:32

3 Answers3

0

To check whether it contains a character from either string, you can use Javascript Regular Expressions. Just match your password candidate to those characters as per the link. You are going to try for four matches. The length of the string, you can check in its length property.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
  • 1
    The question is not about validating a password (for which a regular expression maybe useful), but about **generating a new random password**. – Mischa May 16 '13 at 12:44
0

Here is what I came up with.

Just run it in the JavaScript console.

(function() {
    var passwd, classTypes, classCount, len, chars, classIndex, charIndex;
    do {
        passwd = "";
        classTypes = [];
        classCount = 0;
        len = Math.round(Math.random() * 5 + 8);
        chars = ["~!@#$%^&*()_+=-|\\}]{[\"':;?/>.<,", "0123456789",
            "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
        while (passwd.length < len) {
            classIndex = Math.round(Math.random() * 3);
            classTypes[classIndex] = true;
            charIndex = Math.round(Math.random()
                * (chars[classIndex].length - 1));
            passwd += chars[classIndex].charAt(charIndex);
        }
        console.log(JSON.stringify(classTypes));
        classCount = classTypes.filter(function(value, index, object) {
            return value === true;
        }).length;
        console.log("classCount = " + classCount);
        console.log("passwd.length = " + passwd.length);
    } while (classCount < 4);
    console.log("generated pasword is \n" + passwd + "\n");
    console.log("but see http://xkcd.com/936/ for a better approach to paswords");
})();
stackunderflow
  • 953
  • 7
  • 17
-1

Try

var specialCharacters = "~!@#$%^&*()_+=-|\\}]{[\"':;?/>.<,";
var numbers = "0123456789";
var smallLetters = "abcdefghijklmnopqrstuvwxyz";
var capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

var srcs = [specialCharacters, numbers, smallLetters, capitalLetters];

function getRandomChar(string){
    var pos = Math.floor(Math.random() * string.length);
    return string.charAt(pos);
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}
function generate(){
    var len = 8 + Math.floor(Math.random() * 5);

    var array = [];
    array.push(getRandomChar(specialCharacters));
    array.push(getRandomChar(numbers));
    array.push(getRandomChar(smallLetters));
    array.push(getRandomChar(capitalLetters));

    for(var i = 4; i < len; i++){
        var pos = Math.floor(Math.random() * srcs.length);
        array.push(getRandomChar(srcs[pos]));
    }
    return shuffle(array).join('')
}

for(var i = 0; i < 10; i++){
    console.log(generate())
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    Very nice of you to do his work for him, but answering these kind of questions in this way (just a block of code without any explanation) stimulates him asking more bad questions like this. – Mischa May 16 '13 at 13:00
  • @Mischa I did it because I found it a little funny and to test my self, if OP want to learn he/she can learn by reading it or by asking any doubts in the comments – Arun P Johny May 16 '13 at 13:03
  • I just lost 5 points of reputations for this question : ). I don't care actually for the points, just wondering why they down voted it. Does my question not making any sense at all? Maybe they should also take into consideration that this is a website visible to whole world, and not all users can't express themselves as good as native english speakers. I'm just trying to learn javascript by taking some examples. Anyway, many thanks for those who answered and tried to understand my question rather by judging it : ) – yonan2236 May 16 '13 at 13:04
  • 4
    @yonan2236: your question makes sense, but it doesn't show any effort. Generally people here expect you to put in some effort before asking. Show what you tried in Javascript and where you're stuck and ask a specific question about that. This is a bad question because you're just pasting a big piece of code and hope someone will translate it for you. Arun unfortunately did it for you, thereby rewarding your bad behavior. It's lazy and disrespectful to answerers. Please show some effort and ask specific questions when you are stuck. – Mischa May 16 '13 at 13:10
  • Well, I was able to initialize the variables in Javascript. I'm new to Javascript and don't know where to start. I think that's why it's called a "language" because someone has to teach you about it. You can be fluent in one language but you need some considerable time to learn another. Just a thought.... – yonan2236 May 16 '13 at 13:26
  • 1
    @yonan2236, this isn't the place to learn a language. For that there are tutorials, books, programming classes and screencasts. If -- while learning -- you run into something you don't understand, you can ask about it here. Don't you agree it's a bit rude to just dump a big chunk of code and expect someone to translate it for you? Just a thought... – Mischa May 16 '13 at 14:10