79 lines
2.7 KiB
C#
79 lines
2.7 KiB
C#
|
|
using System.Security.Cryptography;
|
|||
|
|
using System.Text;
|
|||
|
|
namespace LMS.Common.Password
|
|||
|
|
{
|
|||
|
|
public static class PasswordGenerator
|
|||
|
|
{
|
|||
|
|
private const string LowercaseChars = "abcdefghijklmnopqrstuvwxyz";
|
|||
|
|
private const string UppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|||
|
|
private const string NumberChars = "0123456789";
|
|||
|
|
private const string SpecialChars = "@$!%*?.&";
|
|||
|
|
private const string AllChars = LowercaseChars + UppercaseChars + NumberChars + SpecialChars;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 生成指定长度的随机密码
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="length">密码长度</param>
|
|||
|
|
/// <returns>随机生成的密码</returns>
|
|||
|
|
public static string GeneratePassword(int length)
|
|||
|
|
{
|
|||
|
|
if (length < 4)
|
|||
|
|
{
|
|||
|
|
throw new ArgumentException("密码长度必须至少为4个字符", nameof(length));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 使用加密安全的随机数生成器
|
|||
|
|
using var rng = RandomNumberGenerator.Create();
|
|||
|
|
// 确保密码包含至少一个小写字母、一个大写字母、一个数字和一个特殊字符
|
|||
|
|
var password = new StringBuilder();
|
|||
|
|
|
|||
|
|
// 添加每种类型的至少一个字符
|
|||
|
|
password.Append(GetRandomChar(LowercaseChars, rng));
|
|||
|
|
password.Append(GetRandomChar(UppercaseChars, rng));
|
|||
|
|
password.Append(GetRandomChar(NumberChars, rng));
|
|||
|
|
password.Append(GetRandomChar(SpecialChars, rng));
|
|||
|
|
|
|||
|
|
// 添加剩余的随机字符
|
|||
|
|
for (int i = 4; i < length; i++)
|
|||
|
|
{
|
|||
|
|
password.Append(GetRandomChar(AllChars, rng));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 打乱字符顺序
|
|||
|
|
return ShuffleString(password.ToString(), rng);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 从指定字符集中获取一个随机字符
|
|||
|
|
/// </summary>
|
|||
|
|
private static char GetRandomChar(string chars, RandomNumberGenerator rng)
|
|||
|
|
{
|
|||
|
|
byte[] data = new byte[1];
|
|||
|
|
rng.GetBytes(data);
|
|||
|
|
return chars[data[0] % chars.Length];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 打乱字符串中字符的顺序
|
|||
|
|
/// </summary>
|
|||
|
|
private static string ShuffleString(string input, RandomNumberGenerator rng)
|
|||
|
|
{
|
|||
|
|
char[] array = input.ToCharArray();
|
|||
|
|
int n = array.Length;
|
|||
|
|
|
|||
|
|
while (n > 1)
|
|||
|
|
{
|
|||
|
|
byte[] box = new byte[1];
|
|||
|
|
rng.GetBytes(box);
|
|||
|
|
int k = box[0] % n;
|
|||
|
|
n--;
|
|||
|
|
char temp = array[n];
|
|||
|
|
array[n] = array[k];
|
|||
|
|
array[k] = temp;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return new string(array);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|