ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
PasswordHasher.php
Go to the documentation of this file.
1 <?php
2 
4 
7 
9 {
13  private static function getAlgorithm(string $algorithmName): string
14  {
15  if (!$algorithmName) {
16  return '';
17  }
18 
19  // Mapping between algorithm name in Excel and algorithm name in PHP
20  $mapping = [
28  Protection::ALGORITHM_RIPEMD_128 => 'ripemd128',
29  Protection::ALGORITHM_RIPEMD_160 => 'ripemd160',
30  Protection::ALGORITHM_WHIRLPOOL => 'whirlpool',
31  ];
32 
33  if (array_key_exists($algorithmName, $mapping)) {
34  return $mapping[$algorithmName];
35  }
36 
37  throw new Exception('Unsupported password algorithm: ' . $algorithmName);
38  }
39 
49  private static function defaultHashPassword(string $pPassword): string
50  {
51  $password = 0x0000;
52  $charPos = 1; // char position
53 
54  // split the plain text password in its component characters
55  $chars = preg_split('//', $pPassword, -1, PREG_SPLIT_NO_EMPTY);
56  foreach ($chars as $char) {
57  $value = ord($char) << $charPos++; // shifted ASCII value
58  $rotated_bits = $value >> 15; // rotated bits beyond bit 15
59  $value &= 0x7fff; // first 15 bits
60  $password ^= ($value | $rotated_bits);
61  }
62 
63  $password ^= strlen($pPassword);
64  $password ^= 0xCE4B;
65 
66  return strtoupper(dechex($password));
67  }
68 
83  public static function hashPassword(string $password, string $algorithm = '', string $salt = '', int $spinCount = 10000): string
84  {
85  $phpAlgorithm = self::getAlgorithm($algorithm);
86  if (!$phpAlgorithm) {
87  return self::defaultHashPassword($password);
88  }
89 
90  $saltValue = base64_decode($salt);
91  $encodedPassword = mb_convert_encoding($password, 'UCS-2LE', 'UTF-8');
92 
93  $hashValue = hash($phpAlgorithm, $saltValue . $encodedPassword, true);
94  for ($i = 0; $i < $spinCount; ++$i) {
95  $hashValue = hash($phpAlgorithm, $hashValue . pack('L', $i), true);
96  }
97 
98  return base64_encode($hashValue);
99  }
100 }
static defaultHashPassword(string $pPassword)
Create a password hash from a given string.
static hashPassword(string $password, string $algorithm='', string $salt='', int $spinCount=10000)
Create a password hash from a given string by a specific algorithm.
$password
Definition: cron.php:14
static getAlgorithm(string $algorithmName)
Get algorithm name for PHP.
$i
Definition: disco.tpl.php:19
hash(StreamInterface $stream, $algo, $rawOutput=false)
Calculate a hash of a Stream.
Definition: functions.php:406