create a password with a custom length and numbers in csharp

To create a password with a custom length and random numbers in C#, you can use the following code:

main.cs
using System;
using System.Security.Cryptography;

public static string GeneratePassword(int length)
{
    const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    var randomBytes = new byte[length];
    
    // Use a cryptographically secure random number generator to fill the byte array
    using (var rng = new RNGCryptoServiceProvider())
    {
        rng.GetBytes(randomBytes);
    }
    
    // Generate the password using the valid character set and randomBytes
    var result = new char[length];
    for (int i=0; i<length; i++)
    {
        // Map each byte to a valid character from the set
        result[i] = validChars[randomBytes[i] % validChars.Length];
    }
    
    return new string(result);
}
754 chars
25 lines

This function takes an integer length as input, and returns a string that is length characters long, and contains random characters from the set abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.

Note that this code uses a cryptographically secure random number generator to ensure that each byte in randomBytes is truly a random value, and not easily predictable.

You can call this function from elsewhere in your C# code as follows:

main.cs
string password = GeneratePassword(10); // Generate a password 10 characters long
82 chars
2 lines

gistlibby LogSnag