C#RNGCryptoServiceProvider和特殊字符

时间:2016-06-19 05:36:21

标签: c#

我正在寻找一种获取随机字符的方法。我需要一个字符串必须包含至少2个大写字母,至少1个数字和特殊字符。 这是我的代码:

public static string CreateRandomPassword(int Length)
{
    string _Chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ[_!23456790";
    Byte[] randomBytes = new Byte[Length];
    var rng = new RNGCryptoServiceProvider();
    rng.GetBytes(randomBytes);
    var chars = new char[Length];
    int Count = _Chars.Length;

    for(int i = 0;i<Length;i++)
    {
        chars[i] = _Chars[(int)randomBytes[i] % Count];
    }
    return new string(chars);
}

一些结果:

ZNQzvUPFKOL3x

BQSEkKHXACGO

他们没有特殊字符和数字。

1 个答案:

答案 0 :(得分:1)

你的代码很棒!我刚刚用一个验证你的条件的功能包装它。

我执行了以下操作:

public static string CreateRandomPassword(int Length)
    {
        string _Chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ[_!23456790";
        Byte[] randomBytes = new Byte[Length];
        var rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);
        var chars = new char[Length];
        int Count = _Chars.Length;

        for (int i = 0; i < Length; i++)
        {
            chars[i] = _Chars[(int)randomBytes[i] % Count];
        }
        return new string(chars);
    }

    public static string CreateRandomPasswordWith2UpperAnd1NumberAnd1Special(int length)
    {
        while (true)
        {
            var pass = CreateRandomPassword(length);
            int upper=0, num =0, special = 0,lower=0;
            foreach (var c in pass)
            {
                if (c > 'A' && c < 'Z')
                {
                    upper++;
                }
                else if (c > 'a' && c < 'z')
                {
                    lower++;
                }
                else if (c > '0' && c < '9')
                {
                    num++;
                }
                else
                {
                    special++;
                }
            }
            if (upper>=2&&num>=1&&1>=special)
            {
                return pass;
            }
        }
    }

    [Test]
    public void CreateRandomPassword_Length13_RandomPasswordWithNumbers()
    {
        var random = CreateRandomPasswordWith2UpperAnd1NumberAnd1Special(13);
        Assert.IsTrue(true);
    }