如何得到一个随机密码

public sealed class PasswordEngine
{
    private static PasswordEngine engine = new PasswordEngine();
 
    public static PasswordEngine Default
    {
        get
        {
            return engine;
        }
    }
        
    private readonly Random rnd = new Random();
    private string[] allowedCharacters = new string[]
    {
        "abcdefghijklmnopqrstuvwxyz",
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "1234567890",
        "!@#$%^&*()_"
    };
 
    public string Generate(int size)
    {
        return Generate(size, 0, 0, 0);
    }
 
    public string Generate(int size,  int minCapitalLetters, int minNumbers, int minSpecial)
    {
        //Parameter validation
        if (minCapitalLetters + minNumbers + minSpecial > size)
        {
            throw new Exception("Parameter size should be less than or equal to minCapitalLetters + minSmallLetters + minNumbers + minSpecial");
        }
 
 
        //Buffer for 
        char[] buffer = new char[size];
 
        int currentIndex = 0;
        //Fill Capital Letters
        currentIndex = FillBuffer(currentIndex, minCapitalLetters, 1, buffer);
        //Fill Numbers Characters
        currentIndex = FillBuffer(currentIndex, minNumbers, 2, buffer);
        //Fill Special Characters
        currentIndex = FillBuffer(currentIndex, minSpecial, 3, buffer);
 
        //Fill remaining buffer with small characters
        int minSmallLetters= size - (minCapitalLetters  + minNumbers + minSpecial);
        currentIndex = FillBuffer(currentIndex, minSmallLetters, 0, buffer);
 
        RandomizeBuffer(size, buffer);
 
        return new string(buffer);
    }
 
    private void RandomizeBuffer(int size, char[] buffer)
    {
        for (int i = 0; i < size; i++)
        {
            char source = buffer[i];
            int swapIndex = rnd.Next(size);
            buffer[i] = buffer[swapIndex];
            buffer[swapIndex] = source;
        }
    }
 
    private int FillBuffer(int startIndex, int count, int row, char[] buffer)
    {
        for (int i = 0; i < count; i++)
        {
            rnd.Next(3);
            int col = rnd.Next(allowedCharacters[row].Length);
 
            buffer[i+startIndex] = allowedCharacters[row][col];
        }
 
        return startIndex + count;
    }
}
//This will generate a simple password
string password1 = PasswordEngine.Default.Generate(10);
 
//This will generate a password with 2 numbers, 2 special and 2 capital letters
string password2 = PasswordEngine.Default.Generate(10, 2, 2, 2);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值