I am using Membership.GeneratePassword() to generate a random password. Sometimes the returned value doesn't match needed validation requirements. A user can also supply a password, hence the validation requirements.
I basically want to check the returned password, if it doesn't contain an uppercase letter, and lowercase letter, and a digit then generate another one.
Sometimes my check will return true, when it obviously isn't.
I have attempted RegEx and some LINQ as so:
string generatePassword()
{
password = System.Web.Security.Membership.GeneratePassword(16, 8);
if (password.Any(c => char.IsUpper(c)) && password.Any(c => char.IsDigit(c)) && password.Any(c => char.IsLower(c)))
{
return password;
}
else
{
generatePassword();
}
}
void test() {
var pattern = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_\-+=[{\]};:<>|.\/\?])(?=.{8,})";
var count = 0;
for (var i = 0; i < 10000; i++)
{
var password = generatePassword();
if (!Regex.Match(password, pattern).Success)
{
Console.WriteLine(password);
count++;
}
}
Console.WriteLine("There were {0} non matches", count);
}
In my mind, the above should always return a valid password. I have a weird scenario wherein it will return a password that doesn't have a digit, so the check fails, but if I do the same passowrd.Any(char.IsDigit)
inside of test
against the returned password, it'll say true.
If it helps, the password needs to be at least 8 digits, contain an uppercase, lowercase, digit and a special char: !@#$%^&*()_-+=[{]};:<>|./?
Thanks.