Calculate password strength

Share your advanced PureBasic knowledge/code with the community.
User avatar
Kukulkan
Addict
Addict
Posts: 1352
Joined: Mon Jun 06, 2005 2:35 pm
Location: germany
Contact:

Calculate password strength

Post by Kukulkan »

Hello,

I wrote a small blog-article about my password strength check function (in German only). Inside the article, it is available in PHP and JavaScript. Maybe you are interested in a PureBasic version, too?

The German article: http://blog.inspirant.de/index.php?cont ... &id_post=9

Code: Select all

; (w) 2015 Volker Schmid
; (c) free to use, copy, vary and distribute
;
; Calculate a strength value from given password.
; If strength is > 30, the password is considered safe!
; 
; KEEP THIS SIMILAR To JS and PHP FUNCTION PassStrength()!!!!
; 
; PB >= 5.4, works in 32 and 64 bit, cross-platform
;
; @param string Password
; @returns int Strength

Procedure.i PassStrength(Password.s)
  ; length check
  Protected numCount.i = 0
  ; initial strength = len^2/6
  Protected W.f = (Len(Password.s) * Len(Password.s)) / 6
  If Password.s = Str(Val(Password.s))
    ; note first character is numeric
    numCount.i + 1
  EndIf

  Protected i.i
  For i.i = 2 To Len(Password.s)
    ; If previous char was another one this is good, otherwise bad
    Protected t.s = Mid(Password.s, i.i, 1); this
    Protected p.s = Mid(Password.s, i.i-1, 1); previous
    If t.s <> p.s
      W.f + 2
    Else
      W.f - 1
    EndIf
    
    ; check, If previous char was other Case the current (good)
    Protected upper.b  = Bool(t.s = UCase(t.s))
    Protected lower.b  = Bool(t.s = LCase(t.s))
    Protected pupper.b = Bool(p.s = UCase(p.s))
    Protected plower.b = Bool(p.s = LCase(p.s))

    ; good If previous Case is different than current
    If (upper.b <> pupper.b Or lower.b <> plower.b)
      W.f + 2
    EndIf
    
    ; check If value is used multiple times
    Protected occurences.i = CountString(Password.s, t.s)
    If occurences.i > 3
      W.f - 2
    EndIf

    ; count number of numeric characters
    If t.s = Str(Val(t.s))
      numCount.i + 1
    EndIf
  Next

  ; extra points If number of numeric characters is between 20 And 70 percent
  If numCount.i > Len(Password.s) * 0.2 And numCount.i < Len(Password.s) * 0.7
    W.f + 5
  EndIf

  ; Not good If password is more than 70% numbers
  If numCount.i > Len(Password.s) * 0.7
    W.f - 5
  EndIf
  
  ; no negative results
  If W.f < 0: W.f = 0: EndIf
  ; 
  ; Return rounded result
  ProcedureReturn Round(W.f, #PB_Round_Nearest)
EndProcedure

Debug PassStrength("oERF4884")