Completed
Push — master ( 74fb3f...4060a7 )
by Antonio
14:22
created

Encoder::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 2
eloc 2
nc 2
nop 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\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