ILIAS  release_8 Revision v8.25-1-g13de6a5eca6
class.ilBcryptPhpPasswordEncoder.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
27{
28 protected string $costs = '08';
29
34 public function __construct(array $config = [])
35 {
36 foreach ($config as $key => $value) {
37 if (strtolower($key) === 'cost') {
38 $this->setCosts($value);
39 }
40 }
41
42 if (!isset($config['cost']) && static::class === self::class) {
43 // Determine the costs only if they are not passed in constructor
44 $this->setCosts((string) $this->benchmarkCost());
45 }
46
47 $this->init();
48 }
49
50 protected function init(): void
51 {
52 }
53
58 public function benchmarkCost(float $time_target = 0.05): int
59 {
60 $cost = 8;
61
62 do {
63 ++$cost;
64 $start = microtime(true);
65 $encoder = new self(['cost' => (string) $cost]);
66 $encoder->encodePassword('test', '');
67 $end = microtime(true);
68 } while (($end - $start) < $time_target && $cost < 32);
69
70 return $cost;
71 }
72
73 public function getName(): string
74 {
75 return 'bcryptphp';
76 }
77
78 public function getCosts(): string
79 {
80 return $this->costs;
81 }
82
83 public function setCosts(string $costs): void
84 {
85 if ($costs !== '') {
86 $numeric_costs = (int) $costs;
87 if ($numeric_costs < 4 || $numeric_costs > 31) {
88 throw new ilPasswordException('The costs parameter of bcrypt must be in range 04-31');
89 }
90 $this->costs = sprintf('%1$02d', $numeric_costs);
91 }
92 }
93
94 public function encodePassword(string $raw, string $salt): string
95 {
96 if ($this->isPasswordTooLong($raw)) {
97 throw new ilPasswordException('Invalid password.');
98 }
99
100 return password_hash($raw, PASSWORD_BCRYPT, [
101 'cost' => $this->getCosts()
102 ]);
103 }
104
105 public function isPasswordValid(string $encoded, string $raw, string $salt): bool
106 {
107 return password_verify($raw, $encoded);
108 }
109
110 public function requiresReencoding(string $encoded): bool
111 {
112 return password_needs_rehash($encoded, PASSWORD_BCRYPT, [
113 'cost' => $this->getCosts()
114 ]);
115 }
116}
requiresReencoding(string $encoded)
Returns whether the encoded password needs to be re-encoded.
getName()
Returns a unique name/id of the concrete password encoder.
encodePassword(string $raw, string $salt)
Encodes the raw password.
isPasswordValid(string $encoded, string $raw, string $salt)
Checks a raw password against an encoded password.
Class for user password exception handling in ILIAS.
if(!array_key_exists('PATH_INFO', $_SERVER)) $config
Definition: metadata.php:85
string $key
Consumer key/client ID value.
Definition: System.php:193