TOTP::intToBytestring()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
3
namespace BrainExe\Core\Authentication\TOTP;
4
5
use Base32\Base32;
6
use BrainExe\Core\Annotations\Inject;
7
use BrainExe\Core\Annotations\Service;
8
use BrainExe\Core\Util\Time;
9
10
/**
11
 * @Service
12
 */
13
class TOTP
14
{
15
16
    /**
17
     * @var string
18
     */
19
    private $label;
20
21
    /**
22
     * @var integer
23
     */
24
    private $digits;
25
26
    /**
27
     * @var string
28
     */
29
    private $digest;
30
31
    /**
32
     * @var integer
33
     */
34
    private $interval;
35
36
    /**
37
     * @Inject({
38
     *     "%totp.label%",
39
     *     "%totp.digits%",
40
     *     "%totp.digest%",
41
     *     "%totp.interval%"
42
     * })
43
     * @param string $label
44
     * @param integer $digits
45
     * @param string $digest
46
     * @param integer $interval
47
     * @param Time $time
48
     */
49 3
    public function __construct(
50
        string $label,
51
        int $digits,
52
        string $digest,
53
        int $interval,
54
        Time $time
55
    ) {
56 3
        $this->label    = $label;
57 3
        $this->digits   = $digits;
58 3
        $this->digest   = $digest;
59 3
        $this->interval = $interval;
60 3
        $this->time     = $time;
0 ignored issues
show
Bug introduced by
The property time does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
61 3
    }
62
63
    /**
64
     * @param string $secret
65
     * @param int $otp
66
     * @param int|null $timestamp
67
     * @return bool
68
     */
69 2
    public function verify(string $secret, $otp, int $timestamp = null) : bool
70
    {
71 2
        if (null === $timestamp) {
72
            $timestamp = $this->time->now();
73
        }
74
75 2
        for ($i = 0; $i <= 4; $i++) {
76 2
            $currentOtp = (int)$this->at($timestamp, $secret);
77 2
            if ((int)$otp === $currentOtp) {
78 1
                return true;
79
            }
80
81 2
            $timestamp -= $this->interval;
82
        }
83
84 1
        return false;
85
    }
86
87
    /**
88
     * @param string $secret
89
     * @return int
90
     */
91
    public function current(string $secret)
92
    {
93
        return $this->at($this->time->now(), $secret);
94
    }
95
96
    /**
97
     * @param string $secret
98
     * @return string
99
     */
100 1
    public function getUri(string $secret) : string
101
    {
102 1
        $opt = [];
103 1
        $opt['algorithm'] = $this->digest;
104 1
        $opt['digits']    = $this->digits;
105 1
        $opt['secret']    = trim(Base32::encode($secret), '=');
106 1
        $opt['period']    = $this->interval;
107
108 1
        ksort($opt, SORT_STRING);
109
110 1
        $params = str_replace(['+', '%7E'], ['%20', '~'], http_build_query($opt));
111
112 1
        return 'otpauth://totp/' . rawurlencode($this->label) . "?$params";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $params instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
113
    }
114
115
    /**
116
     * @param int $timestamp
117
     * @param string $secret
118
     * @return int
119
     */
120 2
    private function at($timestamp, $secret)
121
    {
122 2
        return $this->generateOTP($this->timecode($timestamp), $secret);
123
    }
124
125
    /**
126
     * @param integer $input
127
     * @param string $secret
128
     * @return int
129
     */
130 2
    private function generateOTP($input, $secret)
131
    {
132 2
        $hash = hash_hmac($this->digest, $this->intToBytestring($input), $secret);
133 2
        $hmac = [];
134
135 2
        foreach (str_split($hash, 2) as $hex) {
136 2
            $hmac[] = hexdec($hex);
137
        }
138
139 2
        $offset = $hmac[19] & 0xf;
140 2
        $code = ($hmac[$offset + 0] & 0x7F) << 24 |
141 2
                ($hmac[$offset + 1] & 0xFF) << 16 |
142 2
                ($hmac[$offset + 2] & 0xFF) << 8 |
143 2
                ($hmac[$offset + 3] & 0xFF);
144
145 2
        return $code % pow(10, $this->digits);
146
    }
147
148
    /**
149
     * @param int $timestamp
150
     * @return int
151
     */
152 2
    private function timecode($timestamp)
153
    {
154 2
        return (int)(((int)$timestamp * 1000) / ($this->interval * 1000));
155
    }
156
157
    /**
158
     * @param int $int
159
     * @return string
160
     */
161 2
    private function intToBytestring($int)
162
    {
163 2
        $result = [];
164 2
        while ($int != 0) {
165 2
            $result[] = chr($int & 0xFF);
166 2
            $int >>= 8;
167
        }
168
169 2
        return str_pad(implode(array_reverse($result)), 8, "\000", STR_PAD_LEFT);
170
    }
171
}
172