Secure Password Hashing with Bcrypt
Modern password hashing using PHP's password_hash() with proper cost factor and validation
0
PHP Code
<?php
class PasswordManager {
private $cost = 12;
public function hashPassword($password) {
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => $this->cost]);
if ($hash === false) {
throw new Exception("Password hashing failed");
}
return $hash;
}
public function verifyPassword($password, $hash) {
if (password_verify($password, $hash)) {
if (password_needs_rehash($hash, PASSWORD_BCRYPT, ["cost" => $this->cost])) {
return ["valid" => true, "needs_rehash" => true];
}
return ["valid" => true, "needs_rehash" => false];
}
return ["valid" => false, "needs_rehash" => false];
}
public function getPasswordStrength($password) {
$score = 0;
$feedback = [];
if (strlen($password) >= 8) $score += 25;
else $feedback[] = "At least 8 characters";
if (preg_match("/[A-Z]/", $password)) $score += 25;
else $feedback[] = "Add uppercase letters";
if (preg_match("/[a-z]/", $password)) $score += 25;
else $feedback[] = "Add lowercase letters";
if (preg_match("/[0-9]/", $password)) $score += 15;
else $feedback[] = "Add numbers";
if (preg_match("/[^a-zA-Z0-9]/", $password)) $score += 10;
else $feedback[] = "Add special characters";
$strength = "Weak";
if ($score >= 80) $strength = "Strong";
elseif ($score >= 50) $strength = "Medium";
return ["score" => $score, "strength" => $strength, "feedback" => $feedback];
}
}
Explanation
This class provides comprehensive password management including secure hashing with bcrypt, automatic salt generation, password strength evaluation, and rehashing capability when security parameters change. The cost factor of 12 provides good security while maintaining reasonable performance.