|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace SumoCoders\FrameworkCoreBundle\Security; |
| 4 | + |
| 5 | +/** |
| 6 | + * This service can be used to estimate the strength of a password. |
| 7 | + * It's based on the private static method Symfony\Component\Validator\Constraints\PasswordStrengthValidator::estimateStrength. |
| 8 | + */ |
| 9 | +class PasswordStrengthService |
| 10 | +{ |
| 11 | + public const STRENGTH_VERY_WEAK = 0; |
| 12 | + public const STRENGTH_WEAK = 1; |
| 13 | + public const STRENGTH_MEDIUM = 2; |
| 14 | + public const STRENGTH_STRONG = 3; |
| 15 | + public const STRENGTH_VERY_STRONG = 4; |
| 16 | + |
| 17 | + /** |
| 18 | + * Returns the estimated strength of a password. |
| 19 | + * |
| 20 | + * The higher the value, the stronger the password. |
| 21 | + * |
| 22 | + * @return PasswordStrength::STRENGTH_* |
| 23 | + */ |
| 24 | + public function estimateStrength( |
| 25 | + string $password |
| 26 | + ): int { |
| 27 | + if (!$length = \strlen($password)) { |
| 28 | + return self::STRENGTH_VERY_WEAK; |
| 29 | + } |
| 30 | + $password = count_chars($password, 1); |
| 31 | + $chars = \count($password); |
| 32 | + |
| 33 | + $control = $digit = $upper = $lower = $symbol = $other = 0; |
| 34 | + foreach ($password as $chr => $count) { |
| 35 | + match (true) { |
| 36 | + $chr < 32 || 127 === $chr => $control = 33, |
| 37 | + 48 <= $chr && $chr <= 57 => $digit = 10, |
| 38 | + 65 <= $chr && $chr <= 90 => $upper = 26, |
| 39 | + 97 <= $chr && $chr <= 122 => $lower = 26, |
| 40 | + 128 <= $chr => $other = 128, |
| 41 | + default => $symbol = 33, |
| 42 | + }; |
| 43 | + } |
| 44 | + |
| 45 | + $pool = $lower + $upper + $digit + $symbol + $control + $other; |
| 46 | + $entropy = $chars * log($pool, 2) + ($length - $chars) * log($chars, 2); |
| 47 | + |
| 48 | + return match (true) { |
| 49 | + $entropy >= 120 => self::STRENGTH_VERY_STRONG, |
| 50 | + $entropy >= 100 => self::STRENGTH_STRONG, |
| 51 | + $entropy >= 80 => self::STRENGTH_MEDIUM, |
| 52 | + $entropy >= 60 => self::STRENGTH_WEAK, |
| 53 | + default => self::STRENGTH_VERY_WEAK, |
| 54 | + }; |
| 55 | + } |
| 56 | +} |
0 commit comments