2016-06-19 2 views
2

임의의 문자를 가져 오는 방법을 찾고 있습니다. 문자열에 대문자 2 자 이상, 숫자 1 자 이상 및 특수 문자가 있어야합니다. 그들은하지 특수 문자와 숫자가C# RNGCryptoServiceProvider 및 특수 문자

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

어떤 결과 : 다음은 내 코드입니다.

+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