44 lines
1.4 KiB
PHP
44 lines
1.4 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace MailAccountAdmin\Common;
|
|
|
|
class PasswordHelper
|
|
{
|
|
public function hashPassword(string $password): string
|
|
{
|
|
return password_hash($password, PASSWORD_DEFAULT);
|
|
}
|
|
|
|
public function verifyPassword(string $password, string $hash): bool
|
|
{
|
|
return password_verify($password, $hash);
|
|
}
|
|
|
|
public function getPasswordHashType(string $passwordHash): string
|
|
{
|
|
if ($passwordHash === '') {
|
|
return 'empty';
|
|
}
|
|
|
|
$passwordHashInfo = password_get_info($passwordHash);
|
|
return $passwordHashInfo['algoName'] ?? 'unknown';
|
|
}
|
|
|
|
public function generateRandomPassword(int $length = 24): string
|
|
{
|
|
// We want a random string of alphanumeric characters. Simple way to do this is to get random bytes, convert them to base64,
|
|
// strip all characters from it that aren't alphanumeric (+, /, =), and take the first $length characters from it.
|
|
|
|
// Get lots of random bytes (will be much more than we need, but this way we don't need to worry about the string being too short
|
|
// after stripping the non-alphanumeric base64 characters).
|
|
$randomBytes = random_bytes(2 * $length);
|
|
|
|
// Convert to base64 and strip non-alphanumeric characters
|
|
$randomAlphaNumeric = str_replace(['+', '/', '='], '', base64_encode($randomBytes));
|
|
|
|
// Shorten string
|
|
return substr($randomAlphaNumeric, 0, $length);
|
|
}
|
|
}
|