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');
}