Thursday, January 24, 2008

Validating password strength

 

A question asked in the PowerShell news group:

I have a script that takes user input of a desired username\password for a local account to be created. However, the complex password policy is in effect so a simple password will not work. So if a simple password is put in, it won't ask again for a password, it will just fail and continue. How do i get the PS script to check if it was successful or if it failed and if it failed, prompt again for the information?

 

I ended up converting a VB.NET code from MSDN. Here's the PowerShell version:

 
Function Validate-Password{

    param(
        [string]$pwd = $(throw "Please specify password"),
        [int]$minLength=8,
        [int]$numUpper = 2,
        [int]$numLower = 2,
        [int]$numNumbers = 2, 
        [int]$numSpecial = 2
    )


    $upper = [regex]"[A-Z]"
    $lower = [regex]"[a-z]"
    $number = [regex]"[0-9]"
    #Special is "none of the above"
    $special = [regex]"[^a-zA-Z0-9]"

    # Check the length.
    if($pwd.length -lt $minLength) {$false; return}
# Check for minimum number of occurrences. if($upper.Matches($pwd).Count -lt $numUpper ) {$false; return} if($lower.Matches($pwd).Count -lt $numLower ) {$false; return} if($number.Matches($pwd).Count -lt $numNumbers ) {$false; return} if($special.Matches($pwd).Count -lt $numSpecial ) {$false; return} # Passed all checks. $true } # Demonstrate that "Password" is not complex. PS > $password = "Password" PS > "'{0}'is complex: {1}" -f $password,(Validate-Password $password)
'Z9f%a>2kQ' is complex: False
 
# Demonstrate that "Password" is complex. 
PS > $password = "Z9f%a>2kQ"
PS > "'{0}' is complex: {1}" -f $password,(Validate-Password $password)
'Z9f%a>2kQ' is complex: True
 

When writing this post I got an answer back that the code is too complicated. At first, it may look intimidating.. but this function lets you control how complex you want the password to be. You just need to specify the parameters, they are all self explanatory. All parameters are optional except for password :

# call it with default parameters
if (Validate-Password -pwd "password") {"password is valid"}

 

The following (one line) validates a password that:

1. Contains at list 10 characters
2. Contains at list 2 upper case characters (default)
3. Contains at list 2 lower case characters (default)
4. Containa at list 3 numbers
5. Contains at list 3 special cahracters

 

if (Validate-Password -pwd "password" -minLength 10 -numUpper 2 -numLower 2 -numNumbers 3 -numSpecial 3) {"password is valid"}

No comments: