SimpleSAML\Utils\Crypto::pwHash PHP Method

pwHash() public static method

This function hashes a password with a given algorithm.
See also: hash_algos()
Author: Dyonisius Visser, TERENA ([email protected])
Author: Jaime Perez, UNINETT AS ([email protected])
public static pwHash ( string $password, string $algorithm, string $salt = null ) : string
$password string The password to hash.
$algorithm string The hashing algorithm, uppercase, optionally prepended with 'S' (salted). See hash_algos() for a complete list of hashing algorithms.
$salt string An optional salt to use.
return string The hashed password.
    public static function pwHash($password, $algorithm, $salt = null)
    {
        if (!is_string($algorithm) || !is_string($password)) {
            throw new \InvalidArgumentException('Invalid input parameters.');
        }
        // hash w/o salt
        if (in_array(strtolower($algorithm), hash_algos())) {
            $alg_str = '{' . str_replace('SHA1', 'SHA', $algorithm) . '}';
            // LDAP compatibility
            $hash = hash(strtolower($algorithm), $password, true);
            return $alg_str . base64_encode($hash);
        }
        // hash w/ salt
        if ($salt === null) {
            // no salt provided, generate one
            // default 8 byte salt, but 4 byte for LDAP SHA1 hashes
            $bytes = $algorithm == 'SSHA1' ? 4 : 8;
            $salt = openssl_random_pseudo_bytes($bytes);
        }
        if ($algorithm[0] == 'S' && in_array(substr(strtolower($algorithm), 1), hash_algos())) {
            $alg = substr(strtolower($algorithm), 1);
            // 'sha256' etc
            $alg_str = '{' . str_replace('SSHA1', 'SSHA', $algorithm) . '}';
            // LDAP compatibility
            $hash = hash($alg, $password . $salt, true);
            return $alg_str . base64_encode($hash . $salt);
        }
        throw new \SimpleSAML_Error_Exception('Hashing algorithm \'' . strtolower($algorithm) . '\' is not supported');
    }