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.

Download  Run Code

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.

Download  Run Code

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#.