OathTrait   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 2
lcom 1
cbo 0
dl 0
loc 40
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A oathHotp() 0 8 1
A oathTruncate() 0 7 1
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
use Da\TwoFA\Exception\InvalidSecretKeyException;
15
16
trait OathTrait
17
{
18
    /**
19
     * @var int the length of the time based one time password token generated. Defaults to 6.
20
     */
21
    protected $tokenLength = 6;
22
23
    /**
24
     * Takes the secret key and the timestamp and returns the one time password.
25
     *
26
     * @param string $seed    the secret key in binary form
27
     * @param string $counter the time as returned by getTimestamp
28
     *
29
     * @throws InvalidSecretKeyException
30
     * @return string
31
     */
32
    protected function oathHotp($seed, $counter)
33
    {
34
        // Counter must be 64-bit int
35
        $bin_counter = pack('N*', 0, $counter);
36
        $hash = hash_hmac('sha1', $bin_counter, $seed, true);
37
38
        return str_pad($this->oathTruncate($hash), $this->tokenLength, '0', STR_PAD_LEFT);
39
    }
40
41
    /**
42
     * Extracts the OTP from the SHA1 hash.
43
     *
44
     * @param string $hash
45
     *
46
     * @return int
47
     **/
48
    protected function oathTruncate($hash)
49
    {
50
        $offset = ord($hash[19]) & 0xf;
51
        $temp = unpack('N', substr($hash, $offset, 4));
52
53
        return substr($temp[1] & 0x7fffffff, -$this->tokenLength);
54
    }
55
}
56