密码强度验证器,你会如何改进?

时间:2011-09-25 13:39:42

标签: php zend-framework

首先,我使用StringLength验证器验证密码长度,因此我想将其保留在PasswordStrength验证器之外。任何想法如何改善这个?

我认为我使用数组和array_diff的方法不是很优雅,但我能想到的另一种方法是正则表达式,它更加难看。

<?php
class My_Validate_PasswordStrength extends Zend_Validate_Abstract
{
    const MSG_NO_NUMBER = 'msgNoNumber';
    const MSG_NO_LOWER_CASE_LETTER = 'msgNoLowerCaseLetter';
    const MSG_NO_UPPER_CASE_LETTER = 'msgNoUpperCaseLetter';

    protected $_messageTemplates = array(
        self::MSG_NO_NUMBER => "'%value%' must contain at least one number",
        self::MSG_NO_LOWER_CASE_LETTER => "'%value%' must contain at least one lower case letter",
        self::MSG_NO_UPPER_CASE_LETTER => "'%value%' must contain at least one upper case letter"
    );

    public function isValid($value)
    {
        $this->_setValue($value);

        $arr = str_split($value);
        $numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $lowerCaseLetters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
        'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        $upperCaseLetters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 
        'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

        if (count(array_diff($numbers, $arr)) === 10) {
            $this->_error(self::MSG_NO_NUMBER);
            return FALSE;
        }

        if (count(array_diff($lowerCaseLetters, $arr)) === 26) {
            $this->_error(self::MSG_NO_LOWER_CASE_LETTER);
            return FALSE;
        }

        if (count(array_diff($upperCaseLetters, $arr)) === 26) {
            $this->_error(self::MSG_NO_UPPER_CASE_LETTER);
            return FALSE;
        }

        return TRUE;
    }
}

2 个答案:

答案 0 :(得分:6)

我不认为正则表达式是丑陋的。

public function isValid($value)
{
    $this->_setValue($value);

    if (preg_match('/[0-9]/', $value) !== 1) {
        $this->_error(self::MSG_NO_NUMBER);
        return FALSE;
    }

    if (preg_match('/[a-z]/', $value) !== 1) {
        $this->_error(self::MSG_NO_LOWER_CASE_LETTER);
        return FALSE;
    }

    if (preg_match('/[A-Z]/', $value) !== 1) {
        $this->_error(self::MSG_NO_UPPER_CASE_LETTER);
        return FALSE;
    }

    return TRUE;
}

答案 1 :(得分:0)

这些测试如何提高力量?在客户,我们要求“密码必须包含至少1个数字,2个大写字母,至少1个'特殊字符'并且长度超过8个字符”

这些表达式计算每个要求 - 第三个计算所有非字母/数字

$capCount  = preg_match_all("/[A-Z]/", $newPassword, $matches);
$numCount  = preg_match_all("/[0-9]/", $newPassword, $matches);
$specCount = preg_match_all("/[^0-9a-zA-z]/", $newPassword, $matches);
相关问题