开发者

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 app. It generates capital letters and numbers but I want it to be like in some programs that formats their code like this xxxx-xxxx-xxxx. so far my code is this

Random random = new Random(0);

private void bu开发者_高级运维tton1_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);
}

Its something simple not to complex so I hope there is a way to implement the "-" to this code.

thanks in advance!


Include this in your 'for' loop :

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


Or if you want to use regular expression, try this:

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


Try this:

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 non-dash characters, change the 24 to 29.

But I also have to tell you that using a random function seeded with 0 is not a very secure way to generate passwords. If the application is stopped and restarted, it will generate the same set of passwords the second time that it did the first time. It is better to not pass an initialization argument in which case it will use the time to seed the random number generator.

If these passwords are going to be used for something important or something which the whole world can access (or both), then even this isn't really random enough to be secure. You should look at cryptographic random number generators like System.Security.Cryptography.RNGCryptoServiceProvider

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜