2016-06-19 64 views
2

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

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

的几率为你的算法创建一个字符串(?密码)是相当低的字母只是提供了其中三个('的[_ !')。 – khlr

+0

分隔小写字母,大写字母,数字,特殊字符的字符串....随机生成一组这些字符串并以随机方式混合使用。 (可能有更好的方法) –

+0

你也许只需要省力一些并使用guid即可。由于长度而更加随机的方式,同样不可能让人记住。 –

回答

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

谢谢!它是完美的。你的代码给了我强大的密码。替换else {special ++; } with} else if(c =='['|| c =='_'|| c =='!'){special ++; }以确保获得特殊字符。 – Jandy

+0

如果你已经使用它,那就投票吧,顺便说一句,你不必验证这个特殊因素,因为它不能是其他的东西...... – silver

+0

else if(c =='['|| c =='_' || c =='!'){special ++; }它需要大量的内存。 – Jandy