DesiBoyz
DesiBoyz

Reputation: 128

Checking for Password within a password hint

I am trying to right some code to prevent a user from entering their password in the password hint. I was thinking of preventing the user from having three consecutive characters from the password in their password hint even if they were separated by one character i.e. p-a-s-s-w-o-r-d.

I wrote the code below but this prevents password hints such as: password: p123a21312swert1 which is too strict. This is because I strip out all of the characters from the password hint that are not in the password. I had a search around but couldn't find anything relevant.

var strippedPwdHint = new string(sValue.Where(c => sCompareTo.ToCharArray().Contains(c)).ToArray());

for (var i = 0; i < (strippedPwdHint.Length - 2); i++)
{
    if (!sCompareTo.Contains(strippedPwdHint.Substring(i, 3))) continue;
    retVal = new ValidationResult(ErrorMessage);
    break;
}

Upvotes: 1

Views: 2306

Answers (1)

Gareth
Gareth

Reputation: 911

In cases like this it's often a case of "how far do I go?" because you're unlikely to ever cover all cases. On top of this something that is obvious and should be prevented to one person may be so obscure it doesn't matter to someone else.

While checking the hint doesn't match the password forwards or backwards is simple and an obvious thing to do to do more gets complicated quite quickly.

Assuming you have

string password = [Password]
string hint = [Password Hint]

Simply comparing the password and hint will flag cases where they match

bool invalid = password.Compare(hint);

To catch the reverse case you could do something like this

string reversed = new string(hint.ToCharArray().Reverse().ToArray());
bool invalid = password.Compare(reversed);

If, as you suggest you've got something like this

string hint = "P-a-s-s-w-o-r-d";

and you know the spacing character then you can replace it then compare

bool invalid = password.Compare(hint.Replace("-",""));

However, if you're not sure what the spacing character is it's more complicated and you'd have to be careful that you're not flagging legal scenarios as invalid.

Assuming you only want to rule out the scenario where the hint is the password + regular spacing, e.g. "P-a-s-s-w-o-r-d" one approach might be

  • Find the spacing between the first and second password characters in the hint
  • Step through the hint in these steps comparing the hint to the password

Further questions include

  • Do the spacing characters matter? For example, how do you handle P-a-s-s!w!o!r!d compared to P-a-s-s-w-o-r-d?
  • How many spacing characters do you care about? For example, is P followed by 20 characters then assword valid?

This being said, it's probably not worth getting too complicated and comparing the hint with the password forwards and backwards is probably enough.

Upvotes: 1

Related Questions