ILIAS  release_6 Revision v6.24-5-g0c8bfefb3b8
class.ilBcryptPhpPasswordEncoder.php
Go to the documentation of this file.
1<?php declare(strict_types=1);
2/* Copyright (c) 1998-2016 ILIAS open source, Extended GPL, see docs/LICENSE */
3
4require_once 'Services/Password/classes/class.ilBasePasswordEncoder.php';
5
12{
16 protected $costs = '08';
17
22 public function __construct(array $config = [])
23 {
24 if (!empty($config)) {
25 foreach ($config as $key => $value) {
26 switch (strtolower($key)) {
27 case 'cost':
28 $this->setCosts($value);
29 break;
30 }
31 }
32 }
33
34 if (!isset($config['cost']) && static::class == self::class) {
35 // Determine the costs only if they are not passed in constructor
36 $this->setCosts((string) $this->benchmarkCost(0.05));
37 }
38
39 $this->init();
40 }
41
45 protected function init() : void
46 {
47 }
48
55 public function benchmarkCost(float $time_target = 0.05) : int
56 {
57 $cost = 8;
58
59 do {
60 $cost++;
61 $start = microtime(true);
62 $encoder = new self(['cost' => (string) $cost]);
63 $encoder->encodePassword('test', '');
64 $end = microtime(true);
65 } while (($end - $start) < $time_target && $cost < 32);
66
67 return $cost;
68 }
69
73 public function getName() : string
74 {
75 return 'bcryptphp';
76 }
77
81 public function isSupportedByRuntime() : bool
82 {
83 return parent::isSupportedByRuntime() && version_compare(phpversion(), '5.5.0', '>=');
84 }
85
89 public function getCosts() : string
90 {
91 return $this->costs;
92 }
93
98 public function setCosts(string $costs) : void
99 {
100 if (!empty($costs)) {
101 $costs = (int) $costs;
102 if ($costs < 4 || $costs > 31) {
103 throw new ilPasswordException('The costs parameter of bcrypt must be in range 04-31');
104 }
105 $this->costs = sprintf('%1$02d', $costs);
106 }
107 }
108
113 public function encodePassword(string $raw, string $salt) : string
114 {
115 if ($this->isPasswordTooLong($raw)) {
116 throw new ilPasswordException('Invalid password.');
117 }
118
119 return password_hash($raw, PASSWORD_BCRYPT, [
120 'cost' => $this->getCosts()
121 ]);
122 }
123
127 public function isPasswordValid(string $encoded, string $raw, string $salt) : bool
128 {
129 return password_verify($raw, $encoded);
130 }
131
135 public function requiresReencoding(string $encoded) : bool
136 {
137 return password_needs_rehash($encoded, PASSWORD_BCRYPT, [
138 'cost' => $this->getCosts()
139 ]);
140 }
141}
An exception for terminatinating execution or to throw for unit testing.
isPasswordTooLong(string $password)
Checks if the password is too long.
requiresReencoding(string $encoded)
@inheritDoc
encodePassword(string $raw, string $salt)
@inheritDoc
isPasswordValid(string $encoded, string $raw, string $salt)
@inheritDoc
Class for user password exception handling in ILIAS.
if(!array_key_exists('PATH_INFO', $_SERVER)) $config
Definition: metadata.php:68