Random Password In C#

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.

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.

  1. // Generate a random number  
  2. Random random = new Random();  
  3. // Any random integer   
  4. int num = random.Next();  

Listing 1.

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.

  1. // Generate a random string with a given size and case.   
  2. // If second parameter is true, the return string is lowercase  
  3. public string RandomString(int size, bool lowerCase)  
  4. {  
  5.     StringBuilder builder = new StringBuilder();  
  6.     Random random = new Random();  
  7.     char ch;  
  8.     for (int i = 0; i < size; i++)  
  9.     {  
  10.         ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
  11.         builder.Append(ch);  
  12.     }  
  13.     if (lowerCase)  
  14.         return builder.ToString().ToLower();  
  15.     return builder.ToString();  
  16. }  

Listing 2.

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.

  1. // Generate a random password of a given length (optional)  
  2. public string RandomPassword(int size = 0)  
  3. {  
  4.     StringBuilder builder = new StringBuilder();  
  5.     builder.Append(RandomString(4, true));  
  6.     builder.Append(RandomNumber(1000, 9999));  
  7.     builder.Append(RandomString(2, false));  
  8.     return builder.ToString();  
  9. }  

Listing 3.

All of the above functionality is listed here in Listing 4. Create a .NET Core Console app in Visual Studio and use this code.

  1. using System;  
  2. using System.Text;  
  3.   
  4. class RandomNumberSample  
  5. {  
  6.     static void Main(string[] args)  
  7.     {  
  8.         // Generate a random number  
  9.         Random random = new Random();  
  10.         // Any random integer   
  11.         int num = random.Next();  
  12.   
  13.         // A random number below 100  
  14.         int randomLessThan100 = random.Next(100);  
  15.         Console.WriteLine(randomLessThan100);  
  16.   
  17.         // A random number within a range  
  18.         int randomBetween100And500 = random.Next(100, 500);  
  19.         Console.WriteLine(randomBetween100And500);  
  20.   
  21.         // Use other methods   
  22.         RandomNumberGenerator generator = new RandomNumberGenerator();  
  23.         int rand = generator.RandomNumber(5, 100);  
  24.         Console.WriteLine($"Random number between 5 and 100 is {rand}");  
  25.   
  26.         string str = generator.RandomString(10, false);  
  27.         Console.WriteLine($"Random string of 10 chars is {str}");  
  28.   
  29.         string pass = generator.RandomPassword();  
  30.         Console.WriteLine($"Random password {pass}");  
  31.   
  32.         Console.ReadKey();  
  33.     }  
  34. }  
  35.   
  36. public class RandomNumberGenerator  
  37. {  
  38.     // Generate a random number between two numbers    
  39.     public int RandomNumber(int min, int max)  
  40.     {  
  41.         Random random = new Random();  
  42.         return random.Next(min, max);  
  43.     }  
  44.   
  45. // Generate a random string with a given size and case.   
  46. // If second parameter is true, the return string is lowercase  
  47. public string RandomString(int size, bool lowerCase)  
  48. {  
  49.     StringBuilder builder = new StringBuilder();  
  50.     Random random = new Random();  
  51.     char ch;  
  52.     for (int i = 0; i < size; i++)  
  53.     {  
  54.         ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
  55.         builder.Append(ch);  
  56.     }  
  57.     if (lowerCase)  
  58.         return builder.ToString().ToLower();  
  59.     return builder.ToString();  
  60. }  
  61.   
  62.     // Generate a random password of a given length (optional)  
  63.     public string RandomPassword(int size = 0)  
  64.     {  
  65.         StringBuilder builder = new StringBuilder();  
  66.         builder.Append(RandomString(4, true));  
  67.         builder.Append(RandomNumber(1000, 9999));  
  68.         builder.Append(RandomString(2, false));  
  69.         return builder.ToString();  
  70.     }  
  71. }  

Listing 4.

The random string and random password looks like Figure 1.

 Generate A Random Password In C# And .NET Core
Figure 1.

 

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.

  1. private static string CreateRandomPassword(int length = 15)  
  2. {  
  3.     // Create a string of characters, numbers, special characters that allowed in the password  
  4.     string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";  
  5.     Random random = new Random();  
  6.   
  7.     // Select one random character at a time from the string  
  8.     // and create an array of chars  
  9.     char[] chars = new char[length];  
  10.     for (int i = 0; i < length; i++)  
  11.     {  
  12.         chars[i] = validChars[random.Next(0, validChars.Length)];  
  13.     }  
  14.     return new string(chars);  
  15. }  

Listing 5.

Note
You can modify validChars string with the characters you allowed in the password.

Reference
https://madskristensen.net/blog/generate-random-password-in-c/

Listing 6 is the complete program written in .NET Core.

  1. using System;  
  2.   
  3. class Program  
  4. {  
  5.     static void Main(string[] args)  
  6.     {   
  7.         Console.WriteLine(CreateRandomPassword());  
  8.         Console.WriteLine(CreateRandomPassword(10));  
  9.         Console.WriteLine(CreateRandomPassword(30));  
  10.   
  11.         Console.WriteLine(CreateRandomPasswordWithRandomLength());  
  12.   
  13.         Console.ReadKey();  
  14.     }  
  15.   
  16.   
  17.     // Default size of random password is 15  
  18.     private static string CreateRandomPassword(int length = 15)  
  19.     {  
  20.         // Create a string of characters, numbers, special characters that allowed in the password  
  21.         string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";  
  22.         Random random = new Random();  
  23.   
  24.         // Select one random character at a time from the string  
  25.         // and create an array of chars  
  26.         char[] chars = new char[length];  
  27.         for (int i = 0; i < length; i++)  
  28.         {  
  29.             chars[i] = validChars[random.Next(0, validChars.Length)];  
  30.         }  
  31.         return new string(chars);  
  32.     }  
  33.   
  34.     private static string CreateRandomPasswordWithRandomLength()  
  35.     {  
  36.         // Create a string of characters, numbers, special characters that allowed in the password  
  37.         string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";  
  38.         Random random = new Random();  
  39.   
  40.         // Minimum size 8. Max size is number of all allowed chars.  
  41.         int size = random.Next(8, validChars.Length);  
  42.   
  43.         // Select one random character at a time from the string  
  44.         // and create an array of chars  
  45.         char[] chars = new char[size];  
  46.         for (int i = 0; i < size; i++)  
  47.         {  
  48.             chars[i] = validChars[random.Next(0, validChars.Length)];  
  49.         }  
  50.         return new string(chars);  
  51.     }  

Listing 6.

Summary

In this article and code sample, we learned how to generate random passwords using C# in .NET Core.