开源 密码生成器源码 | C#

Sky

0x04|共鸣者
07
121
78
奇源币
0
管理成员
版主
VIP
C#:
using System;
using System.Security.Cryptography;

class PasswordGenerator
{
    private const string UppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string LowercaseChars = "abcdefghijklmnopqrstuvwxyz";
    private const string DigitChars = "0123456789";
    private const string SpecialChars = "!@#$%^&*()-_=+[]{}|;:'\",.<>/?";

    private static Random random = new Random();

    public static string GeneratePassword(int length, bool includeUppercase, bool includeLowercase, bool includeDigits, bool includeSpecialChars)
    {
        string validChars = "";

        if (includeUppercase)
            validChars += UppercaseChars;
        if (includeLowercase)
            validChars += LowercaseChars;
        if (includeDigits)
            validChars += DigitChars;
        if (includeSpecialChars)
            validChars += SpecialChars;

        if (validChars.Length == 0)
            throw new ArgumentException("At least one character set must be selected.");

        char[] password = new char[length];
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            int max = validChars.Length;

            for (int i = 0; i < length; i++)
            {
                byte[] randomNumber = new byte[1];
                rng.GetBytes(randomNumber);
                int index = Convert.ToInt32(randomNumber[0]) % max;
                password[i] = validChars[index];
            }
        }

        return new string(password);
    }

    static void Main()
    {
        int passwordLength = 12;
        bool includeUppercase = true;
        bool includeLowercase = true;
        bool includeDigits = true;
        bool includeSpecialChars = true;

        string password = GeneratePassword(passwordLength, includeUppercase, includeLowercase, includeDigits, includeSpecialChars);
        Console.WriteLine("Generated Password: " + password);
    }
}
 
后退
顶部