PHP
Secure Password Hashing - حماية متقدمة
نظام متقدم لتشفير كلمات المرور مع Salt، Pepper، وAdaptive Hashing. مقاوم لـ Rainbow Tables وBrute Force.
class SecurePasswordHasher {
private string $pepper;
private int $cost;
public function __construct(string $pepper, int $cost = 12) {
$this->pepper = $pepper;
$this->cost = $cost;
}
public function hash(string $password): string {
// Generate unique salt
$salt = bin2hex(random_bytes(16));
// Add pepper (application-level secret)
$passwordWithPepper = hash_hmac('sha256', $password, $this->pepper);
// Hash with bcrypt (adaptive)
$hash = password_hash($passwordWithPepper, PASSWORD_BCRYPT, [
'cost' => $this->cost
]);
// Store salt with hash
return $salt . ':' . $hash;
}
public function verify(string $password, string $storedHash): bool {
[$salt, $hash] = explode(':', $storedHash, 2);
// Reconstruct password with pepper
$passwordWithPepper = hash_hmac('sha256', $password, $this->pepper);
return password_verify($passwordWithPepper, $hash);
}
public function needsRehash(string $storedHash): bool {
[$salt, $hash] = explode(':', $storedHash, 2);
return password_needs_rehash($hash, PASSWORD_BCRYPT, [
'cost' => $this->cost
]);
}
// Advanced: Time-safe comparison
public function constantTimeCompare(string $a, string $b): bool {
if (strlen($a) !== strlen($b)) {
return false;
}
$result = 0;
for ($i = 0; $i < strlen($a); $i++) {
$result |= ord($a[$i]) ^ ord($b[$i]);
}
return $result === 0;
}
}
// Usage
$hasher = new SecurePasswordHasher('your-secret-pepper', 12);
$hash = $hasher->hash('user_password');
$isValid = $hasher->verify('user_password', $hash);
💡 مثال الاستخدام
استخدم Secure Hashing لحماية كلمات المرور في التطبيقات، APIs، أو أنظمة Authentication.
استخدام حر
هذا الكود متاح للاستخدام الحر. إذا كان لديك أسئلة أو تحتاج مساعدة، لا تتردد في التواصل معي.