user20168338
user20168338

Reputation:

Generate random password for one-time password verification

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?

Upvotes: 0

Views: 3307

Answers (4)

Kris
Kris

Reputation: 557

Since Random is not cryptographically safe and Microsoft recommends using RandomNumberGenerator, you can do following to get a cryptographically strong random PIN number:

Method:

static int GeneratePIN(int start, int stop)
{
    return RandomNumberGenerator.GetInt32(start, stop);
}

Usage:

Console.WriteLine("Random PIN: {0}", GeneratePIN(100000, 1000000));

Upvotes: 2

Hossein Sabziani
Hossein Sabziani

Reputation: 3495

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

Upvotes: 0

Denis Schaf
Denis Schaf

Reputation: 2727

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;
}

Upvotes: 2

freifede
freifede

Reputation: 91

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;
}

Upvotes: 2

Related Questions