-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathHOTPResult.php
More file actions
79 lines (67 loc) · 1.82 KB
/
HOTPResult.php
File metadata and controls
79 lines (67 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace jakobo\HOTP;
/**
* The HOTPResult Class converts an HOTP item to various forms
* Supported formats include hex, decimal, string, and HOTP
* @author Jakob Heuser (firstname)@felocity.com
* @copyright 2011-2020
* @license BSD-3-Clause
*/
class HOTPResult
{
private ?int $decimal = null;
private ?string $hex = null;
public function __construct(private string $hash)
{
}
/**
* Returns the string version of the HOTP
*/
public function toString(): string
{
return $this->hash;
}
/**
* Returns the hex version of the HOTP
*/
public function toHex(): string
{
if (!$this->hex) {
$this->hex = dechex($this->toDec());
}
return $this->hex;
}
/**
* Returns the decimal version of the HOTP
*/
public function toDec(): int
{
if (!$this->decimal) {
// store calculate decimal
$hmacResult = [];
// Convert to decimal
foreach (str_split($this->hash, 2) as $hex) {
$hmacResult[] = hexdec($hex);
}
$offset = $hmacResult[19] & 0xf;
$this->decimal = (
(($hmacResult[$offset + 0] & 0x7f) << 24) |
(($hmacResult[$offset + 1] & 0xff) << 16) |
(($hmacResult[$offset + 2] & 0xff) << 8) |
($hmacResult[$offset + 3] & 0xff)
);
}
return $this->decimal;
}
/**
* Returns the truncated decimal form of the HOTP
* @param int $length the length of the HOTP to return
* @return string
*/
public function toHOTP(int $length): string
{
$str = str_pad((string)$this->toDec(), $length, "0", STR_PAD_LEFT);
return substr($str, (-1 * $length));
}
}