OathTrait::oathHotp()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/2fa-library project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\TwoFA\Traits;
13
14
trait OathTrait
15
{
16
    /**
17
     * @var int the length of the time based one time password token generated. Defaults to 6.
18
     */
19
    protected $tokenLength = 6;
20
21
    /**
22
     * Takes the secret key and the timestamp and returns the one time password.
23
     *
24
     * @param string $seed    the secret key in binary form
25
     * @param string $counter the time as returned by getTimestamp
26
     *
27
     * @return string
28
     */
29
    protected function oathHotp(string $seed, string $counter): string
30
    {
31
        // Counter must be 64-bit int
32
        $bin_counter = pack('N*', 0, $counter);
33
        $hash = hash_hmac('sha1', $bin_counter, $seed, true);
34
35
        return str_pad($this->oathTruncate($hash), $this->tokenLength, '0', STR_PAD_LEFT);
36
    }
37
38
    /**
39
     * Extracts the OTP from the SHA1 hash.
40
     *
41
     * @param string $hash
42
     *
43
     * @return int
44
     **/
45
    protected function oathTruncate(string $hash): int
46
    {
47
        $offset = ord($hash[19]) & 0xf;
48
        $temp = unpack('N', substr($hash, $offset, 4));
49
50
        return substr($temp[1] & 0x7fffffff, -$this->tokenLength);
51
    }
52
}
53