schangxiang@126.com
2025-08-05 04d10bce51a6272d02a4a0f1b05a4f64bf73f273
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
 
public class PasswordGenerator
{
    //private const string ValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
    private const string ValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
    private static readonly object _lock = new object(); // 用于线程安全
    private static readonly char[] _chars = ValidChars.ToCharArray(); // 预加载字符数组以提高性能
    private static readonly int _validCharsLength = ValidChars.Length; // 预加载长度以提高性能
    private static readonly byte[] _randomBytesBuffer = new byte[4]; // 用于生成随机数以初始化Random对象(可选,取决于需求)
    private static readonly Random _random = new Random(); // 仅为初始化Random对象(可选,取决于需求)
    private static readonly ThreadLocal<Random> _threadRandom = new ThreadLocal<Random>(() => new Random(BitConverter.ToInt32(GetRandomBytes(), 0))); // 线程安全的Random对象(可选,取决于需求)
    private static byte[] GetRandomBytes() { lock (_lock) { _rng.GetBytes(_randomBytesBuffer); return _randomBytesBuffer; } } // 获取随机字节数组的方法,确保线程安全。如果不需要线程安全,可以移除lock。
    private static int GetRandomInt(int maxValue) => _threadRandom.Value.Next(maxValue); // 使用线程安全的Random对象获取随机整数。如果不需要线程安全,可以使用普通的_random.Next(maxValue)。
    private static char GetRandomChar() => _chars[GetRandomInt(_validCharsLength)]; // 获取随机字符。如果不需要线程安全,可以使用_chars[random.Next(_validCharsLength)]。
    public static string GenerateRandomPassword(int length) => new string(Enumerable.Range(0, length).Select(_ => GetRandomChar()).ToArray()); // 生成密码字符串。如果不需要线程安全,可以直接使用_chars[random.Next(_validCharsLength)]。
}