-1

I put a button for the password generator program called generate. When this button is clicked, it puts the created password in the textbox, but when it creates the password by chance, sometimes it does not put the number in the password. I want to say that there must be a few numbers in each password by chance

This is the generate button code

private void Generate_Click(object sender, RoutedEventArgs e)
{
    {
        TextBox.SelectAll();
    }
    TextBox.Selection.Text = "";
    int len_1 = Convert.ToInt32(Label.Text);
    const string ssPass_1 = "__abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    const string ValidChar_1 = ssPass_1;
    StringBuilder result_1 = new StringBuilder();
    Random rand_1 = new Random();
    while (0 < len_1--)
    {
        result_1.Append(ValidChar_1[rand_1.Next(ValidChar_1.Length)]);
    }
    TextBox.Selection.Text = "mstsc\nnet user " + ssPass + " " + result_1.ToString() + "\nnet user " + ssPass + " " + result_1.ToString() + " /add\nnet localgroup Administrators " + ssPass + " /add\nnet localgroup \"Remote Desktop Users\"" + " /add " + ssPass + "\n";
}
  • Related : [Generating Random Passwords](https://stackoverflow.com/questions/54991/generating-random-passwords) – J... Feb 09 '22 at 18:22
  • Related : [Generating a strong password in C#?](https://stackoverflow.com/q/2266721/327083) – J... Feb 09 '22 at 18:23
  • This is not my answer I want a code that always puts a certain letter in the password – Mahdi Jamal Feb 09 '22 at 18:31

1 Answers1

0

Change your code to generate m1 numbers, m2 special characters and n - m1 - m2 letters into char array, than sort it using random to shuffle

string GeneratePasswordChars(int numCount, int specialCount, int letterCount)
{
    var special = new[] {'$', '_', '!'}; // add others
    var letters = new[] {'a', 'b', 'c'}; // add others
    var random = new Random();
    var nums = Enumerable.Range(0, numCount).Select(i => random.Next(10));
    var special = Enumerable.Range(0, specialCount).Select(i => special[random.Next(special.Length)];
    var letters = Enumerable.Range(0, letterCount).Select(i => letters[random.Next(letters.Length)];

    var chars = nums.Concat(special).Concat(letters).OrderBy(c => Guid.NewGuid());

    return string.Concat(chars);

}

P.S. Note that this is not cryptographic strong password...

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184