Generate a random password in C#
This post will discuss how to generate a cryptographically strong random password of specified length in C#.
1. Using Random Class
The idea is to randomly choose characters from a selected range of ASCII characters and construct a string of the desired length out of it.
To construct a random alphanumeric password, the ASCII range should consist of digits, uppercase, and lowercase characters, as shown below. We can further extend the following code to generate any other characters that fall within some ASCII range.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; using System.Text; public class Example { public static string GetRandomPassword(int length) { const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; StringBuilder sb = new StringBuilder(); Random rnd = new Random(); for (int i = 0; i < length; i++) { int index = rnd.Next(chars.Length); sb.Append(chars[index]); } return sb.ToString(); } public static void Main() { int length = 10; string password = GetRandomPassword(length); Console.WriteLine(password); } } /* Output: 3Dn6V7dK48 */ |
2. Using RNGCryptoServiceProvider Class
The RNGCryptoServiceProvider class should be used over the Random class to ensure a cryptographically strong random number generator. The following code example creates a random sequence of the specified number of byte using the RNGCryptoServiceProvider class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Security.Cryptography; public class Example { public static string GetRandomPassword(int length) { byte[] rgb = new byte[length]; RNGCryptoServiceProvider rngCrypt = new RNGCryptoServiceProvider(); rngCrypt.GetBytes(rgb); return Convert.ToBase64String(rgb); } public static void Main() { int length = 10; string password = GetRandomPassword(length); Console.WriteLine(password); } } /* Output: snVzDvDCcEKyng== */ |
3. Using Membership.GeneratePassword() method
To generate a random password of the specified length, we can also use the Membership.GeneratePassword() method from the System.Web.Security namespace. It takes the length and the minimum number of non-alphanumeric characters in the generated password.
Its usage can be seen here.
That’s all about generating a random password in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)