Home > Mobile >  Generate random password for one-time password verification
Generate random password for one-time password verification

Time:11-10

I had to generate random password for temporary entry/login purpose in C#. Now I need to only send 6 digits but no more characters, or special characters. New to the C# world. Hence, I am providing what I have so far.

helper.cs

public static string GenerateRandomPassword()
{
    int numsLength = 6;
    
    const string nums = "0123456789";
    StringBuilder sb = new StringBuilder();
    Random rnd = new Random();

    for (int i = 0; i < charLength; i  )
    {
        int index = rnd.Next(chars.Length);
        sb.Append(chars[index]);
    }
    int numindex = rnd.Next(nums.Length);
    sb.Append(nums[numindex]);

    return sb.ToString();
}

I think my logic is still not right. I know that I should not use String Builder since I only want to send digits. Can anyone help me and figure out my mistake by editing the above codes?

CodePudding user response:

Try to generate random numbers directly and convert them to a string, rather than to select random characters from an existing string, this will simplify your code

Random rnd = new Random();

public static string GenerateRandomPassword()
{
    int numsLength = 6;
    string sixDigitString = "";
    for (int i = 0; i < charLength; i  )
    {
        //this takes the existing string and adds a random number to it. Do this as many times as you need to
        sixDigitString  = rnd.Next(0,9).ToString();
    }
    return sixDigitString;
}

CodePudding user response:

You could also just concatenate strings and do something like:

public static string GenerateRandomPassword()
{
    int numsLength = 6;

    const string nums = "0123456789";
    string tempPass = string.Empty;
    Random rnd = new Random();

    for (int i = 1; i <= numsLength; i  )
    {
        int index = rnd.Next(nums.Length);
        tempPass  = nums[index];
    }

    return tempPass;
}

CodePudding user response:

  Random rnd = new Random();
  String passSixDigit = rnd.Next(0, 999999).ToString("000000");
  • Related