繁体   English   中英

C#RNGCryptoServiceProvider和特殊字符

[英]C# RNGCryptoServiceProvider and special characters

我正在寻找一种获取随机字符的方法。我需要一个字符串必须包含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

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

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

我执行了以下操作:

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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM