September 26, 2018 11:14 by
Peter
A random password is a combination of characters, numbers, and special characters. We can generate a random password by combining random numbers and random strings.
Generate A Random Password In C# And .NET Core. The code snippet in this article is an example of how to generate random numbers and random strings and combine them to create a random password using C# and .NET Core.
The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value. The Random class has three public methods - Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0.
Generate a random number
The following code in Listing 1 returns a random number.
// Generate a random number
Random random = new Random();
// Any random integer
int num = random.Next();
Generate a random string
The following code snippet in Listing 2 generates a random string with a given size. The second parameter of the RandomString method is used for setting if the string is a lowercase string.
// Generate a random string with a given size and case.
// If 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();
}
Creating a random password
A random password can simply be a combination of a random string and a random number. To make it more complex, you can even add special characters and mix it up.
For us, we will combine the two methods - RandomNumber and RandomString.
The following code snippet in Listing 3 generates a password of length 10 with first 4 letters lowercase, next 4 letters numbers, and the last 2 letters as uppercase.
// 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();
}
All of the above functionality is listed here in Listing 4. Create a .NET Core Console app in Visual Studio and use 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 a random string with a given size and case.
// If 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();
}
// 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();
}
}
The random string and random password looks like Figure 1.
Generate A Random Password In C# And .NET Core
Random password with given characters
Now, let’s say, you want to create a password that allows some specific characters only. The following code snippet in Listing 5 has a string of valid characters. The code uses 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);
}
Note
You can modify validChars string with the characters you allowed in the password.
Listing 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);
}