C # random password generator

Here is the code: (passwordLengthBox is 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 in upper case and lower case) and the length numbers 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), which sometimes sets the password length, it gives me 5-character passwords and sometimes 6/7/8 character long passwords.

What's my mistake?

+6
c # random encoding ascii numericupdown
source share
5 answers

The problem is here:

 int[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; 

With this declaration, every time a number is added to the password , it is taken as an ASCII number, not a real value. This way you add integers from 48 to 57, which makes the result longer than expected.

eg. when 6 generated as a random number, you add something like: ((int)'6').ToString() in your password variable, which actually adds 54 instead of 6 .

Declare this array as char[] and it will work fine.

+14
source share

Instead, you can try this little method.

 public static string Random(int length) { try { byte[] result = new byte[length]; for (int index = 0; index < length; index++) { result[index] = (byte)new Random().Next(33, 126); } return System.Text.Encoding.ASCII.GetString(result); } catch (Exception ex) { throw new Exception(ex.Message, ex); } } 

The only difference is that it will use alphanumeric characters, for example, it can generate strings like f6Dx3$5d£4hG7

take a look at www.asciitable.com and design the character range you want to use.

For Nathan , here is another way to do this if you know exactly which characters you want ...

 public static string Random(int length) { string allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; return new string(allowed .OrderBy(o => Guid.NewGuid()) .Take(length) .ToArray()); } 
+5
source share

Here is a slight improvement in the answer from series0ne . This answer gave a password with the same character. (eg, %%%%%)

  var random = new Random((int) DateTime.Now.Ticks); try { var result = new byte[length]; for (var index = 0; index < length; index++) { result[index] = (byte) random.Next(33, 126); } return System.Text.Encoding.ASCII.GetString(result); } catch (Exception ex) { throw new Exception(ex.Message, ex); } 
+3
source share

Here is My complete function for generating a random password with the required length (thanks to Vyacheslav Smityuh)

  private String GeneratePassword(int genlen = 21, bool usenumbers = true, bool uselowalphabets = true, bool usehighalphabets = true, bool usesymbols = true) { var upperCase = new char[] { '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' }; var lowerCase = new char[] { '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' }; var numerals = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; var symbols = new char[] { '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '{', '[', '}', ']', '-', '_', '=', '+', ':', ';', '|', '/', '?', ',', '<', '.', '>' }; char[] total = (new char[0]) .Concat(usehighalphabets ? upperCase : new char[0]) .Concat(uselowalphabets ? lowerCase : new char[0]) .Concat(usenumbers ? numerals : new char[0]) .Concat(usesymbols ? symbols : new char[0]) .ToArray(); var rnd = new Random(); var chars = Enumerable .Repeat<int>(0, genlen) .Select(i => total[rnd.Next(total.Length)]) .ToArray(); return new string(chars); } 
+3
source share

You can try the following code:

 var numberOfChars = 6; var upperCase = new char[] { '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' }; var lowerCase = new char[] { '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' }; var numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; var rnd = new Random(); var total = upperCase .Concat(lowerCase) .Concat(numbers) .ToArray(); var chars = Enumerable .Repeat<int>(0, numberOfChars) .Select(i => total[rnd.Next(total.Length)]) .ToArray(); var result = new string(chars); 
0
source share

All Articles