Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing a Desktop Application using vb.net. I want to test the password strength created by the users. I am using this code but it does not seem to work for me. Please assist.
VB
Enum PasswordScore
    Blank = 0
    VeryWeak = 1
    Weak = 2
    Medium = 3
    GOOD = 4
    Strong = 5
    VeryStrong = 6
End Enum

Public Function CheckStrength(ByVal password As String) As PasswordScore
    Dim score As Integer = 1

    If password.Length < 1 Then
        Return PasswordScore.Blank
    End If
    If password.Length < 4 Then
        Return PasswordScore.VeryWeak
    End If

    If password.Length >= 5 Then
        score = score + 1
    End If
    If password.Length >= 10 Then
        score = score + 1
    End If

    If Regex.IsMatch(password, "/\d+/") Then
        score = score + 1
    End If

    If Regex.IsMatch(password, "/[a-z]/") Then

        score = score + 1
    End If

    If Regex.IsMatch(password, "/[0-9]/") Then

        score = score + 1
    End If

    If Regex.IsMatch(password, "/[A-Z]/") Then
        score = score + 1
    End If
    If Regex.IsMatch(password, "/[.,!,@,#,$,%,^,&]/") Then
        score = score + 1
    End If
    If Regex.IsMatch(password, "/[*,?,_,~,-,£,(,)]/") Then
        score = score + 1
    End If


    Return CType(score, PasswordScore)
End Function
Posted
Updated 11-Jan-11 1:50am
v2
Comments
JF2015 11-Jan-11 7:50am    
Added code formatting. Please always wrap your code snippets with <pre> tags.
CPallini 11-Jan-11 7:53am    
"Doesn't work" is pretty vague: to get better help you should state what the expected and osserved behaviours are.

The probable problem is that your score can be a higher value than you have enums to represent it.

What you might want to try is adding this code before the return statement:

VB
score = Math.Min(DirectCast(PasswordScore, integer), score)


At least you'll normalize the value into something that can be used. However, I would refactor the entire method, and probably not use enums the way you're using them.

 
Share this answer
 
v3
I have a 2nd answer - if you google "strong password check", you'll find a site that suggests several regex clauses that you could use to do the very same thing. To maintain your scoring paradigm, put each regex into its own method that returns either 1 or 0.

Here's a page that has several regex clauses:

http://www.webpronews.com/expertarticles/2006/12/14/validating-strong-passwords-in-c-and-aspnet[^]
 
Share this answer
 
v2
Comments
fjdiewornncalwe 11-Jan-11 10:07am    
+5. Super answer.
Sergey Alexandrovich Kryukov 11-Jan-11 10:44am    
Good find -- big difference - a 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900