How to Generate Random Passwords in C#

How to Generate Random Passwords in C#

This tutorial will demonstrate how you can generate random passwords in C# using System.Web.Security.

Generate Random Passwords using the System.Web.Security Method in C#

The .NET Framework provides a function you can use to generate passwords at any length you specify and containing a certain number of non-alphanumeric characters using its function GeneratePasswords. To utilize this, you must first ensure that you have added a reference to System.Web. To add this reference, follow the steps below:

  • Right-click on References
  • Click Add Reference
  • Click the Assemblies tab on the left
  • Find the System.Web.dll file and click “OK'”

After successfully adding the reference, you can then use its using statement in your code.

using System.Web.Security;

The GeneratePassword function accepts two inputs. The first, the number of characters required in the password to be generated. The second input refers to the number of non-alphanumeric characters required. The generated password is then returned as a string variable which you can then use in your code.

Example:

using System;
using System.Web.Security;

namespace GeneratePassword_Example {
  class Program {
    static void Main(string[] args) {
      // Create a for loop to run the code 10 times
      for (int i = 0; i < 10; i++) {
        // Store the password generated into a string variable
        // The password will have a length of 8 characters and 3 non alphanumeric characters
        string generated_pass = Membership.GeneratePassword(8, 3);
        // Print the newly generated password to the console
        Console.WriteLine("Password " + (i + 1).ToString() + ": " + generated_pass);
      }

      Console.ReadLine();
    }
  }
}

In the example above, we ran the GeneratePassword function 10 times within a loop to demonstrate how all passwords generated are different and meet the requirements set by the input parameters.

Output:

Password 1: *X!2OL%8
Password 2: _0=[qjFq
Password 3: &zGiOR=#
Password 4: *Is8&]2j
Password 5: Dv-${$Pt
Password 6: *Gkr-B4.
Password 7: )e==gu3O
Password 8: X$+LRe(e
Password 9: *2Y[.gpJ
Password 10: .W=y1zF&

Related Article - Csharp Random