检查字符串是否有足够强的密码

Voi*_*ing 18 c# string passwords webmatrix razor

可能重复:
强密码正则表达式
需要RegEx密码强度?

我只是想知道在某些条件下搜索字符串的最佳方法是什么(具体的密码强度)可以实现.

到目前为止,我有一个简单的:

if(password.Length <= 7)
    {
        errorMessage = "Your password must be at least 8 characters.";
    }
Run Code Online (Sandbox Code Playgroud)

我希望能够检查大写字母,但我不确定方法或程序是什么.我试过Googling,搜索网站:http: //msdn.microsoft.com,搜索我的C#书的索引(C#Programming 3E,Barbara Doyle),但我似乎找不到任何东西.

我知道我可以尝试这个......:

foreach(char c in password)
    {
        if(c!='A' || c!='B' || c!='C' || c!='D' ..... || c!='Z')
        {
            errorMessage = "Your password must contain at least one capital letter";
        }
    }
Run Code Online (Sandbox Code Playgroud)

...但这将是非常草率的,并且必须加倍才能检查至少一个小写字母.我确信有更好的方法可以做到这一点,或者至少是我上面显示的方法的简写.

此外,我可能决定检查特殊字符的密码(在上面的示例中似乎比使用大写和小写字母更容易做,所以我可以将它用于特殊字符,如果我决定使它们成为必要).如果有一种简单(或适当)的方式,我也很乐意拥有这些知识.

无论如何,非常感谢你们给予任何帮助.

Ste*_*ird 62

当我从这里偷走这件事时,我无法理解

using System.Text;
using System.Text.RegularExpressions;

  public enum PasswordScore
  {
    Blank = 0,
    VeryWeak = 1,
    Weak = 2,
    Medium = 3,
    Strong = 4,
    VeryStrong = 5
  }

  public class PasswordAdvisor
  {
    public static PasswordScore CheckStrength(string password)
    {
      int score = 0;

      if (password.Length < 1)
        return PasswordScore.Blank;
      if (password.Length < 4)
        return PasswordScore.VeryWeak;

      if (password.Length >= 8)
        score++;
      if (password.Length >= 12)
        score++;
      if (Regex.Match(password, @"/\d+/", RegexOptions.ECMAScript).Success)
        score++;
      if (Regex.Match(password, @"/[a-z]/", RegexOptions.ECMAScript).Success &&
        Regex.Match(password, @"/[A-Z]/", RegexOptions.ECMAScript).Success)
        score++;
      if (Regex.Match(password, @"/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/", RegexOptions.ECMAScript).Success)
        score++;

      return (PasswordScore)score;
    }
  }
Run Code Online (Sandbox Code Playgroud)

请注意使用正则表达式来检查大写字符.这似乎是一个不错的方法,因为它检查长度,使用大写和小写字符,数字和特殊字符.

**更新**

我知道这个问题现已关闭,但我可以为VoidKing添加更多解释来理解一些概念.

从CheckStrength方法返回PasswordScore,该方法可用作代码中下一步操作的条件.

这是一个未经测试的演示,说明如何使用上述代码:

String password = "MyDummy_Password"; // Substitute with the user input string
PasswordScore passwordStrengthScore = PasswordAdvisor.CheckStrength(password);

switch (passwordStrengthScore) {
    case PasswordScore.Blank:
    case PasswordScore.VeryWeak:
    case PasswordScore.Weak:
            // Show an error message to the user
            break;
    case PasswordScore.Medium:
    case PasswordScore.Strong:
    case PasswordScore.VeryStrong:
           // Password deemed strong enough, allow user to be added to database etc
           break;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,枚举用作将密码强度分类为人类可读组的手段.保持代码干净,并使代码中的内容变得明显.

关于正则表达式的使用,如果你不熟悉它们的概念以及如何以及何时使用它们,我建议做一些研究,因为这些在许多不同场景中用于检查字符串中的模式是有用的.也许从这里开始.

  • 密码为"Password @ 123"将产生`PasswordScore`为`6`,未在`enum`中定义.因此得分必须从0开始才能使其更可靠. (3认同)
  • 我必须去掉尾随/前导“/”才能使其正常工作。 (2认同)