Completed
Push — master ( 365b59...c70c47 )
by Matze
06:43
created

TOTP::timecode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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);
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 Comprehensibility introduced by
The string literal otpauth://totp/ does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
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