86 lines
2.8 KiB
PHP
86 lines
2.8 KiB
PHP
<?php
|
|
namespace App\Helpers;
|
|
|
|
/**
|
|
* Class Argon2Hasher
|
|
* Enterprise Argon2id Password Hashing & Password Policy Guard
|
|
*
|
|
* @package App\Helpers
|
|
*/
|
|
class Argon2Hasher
|
|
{
|
|
/**
|
|
* Hash a plaintext password using Argon2id
|
|
*
|
|
* @param string $password Plaintext password
|
|
* @return string Hashed password
|
|
*/
|
|
public static function hash(string $password): string
|
|
{
|
|
return password_hash($password, PASSWORD_ARGON2ID, [
|
|
'memory_cost' => 65536, // 64 MB
|
|
'time_cost' => 4, // 4 passes
|
|
'threads' => 1,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Verify plaintext password against Argon2id hash
|
|
*
|
|
* @param string $password Plaintext password
|
|
* @param string $hash Hashed password stored in database
|
|
* @return bool
|
|
*/
|
|
public static function verify(string $password, string $hash): bool
|
|
{
|
|
if (empty($hash)) return false;
|
|
return password_verify($password, $hash);
|
|
}
|
|
|
|
/**
|
|
* Check if password needs rehash due to upgraded algorithm or parameters
|
|
*
|
|
* @param string $hash
|
|
* @return bool
|
|
*/
|
|
public static function needsRehash(string $hash): bool
|
|
{
|
|
return password_needs_rehash($hash, PASSWORD_ARGON2ID, [
|
|
'memory_cost' => 65536,
|
|
'time_cost' => 4,
|
|
'threads' => 1,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Validate Password Strength against Enterprise Security Policy
|
|
*
|
|
* @param string $password
|
|
* @return array ['valid' => bool, 'errors' => array]
|
|
*/
|
|
public static function validatePolicy(string $password): array
|
|
{
|
|
$errors = [];
|
|
if (strlen($password) < 8) {
|
|
$errors[] = "รหัสผ่านต้องมีความยาวอย่างน้อย 8 ตัวอักษร";
|
|
}
|
|
if (!preg_match('/[A-Z]/', $password)) {
|
|
$errors[] = "รหัสผ่านต้องมีตัวอักษรภาษาอังกฤษพิมพ์ใหญ่อย่างน้อย 1 ตัว (A-Z)";
|
|
}
|
|
if (!preg_match('/[a-z]/', $password)) {
|
|
$errors[] = "รหัสผ่านต้องมีตัวอักษรภาษาอังกฤษพิมพ์เล็กอย่างน้อย 1 ตัว (a-z)";
|
|
}
|
|
if (!preg_match('/[0-9]/', $password)) {
|
|
$errors[] = "รหัสผ่านต้องมีตัวเลขอย่างน้อย 1 ตัว (0-9)";
|
|
}
|
|
if (!preg_match('/[\W_]/', $password)) {
|
|
$errors[] = "รหัสผ่านต้องมีอักขระพิเศษอย่างน้อย 1 ตัว (!@#$%^&* เป็นต้น)";
|
|
}
|
|
|
|
return [
|
|
'valid' => empty($errors),
|
|
'errors' => $errors,
|
|
];
|
|
}
|
|
}
|