In this article, you’ll learn how to generate random numbers and random strings and combine them to create a random password using C# and .NET Core.
A random password is a combination of numbers, characters, and special characters. We can generate a random password by combining random numbers and strings.
Random class constructors have two overloaded forms. It takes no value or it takes a seed value.
The Random class has three public methods – NextDouble, NextBytes, and Next. The NextBytes returns a variety of bytes filled with random numbers, the Next method returns a random number, and NextDouble returns a random number in the range of 0.0 and 1.0.
Generate a random number
//The following code in Steps 1 returns a random number.
// Generate a random number
Random random = new Random();
// Any random integer
int num = random.Next();
Steps 1.
Generate a random string
The following example, in Steps 2 generates a random string with a given size. The second value of the RandomString method use for setting if the string is a lowercase string.
// Generate the random string with a given size and case.
// If the second parameter is true, the return string is lowercase
public string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
Steps 2.
Creating a random password
A random password can basically be a combination of a random string and a random number. To make it more progressively unpredictable, you can even include special characters and mix them up.
we’ll combine the two methods – RandomString and RandomNumber.
The following example, in Steps 3 generates a password of length 10 with first 4 letters lowercase. next 4 letters numbers, and the last 2 letters as uppercase.
// Generate the random password of a given length (optional)
public string RandomPassword(int size = 0)
{
StringBuilder builder = new StringBuilder();
builder.Append(RandomString(4, true));
builder.Append(RandomNumber(1000, 9999));
builder.Append(RandomString(2, false));
return builder.ToString();
}
Steps 3.
The majority of the above functionality listed here in Steps 4. Create a .NET Core Console app in Visual Studio and utilize this code.
using System;
using System.Text;
class RandomNumberSample
{
static void Main(string[] args)
{
// Generate a random number
Random random = new Random();
// Any random integer
int num = random.Next();
// A random number below 100
int randomLessThan100 = random.Next(100);
Console.WriteLine(randomLessThan100);
// A random number within a range
int randomBetween100And500 = random.Next(100, 500);
Console.WriteLine(randomBetween100And500);
// Use other methods
RandomNumberGenerator generator = new RandomNumberGenerator();
int rand = generator.RandomNumber(5, 100);
Console.WriteLine($"Random number between 5 and 100 is {rand}");
string str = generator.RandomString(10, false);
Console.WriteLine($"Random string of 10 chars is {str}");
string pass = generator.RandomPassword();
Console.WriteLine($"Random password {pass}");
Console.ReadKey();
}
}
public class RandomNumberGenerator
{
// Generate a random number between two numbers
public int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
// Generate the random string with a given size and case.
// If second parameter is true, then return string is lowercase
public string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
// Generate a random password of a given length (optional)
public string RandomPassword(int size = 0)
{
StringBuilder builder = new StringBuilder();
builder.Append(RandomString(4, true));
builder.Append(RandomNumber(1000, 9999));
builder.Append(RandomString(2, false));
return builder.ToString();
}
}
Steps 4.
The random password and random string look like Figure 1. Generate A Random Password In C# And .NET Core
Figure 1.
Random password with given characters
Now, if you want to create a password that allows some specific characters only. The following example in Steps 5 has a string of valid characters. The code utilizes this string to pick one character at a time for the password and stops at the given length. The default length of the password is 15.
private static string CreateRandomPassword(int length = 15)
{
// Create a string of characters, numbers, special characters that allowed in the password
string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";
Random random = new Random();
// Select one random character at a time from the string
// and create an array of chars
char[] chars = new char[length];
for (int i = 0; i < length; i++)
{
chars[i] = validChars[random.Next(0, validChars.Length)];
}
return new string(chars);
}
Steps 5.
You can also change validChars string with the characters you allowed in the password.
Steps 6 is the complete program written in .NET Core.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(CreateRandomPassword());
Console.WriteLine(CreateRandomPassword(10));
Console.WriteLine(CreateRandomPassword(30));
Console.WriteLine(CreateRandomPasswordWithRandomLength());
Console.ReadKey();
}
// Default size of random password is 15
private static string CreateRandomPassword(int length = 15)
{
// Create a string of characters, numbers, special characters that allowed in the password
string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";
Random random = new Random();
// Select one random character at a time from the string
// and create an array of chars
char[] chars = new char[length];
for (int i = 0; i < length; i++)
{
chars[i] = validChars[random.Next(0, validChars.Length)];
}
return new string(chars);
}
private static string CreateRandomPasswordWithRandomLength()
{
// Create a string of characters, numbers, special characters that allowed in the password
string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";
Random random = new Random();
// Minimum size 8. Max size is number of all allowed chars.
int size = random.Next(8, validChars.Length);
// Select one random character at a time from the string
// and create an array of chars
char[] chars = new char[size];
for (int i = 0; i < size; i++)
{
chars[i] = validChars[random.Next(0, validChars.Length)];
}
return new string(chars);
}
}