Tuesday, July 12, 2011

Customizable Password Policy C#

Introduction
To enforce password strength in such a way that user can configure the number of uppercase, lowercase, special characters and digits the password can contain. 

Background
One of my projects, there arises a scenario in which the password strength is configure in the database. Have to make use of this database configuration to validate the password entered by the user. So I needed a class which can enforce this and should be highly customizable.

Using the code
Password Policy contains a method IsValid which takes password string as its parameter and checks for various conditions like minimum lenth of the password, the number of uppercase or lowercase the password can contain. The user can also customize the no of digits and non-alpha numeric characters also.
It does all the Counts throug the Regex.Matches function which retuns the number of occurances of the pattern.


public class PasswordPolicy
    {
        private static int Minimum_Length = 7;
        private static int Upper_Case_length = 1;
        private static int Lower_Case_length = 1;
        private static int NonAlpha_length = 1;
        private static int Numeric_length = 1;
 
        public static bool IsValid(string Password)  
        {
            if (Password.Length < Minimum_Length)
                 return false;               
             if (UpperCaseCount(Password) < Upper_Case_length)
                 return false;
             if (LowerCaseCount(Password) < Lower_Case_length)
                 return false;
             if (NumericCount(Password) < 1)
                 return false;
             if (NonAlphaCount(Password) < NonAlpha_length)
                 return false;
             return true;  
         }
 
        private static int UpperCaseCount(string Password)
        {
            return Regex.Matches(Password, "[A-Z]").Count;
        }
 
        private static int LowerCaseCount(string Password)
        {
            return Regex.Matches(Password, "[a-z]").Count;
        }
        private static int NumericCount(string Password)
        {
            return Regex.Matches(Password, "[0-9]").Count;
        }
        private static int NonAlphaCount(string Password)
        {
            return Regex.Matches(Password, @"[^0-9a-zA-Z\._]").Count;
        }
    }

No comments:

Post a Comment