I'm looking to do some pattern matching for passwords, and found a regex example on SO, but when I pass a password through which should be deemed "strong", I am met with the opposite. For example, the string "JlcimYQF+EkHVA*" yields a rating of 1, which means that the string patterns aren't being matched in the regex, but I am unsure why.
Code below:
public class PasswordAdvisor
{
public static PasswordScore CheckStrength(string password)
{
int score = 1;
if (password.Length < 12)
return PasswordScore.TooShort;
if (password.Length >= 16)
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;
}
}
Deceleration:
var passwordStrengthScore = PasswordAdvisor.CheckStrength(@"JlcimYQF+EkH*VA");
Console.WriteLine((int)passwordStrengthScore);
switch (passwordStrengthScore)
{
case PasswordScore.TooShort:
Console.WriteLine("Password is too short");
break;
case PasswordScore.Weak:
Console.WriteLine("Password is very weak");
break;
case PasswordScore.Medium:
Console.WriteLine("OK password");
break;
case PasswordScore.Strong:
Console.WriteLine("Strong password");
break;
case PasswordScore.VeryStrong:
Console.WriteLine("Very strong password");
break;
}