Jump to content


Photo

Function to validate password length and complexity.

security password validate length complexity

  • Please log in to reply
1 reply to this topic

#1 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 07 March 2013 - 07:01 AM

Continuing my posting of security-related functions in this section, I've decided to post this one up. I've posted a basic version of the RegExp previously, to which Psycho gave me some good feedback.

Thus, the current function was born:
// Define the flags used for validating passwords.
define ('SF_VALIDATE_PASS_LOWER', 1);
define ('SF_VALIDATE_PASS_UPPER', 2);
define ('SF_VALIDATE_PASS_NUMERICAL', 4);
define ('SF_VALIDATE_PASS_SPECIAL', 8);
define ('SF_VALIDATE_PASS_ALL', 15);

/**
 * Validates the password according to the flags and mininum length given.
 *
 * Returns true if the password matches the constraints, or false if it fails.
 *
 * Default minimum length is 8 characters, and all flags activated.
 *
 * @author Christian Fagerheim (Fagerheim Software)
 * @link www.fagsoft.no
 * @license Creative Commons Attribution-ShareAlike 3.0. http://creativecommons.org/licenses/by-sa/3.0/.
 *
 * @param string $password
 * @param int[optional] $minLength
 * @param int[optional] $flags
 *
 * @return bool
 */
function validatePassword ($password, $minLength = 8, $flags = SF_VALIDATE_PASS_ALL) {
	// Make sure we got a valid minimum length.
	if (!is_int ($minLength) || $minLength < 0) {
		trigger_error ('Minimum length must be a positive integer', E_USER_ERROR);
	}

	// Create the constraints for the password.
	$passReg = '';
	if ($flags & SF_VALIDATE_PASS_LOWER) {
		$passReg .= '(?=.*[a-z])';
	}
	if ($flags & SF_VALIDATE_PASS_UPPER) {
		$passReg .= '(?=.*[A-Z])';
	}
	if ($flags & SF_VALIDATE_PASS_NUMERICAL) {
		$passReg .= '(?=.*\\d)';
	}
	if (false && $flags & SF_VALIDATE_PASS_SPECIAL) {
		$special = preg_quote (',.;:"\'!?*(){}[]/^§|#¤%&_=<>@£$€ +-', '/');
		$passReg .= "(?=.*[$special])";
	}

	// Add the minimum length requirement.
	$passReg .= '.{'.$minLength.',}';

	// Check that the password matches the constraints, and return a boolean.
	if (!preg_match ("/^$passReg\\z/u", $password)) {
		return false;
	}

	return $password;
}

Keeping it simple.

#2 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 07 March 2013 - 09:06 AM

Just noticed a little mistake in the code above. For some reason there's an extra false && which shouldn't be there, in the final constraint check. Remove it to make the special characters limitation apply.
Keeping it simple.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com