I've constructed a simple class whose entire purpose is to hash passwords securely and simply.
The catch is the PHP version is probably going to be 5.2.x. This means:
- No
CRYPT_BLOWFISH
- Obviously no
password_hash()
.
The question is, is the following secure? Can it be improved?
/**
* Class Hasher
*
* @package Dependencies\Hasher
*
* Defines hashing mechanism for password saving.
*/
class Hasher {
/**
* @param string $string String for hashing
* @param string $salt Unique salt. The salt is best kept as a very long, very random string.
* @param int $cost Cost parameter. 2^$cost iterations over the hashing algorithm.
*
* @return string
*/
public function algo($string, $salt, $cost) {
$iterations = pow(2, $cost);
$result = "";
for ($i = 0; $i < $iterations; $i++) {
$result = sha1($result . $salt . $string);
}
return $result;
}
/**
* Pass a password through the hashing algorithm. And return the result.
*
* @param string $password
* @param string $salt
* @param int $cost
*
* @return string
*/
public final function hash($password, $salt, $cost = 10) {
return $this->algo($password, $salt, $cost);
}
/**
* Match password through the hashing algorithm against an existing hash to make sure there's a match.
*
* @param string $hash
* @param string $password
* @param string $salt
* @param int $cost
*
* @return bool
*/
public final function verify($hash, $password, $salt, $cost = 10) {
return $this->algo($password, $salt, $cost) == $hash;
}
}