Encoder   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 79
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A generateBase32RandomKey() 0 9 2
A toBase32() 0 6 1
A fromBase32() 0 8 1
A getRandomNumber() 0 4 1
A strPadBase32() 0 8 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\Support;
13
14
use Da\TwoFA\Contracts\TotpEncoderInterface;
15
use Da\TwoFA\Traits\SecretValidationTrait;
16
use Da\TwoFA\Validator\SecretKeyValidator;
17
use ParagonIE\ConstantTime\Base32;
18
19
class Encoder implements TotpEncoderInterface
20
{
21
    use SecretValidationTrait;
22
23
    /**
24
     * Encoder constructor.
25
     *
26
     * @param SecretKeyValidator|null $secretKeyValidator
27
     */
28
    public function __construct(SecretKeyValidator $secretKeyValidator = null)
29
    {
30
        $this->secretKeyValidator = $secretKeyValidator ?: new SecretKeyValidator();
31
    }
32
33
    /**
34
     * @inheritdoc
35
     */
36
    public function generateBase32RandomKey($length = 16, $prefix = '')
37
    {
38
        $secret = $prefix ? $this->toBase32($prefix) : '';
39
        $secret = $this->strPadBase32($secret, $length);
40
41
        $this->validateSecret($secret);
42
43
        return $secret;
44
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function toBase32($value)
50
    {
51
        $encoded = Base32::encodeUpper($value);
52
53
        return str_replace('=', '', $encoded);
54
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59
    public function fromBase32($value)
60
    {
61
        $value = strtoupper($value);
62
63
        $this->validateSecret($value);
64
65
        return Base32::decodeUpper($value);
66
    }
67
68
    /**
69
     * Get a random number.
70
     *
71
     * @param $from
72
     * @param $to
73
     *
74
     * @return int
75
     */
76
    protected function getRandomNumber($from = 0, $to = 31)
77
    {
78
        return random_int($from, $to);
79
    }
80
81
    /**
82
     * Pad string with random base 32 chars.
83
     *
84
     * @param $string
85
     * @param $length
86
     *
87
     * @return string
88
     */
89
    private function strPadBase32($string, $length)
90
    {
91
        for ($i = 0; $i < $length; $i++) {
92
            $string .= substr('234567QWERTYUIOPASDFGHJKLZXCVBNM', $this->getRandomNumber(), 1);
93
        }
94
95
        return $string;
96
    }
97
}
98