Calculate the minimum entropy for a password and its matches.

@param string $password Password
@param array  $matches  Array of Match objects on the password

@return float Minimum entropy for non-overlapping best matches of a password
497153
public function getMinimumEntropy($password, $matches)
    {
        $passwordLength = strlen($password);
        $entropyStack = [];
        // for the optimal sequence of matches up to k, holds the final match (match.end == k).
        // null means the sequence ends without a brute-force character.
        $backpointers = [];
        $bruteforceMatch = new Bruteforce($password, 0, $passwordLength - 1, $password);
        $charEntropy = log($bruteforceMatch->getCardinality(), 2);

        foreach (range(0, $passwordLength - 1) as $k) {
            // starting scenario to try and beat: adding a brute-force character to the minimum entropy sequence at k-1.
            $entropyStack[$k] = $this->prevValue($entropyStack, $k) + $charEntropy;
            $backpointers[$k] = null;
            foreach ($matches as $match) {
                if (!isset($match->begin) || $match->end !== $k) {
                    continue;
                }

                // See if entropy prior to match + entropy of this match is less than
                // the current minimum top of the stack.
                $candidateEntropy = $this->prevValue($entropyStack, $match->begin) + $match->getEntropy();
                if ($candidateEntropy <= $entropyStack[$k]) {
                    $entropyStack[$k] = $candidateEntropy;
                    $backpointers[$k] = $match;
                }
            }
        }

        // Walk backwards and decode the best sequence
        $matchSequence = [];
        $k = $passwordLength - 1;
        while ($k >= 0) {
            $match = $backpointers[$k];

            if ($match) {
                $matchSequence[] = $match;

                $k = $match->begin - 1;
            } else {
                --$k;
            }
        }
        $matchSequence = array_reverse($matchSequence);

        $s = 0;
        $matchSequenceCopy = [];
        // Handle subtrings that weren't matched as bruteforce match.
        foreach ($matchSequence as $match) {
            if ($match->begin - $s > 0) {
                $matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $match->begin - 1, $bruteforceMatch->getCardinality());
            }

            $s = $match->end + 1;
            $matchSequenceCopy[] = $match;
        }

        if ($s < $passwordLength) {
            $matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $passwordLength - 1, $bruteforceMatch->getCardinality());
        }

        $this->matchSequence = $matchSequenceCopy;

        return $entropyStack[$passwordLength - 1];
    }
914976
private function getKey(array $config, $password)
    {
        $key = rtrim(file_get_contents($config['rsa_key']));
        $rsa = new \Crypt_RSA();
        if (null !== $password) {
            $rsa->setPassword($password);
        }
        $rsa->loadKey($key);

        return $rsa;
    }
630545
def minimum_entropy_match_sequence(password, matches):
    
    bruteforce_cardinality = calc_bruteforce_cardinality(password) # e.g. 26 for lowercase
    up_to_k = [0] * len(password) # minimum entropy up to k.
    # for the optimal sequence of matches up to k, holds the final match (match['j'] == k). null means the sequence ends
    # without a brute-force character.
    backpointers = []
    for k in range(0, len(password)):
        # starting scenario to try and beat: adding a brute-force character to the minimum entropy sequence at k-1.
        up_to_k[k] = get(up_to_k, k-1) + lg(bruteforce_cardinality)
        backpointers.append(None)
        for match in matches:
            if match['j'] != k:
                continue
            i, j = match['i'], match['j']
            # see if best entropy up to i-1 + entropy of this match is less than the current minimum at j.
            up_to = get(up_to_k, i-1)
            candidate_entropy = up_to + calc_entropy(match)
            if candidate_entropy < up_to_k[j]:
                #print "New minimum: using " + str(match)
                #print "Entropy: " + str(candidate_entropy)
                up_to_k[j] = candidate_entropy
                backpointers[j] = match

    # walk backwards and decode the best sequence
    match_sequence = []
    k = len(password) - 1
    while k >= 0:
        match = backpointers[k]
        if match:
            match_sequence.append(match)
            k = match['i'] - 1
        else:
            k -= 1
    match_sequence.reverse()

    # fill in the blanks between pattern matches with bruteforce "matches"
    # that way the match sequence fully covers the password: match1.j == match2.i - 1 for every adjacent match1, match2.
    def make_bruteforce_match(i, j):
        return {
            'pattern': 'bruteforce',
            'i': i,
            'j': j,
            'token': password[i:j+1],
            'entropy': lg(math.pow(bruteforce_cardinality, j - i + 1)),
            'cardinality': bruteforce_cardinality,
        }
    k = 0
    match_sequence_copy = []
    for match in match_sequence:
        i, j = match['i'], match['j']
        if i - k > 0:
            match_sequence_copy.append(make_bruteforce_match(k, i - 1))
        k = j + 1
        match_sequence_copy.append(match)

    if k < len(password):
        match_sequence_copy.append(make_bruteforce_match(k, len(password) - 1))
    match_sequence = match_sequence_copy

    min_entropy = 0 if len(password) == 0 else up_to_k[len(password) - 1] # corner case is for an empty password ''
    crack_time = entropy_to_crack_time(min_entropy)

    # final result object
    return {
        'password': password,
        'entropy': round_to_x_digits(min_entropy, 3),
        'match_sequence': match_sequence,
        'crack_time': round_to_x_digits(crack_time, 3),
        'crack_time_display': display_time(crack_time),
        'score': crack_time_to_score(crack_time),
    }
793837
public function convertPassword($password)
    {
        if (self::TYPE_PASSWORD_DIGEST === $this->getTypeValue()) {
            $password = $this->digestPassword($password);
        }

        return $password;
    }
131267
public function password($password = null) {
		while (empty($password)) {
			$password = $this->in('Password');
		}

		$this->loadModel(CLASS_USERS);
		$this->Users->addBehavior('Tools.Passwordable', ['confirm' => false]);

		/** @var \App\Model\Entity\User $entity */
		$entity = $this->Users->newEntity([
			'pwd' => $password,
		], ['validate' => false]);
		/** @var \Tools\Model\Behavior\PasswordableBehavior $Passwordable */
		$Passwordable = $this->Users->behaviors()->get('Passwordable');
		$Passwordable->beforeSave(new Event('beforeSave'), $entity, new ArrayObject());

		$this->out('Generating hash...');
		$this->hr();
		$this->out($entity->password);
		$this->hr();
	}
619315
public static function match($password, array $userInputs = [])
    {
        $groups = static::group($password);
        $matches = [];

        $k = 0;
        foreach ($groups as $group) {
            $char = $group[0];
            $length = strlen($group);

            if ($length > 2) {
                $end = $k + $length - 1;
                $token = substr($password, $k, $end + 1);
                $matches[] = new static($password, $k, $end, $token, $char);
            }
            $k += $length;
        }

        return $matches;
    }
1367923
public static function analyze($password)
	{
		$stats = array();

		$len = strlen($password);

		$stats['count'][0] = $len;
		$stats['uniqueCharacters'] = 0;
		$stats['uniqueClasses']    = 0;

		$classes   = array();
		$histogram = array();

		for ($i = 0; $i < $len; $i++)
		{
			$c = $password[$i];

			$cl = CharacterClass::match($c);

			foreach ($cl as $class)
			{
				if (empty($stats['count'][$class->name]))
				{
					$stats['count'][$class->name] = 1;
					if ($class->flag)
					{
						$stats['uniqueClasses']++;
					}
				}
				else
				{
					$stats['count'][$class->name]++;
				}
			}

			if (empty($histogram[$c]))
			{
				$histogram[$c] = 1;
				$stats['uniqueCharacters']++;
			}
			else
			{
				$histogram[$c]++;
			}
		}

		return $stats;
	}
374277
protected static function validatePassword($password) {
		if (empty($password)) {
			throw new InvalidPasswordException();
		}

		$password = \trim($password);

		if (\strlen($password) < 1) {
			throw new InvalidPasswordException();
		}

		return $password;
	}
902672
private function _hashPassword($password = null)
    {
        if (null !== $password) {
            $this->password = md5($password);
        }

        return $this->password;
    }
1043867
public function passwordNeedRehash(string $password) : bool
    {
        $options = [
            //'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM), // Never use a static salt or one that is not randomly generated.
            'cost' => 12, // the default cost is 10
        ];

        if (password_needs_rehash($this->password, PASSWORD_DEFAULT, $options)) {
            $this->password = self::passwordHash($password);
            $this->update();

            return true;
        }

        return false;
    }
409472
private function checkModeBcrypt($password, $hash)
    {
        $this->cwsDebug->titleH2('Check password hash in BCRYPT mode');
        $this->cwsDebug->labelValue('Password', $password);
        $this->cwsDebug->labelValue('Hash', $hash);

        $checkHash = crypt($password, $hash);
        $this->cwsDebug->labelValue('Check hash', $checkHash);

        $result = $this->slowEquals($hash, $checkHash);
        $this->cwsDebug->labelValue('Valid?', ($result ? 'YES!' : 'NO...'));

        return $result;
    }
1178421
public static function hash($password, $cost = null)
    {
        if ($cost === null) {
            $cost = self::DEFAULT_COST;
        }
        $prefix = sprintf('$%s$%02d$', self::PREFIX, $cost);
        $salt = self::createSalt();
        return crypt($password, $prefix.$salt);
    }
390986
public function match(array $matches) {
        $params = explode(' ', $matches[1]);
        $paramsNum = count($params);
        $this->params[] = $params[0];

        if (1 == $paramsNum) {
            return sprintf($this->defaultRegx['char'], '+');
        }
        else if (2 == $paramsNum) {
            return sprintf($this->defaultRegx[$params[1]], '+');
        }
        else if (3 == $paramsNum) {
            return sprintf($this->defaultRegx[$params[1]], $params[2] > 0 ? '{' . $params[2] . '}' : '*');
        }
        else if (4 == $paramsNum) {
            return sprintf($this->defaultRegx[$params[1]], '{' . $params[2] . ',' . $params[3] . '}');
        }
    }
221226
public function encode( $password, $salt = null )
	{
		return ( isset( $this->hasher ) ? $this->hasher->getHashedPassword( $password, $salt ) : $password );
	}
800405
protected function hashPasswordAttributes(array $attributes = array(), array $passwordAttributes = array()) {

        if (empty($passwordAttributes) || empty($attributes)) {
            return $attributes;
        }

        $result = array();
        foreach ($attributes as $key => $value) {

            if (in_array($key, $passwordAttributes) && !is_null($value)) {
                if ($value != $this->getOriginal($key)) {
                    $result[$key] = Hash::make($value);
                }
            } else {
                $result[$key] = $value;
            }
        }

        return $result;
    }
181011
public static function hashPassword($password)
    {
        # Test the message and key for string validity.
        Helpers::isString($password, 'Hash', 'hashPassword');

        return \Sodium\crypto_pwhash_scryptsalsa208sha256_str(
            $password,
            Constants::PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE,
            Constants::PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE
        );
    }
1103639
public function checkPassword($password)
    {
        $valid = static::$dispatcher->until(new CheckingPassword($this, $password));

        if ($valid !== null) {
            return $valid;
        }

        return static::$hasher->check($password, $this->password);
    }