1

I want to create a random password generator in my ASP.NET C# web application.

I have created that but it is applicable only for the integer format. If I give any characters it shows the debugging error as "my input format is wrong".

But i want to enter both string and integer. For example my textbox field may be

dft-001

I want a random password for this value and also my length should be restricted to 8 digits or characters only.

My current code:

public static string CreateRandomPassword(int PasswordLength)
    {

        string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789-";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;

        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        }

        return new string(chars);
    }


protected void Button1_Click(object sender, EventArgs e)
    {
        userid.Text = "Your id is:     " + id.Text;
        if(id .Text!="")
        {

            string myInt = id.Text.ToString(); 
            password.Text = "Your password is: " + CreateRandomPassword(int.Parse(myInt)); 
        }
       }
2
  • Can you elaborate on what you mean by "I want a password for this value"? What relationship are you looking for between the user id and the random generated password? Your code reads like the password length would be set by the user id (!?) but then you say you only want 8 characters. Commented Mar 11, 2011 at 5:12
  • maybe you should try using the built-in generator msdn.microsoft.com/en-us/library/… Commented Aug 9, 2013 at 18:10

7 Answers 7

4

There are a few things you can do to correct this based on what you have stated in your requirements.

public static string CreateRandomPassword()  //If you are always going to want 8 characters then there is no need to pass a length argument
    {
        string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789-";
        Random randNum = new Random((int)DateTime.Now.Ticks);  //Don't forget to seed your random, or else it won't really be random
        char[] chars = new char[8];
        //again, no need to pass this a variable if you always want 8

        for (int i = 0; i < 8; i++)
        {
            chars[i] = _allowedChars[randNum.Next(_allowedChars.Length)];
            //No need to over complicate this, passing an integer value to Random.Next will "Return a nonnegative random number less than the specified maximum."
        }
        return new string(chars);
    }


protected void Button1_Click(object sender, EventArgs e)
    {
        userid.Text = "Your id is:     " + id.Text;
        if(id .Text!="")
        {
            password.Text = "Your password is: " + CreateRandomPassword(); 
        }
    }

If I've understood what you want to do correctly, then this should get you there.

Ref: MSDN Random.Next

Sign up to request clarification or add additional context in comments.

4 Comments

hi thank u very much for your code..i hope it wil works surely..but i got two errors do u have any idea on that.. Error 1: The best overloaded method match for 'System.Random.Random(int)' has some invalid arguments Error 2: Argument '1': cannot convert from 'long' to 'int'
hey i found that..code is now working...thanks a lot...am so happy
you need to add an int cast to the DateTime.Now.Ticks to pass the ticks as ints instead of long
There is also a typo in the var randNum and rndNum.
3

Shouldn't it be:

password.Text = CreateRandomPassword(int.Prase(myInt))

However, it is extremely strange that you are:

  1. Taking a user ID and converting it to string (I assume it is a number)
  2. Parsing that string back to a number
  3. Using this number as the length of your password

If your user ID is, say, 345678, you are creating a password which contains 345,678 characters! Please check your program logic.

2 Comments

Based on the reqs, CreateRandomPassword should take a constant value for PASSWORD_LENGTH and really shouldn't be based on the value of id.Text at all.
Most definitely a program logic error. Agree totally with your answer.
1

Check out the following link for password generator in asp.net

Password generator in ASP.NET

Comments

1

Depending on how fast the function is called multiple times the passwords will look similar if you use Random as a local variable (even when using Ticks as seeds). A solution for that is to use it as a static variable to ensure the result is truly random.

private static Random rand = new Random();

Another one is to use .net built-in solutions like Path.GetRandomFileName() which will give you results like

// w143kxnu.idj

Use only the first 8 chars and arbitrary change some chars to Upper().

Comments

0

Changing your Button_Click method to the following will give you a random password of 8 characters:

static const int PASSWORD_LENGTH = 8;
protected void Button1_Click(object sender, EventArgs e)
{
    userid.Text = "Your id is:     " + id.Text;
    if(id .Text!="")
    {

        string myInt = id.Text.ToString(); 
        password.Text = "Your password is: " + CreateRandomPassword(PASSWORD_LENGTH); 
    }
   }

Otherwise if id.Text contains any letters at all, it will fail which is most likely the error you are getting.

Comments

0

There is 2 problems. First id.Text.ToString() may contain some characters that make it fail to be parsed to int. "helo123" can't be parsed directly into int. This causes "input format is wrong". You should only do this if you are sure the ID contains only numbers.

Second, CreateRandomPassword(int.Parse(myInt)) creates a password that is as long as the value of the id. You should CreateRandomPassword(10) or CreateRandomPassword(randNum.Next(5, 12)). If your ID is 500, your password would be 500 characters long and if your field is supposed to be 32 characters, this could fail with "input format is wrong".

Comments

0

First we take 6 (any) random numbers from “0123456789”.

Then we create a function that returns the random number.

private string GetRandomNumber()
{
    var chars = "0123456789";
    var random = new Random();
    var result = new string(
        Enumerable.Repeat(chars, 6)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());
    return result;
}

Visit Here to View full example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.