How to make a keygen that writes "-" every four letters in C #

I have a quick question. I have a keygen to generate random passwords for my application. It generates uppercase letters and numbers, but I want it to be like in some programs that format their code, like this xxxx-xxxx-xxxx . still my code is this

 Random random = new Random(0); private void button1_Click(object sender, EventArgs e) { textBox1.Text = getrandomcode(); } public string getrandomcode() { char[] tokens = {'0', '1', '2', '3', '4', '5', '7', '8', '9', '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[] codeArray = new char[24]; for (int i = 0; i < 24; i++) { int index = random.Next(tokens.Length - 1); codeArray[i] = tokens[index]; } return new String(codeArray); } 

Something simple is not complicated, so I hope there is a way to implement a “-” for this code.

early!

+4
source share
3 answers

Try the following:

 for (int i = 0; i < 24; i++) { if (i % 5 == 4) { codeArray[i] = '-'; } else { int index = random.Next(tokens.Length - 1); codeArray[i] = tokens[index]; } } 

If you want your password to have 24 characters without a dash, change the value of 24 to 29.

But I must also tell you that using a random function spent on 0 is not a very safe way to generate passwords. If the application is stopped and restarted, it will generate the same set of passwords the second time it was done the first time. It is better not to pass the initialization argument, in which case it will use the time to generate the random number generator.

If these passwords are used for something important or something that the whole world (or both) can access, then even this is not random enough to ensure security. You should look at cryptographic random number generators such as System.Security.Cryptography.RNGCryptoServiceProvider

0
source

Include this in the 'for' loop:

 if (i % 5 == 4) { codeArray[i] = '-'; } else { int index = random.Next(tokens.Length - 1); codeArray[i] = tokens[index]; } 
+6
source

Or, if you want to use regex, try the following:

 textBox1.Text = Regex.Replace(getrandomcode(), @"(\w{4})(\w{4})(\w{4})(\w{4})(\w{4})", "$1-$2-$3-$4-$5") 
+3
source

All Articles