Here is the code: (passwordLengthBox is a NumericUpDown Box, r and k are random numbers)
private void generateButton_Click(object sender, EventArgs e)
{
int r, k;
int passwordLength = (Int32)passwordLengthBox.Value;
string password = "";
char[] upperCase = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
char[] lowerCase = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
int[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
Random rRandom = new Random();
for (int i = 0; i < passwordLength; i++)
{
r = rRandom.Next(3);
if (r == 0)
{
k = rRandom.Next(0, 25);
password += upperCase[k];
}
else if (r == 1)
{
k = rRandom.Next(0, 25);
password += lowerCase[k];
}
else if (r == 2)
{
k = rRandom.Next(0, 9);
password += numbers[k];
}
}
textBox.Text = password;
}
What this program does is to create a random password with letters (both upper case and lower case) and numbers at the length that I choose. The problem is that the program does not make the password length as I chose.
For example: if I type 5 in the NumericUpDown Box (passwordLengthBox) that sets the Password Length sometimes its giving me passwords that are 5 chars long and sometime 6/7/8 chars long passwords.
What is my mistake?
You could try this little method instead instead.
The only difference with this is that it will use alphanumeric chars too, for example it may generate strings like
f6Dx3$5d£4hG7
take a look at www.asciitable.com and work out the character range you want to use.
For Nathan, here is another way you could do it, if you know exactly which characters you want...
Here My Complete Function to generate random password with desired length (thanks to Viacheslav Smityukh)
Problem is here:
With that declaration every time a number is appended into
password
it is taken as ASCII number, not a real value. So you're adding integers from 48 to 57, what makes result string longer then expected.e.g. when
6
is generated as a random number, you're appending something like:((int)'6').ToString()
into yourpassword
variable, what actually adds54
instead of6
.Declare that array as
char[]
and it will works fine.Here is a slight improvement on the answer from series0ne. That answer gave a password with the same character. (e.g. %%%%%)
You can try the following code: