Passed
Push — master ( 691abb...b68521 )
by Tony Karavasilev (Тони
10:37
created

TokenGenerator::getPasswordCharacter()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 4
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Utility class for cryptography key and token generation.
5
 */
6
7
namespace CryptoManana\Utilities;
8
9
use \CryptoManana\Core\Abstractions\Containers\AbstractRandomnessInjectable as RandomnessContainer;
10
use \CryptoManana\Core\Interfaces\Randomness\EncryptionKeyGenerationInterface as EncryptionKeyGeneration;
11
use \CryptoManana\Core\Interfaces\Randomness\HashingKeyGenerationInterface as HashingKeyGeneration;
12
use \CryptoManana\Core\Interfaces\Randomness\TokenGenerationInterface as TokenStringGeneration;
13
use \CryptoManana\Core\StringBuilder as StringBuilder;
14
15
/**
16
 * Class TokenGenerator - Utility class for cryptography token generation.
17
 *
18
 * @package CryptoManana\Utilities
19
 *
20
 * @property \CryptoManana\Core\Abstractions\Randomness\AbstractGenerator $randomnessSource
21
 */
22
class TokenGenerator extends RandomnessContainer implements
23
    TokenStringGeneration,
24
    HashingKeyGeneration,
25
    EncryptionKeyGeneration
26
{
27
    /**
28
     * Internal method for validation of positive output length.
29
     *
30
     * @param int $length The output length value for validation.
31
     *
32
     * @throws \Exception Validation errors.
33
     */
34 9
    protected function applyLengthValidation($length)
35
    {
36 9
        $length = filter_var(
37 9
            $length,
38 9
            FILTER_VALIDATE_INT,
39
            [
40
                "options" => [
41 9
                    "min_range" => 1,
42 9
                    "max_range" => PHP_INT_MAX,
43
                ],
44
            ]
45
        );
46
47 9
        if ($length === false) {
48 1
            throw new \LengthException(
49 1
                'The length of the desired output data must me at least 1 character long.'
50
            );
51
        }
52 8
    }
53
54
    /**
55
     * Internal method for generation of characters used for secure password string building.
56
     *
57
     * @param int|mixed $case Generation case as integer.
58
     *
59
     * @return string Password character.
60
     * @throws \Exception Validation Errors.
61
     */
62 1
    protected function getPasswordCharacter($case)
63
    {
64
        switch ($case) {
65 1
            case 1:
66 1
                return $this->randomnessSource->getDigit(true);
67 1
            case 2:
68 1
                return $this->randomnessSource->getLetter(false);
69 1
            case 3:
70 1
                return StringBuilder::stringToUpper($this->randomnessSource->getLetter(false));
71
72
            default:
73 1
                return $this->randomnessSource->getString(1, ['!', '@', '#', '$', '%', '^']);
74
        }
75
    }
76
77
    /**
78
     * Generate a random token string in alphanumeric or hexadecimal format.
79
     *
80
     * Note: This method can generate HEX output if the `$useAlphaNumeric` parameter is set to `false`.
81
     *
82
     * @param int $length The desired output length (default => 40).
83
     * @param bool|int $useAlphaNumeric Flag for switching to alphanumerical (default => true).
84
     *
85
     * @return string Randomly generated alphanumeric/hexadecimal token string.
86
     * @throws \Exception Validation errors.
87
     */
88 4
    public function getTokenString($length = 40, $useAlphaNumeric = true)
89
    {
90 4
        $this->applyLengthValidation($length);
91
92 3
        if ($useAlphaNumeric) {
93 3
            $token = $this->randomnessSource->getAlphaNumeric($length, true);
94
        } else {
95 1
            $token = $this->randomnessSource->getHex($length, true);
96
        }
97
98 3
        return StringBuilder::stringReverse($token);
99
    }
100
101
    /**
102
     * Generate a random password string.
103
     *
104
     * Note: This method can use more special symbols on generation if the `$stronger` parameter is set to `true`.
105
     *
106
     * @param int $length The desired output length (default => 10).
107
     * @param bool|int $stronger Flag for using all printable ASCII characters (default => true).
108
     *
109
     * @return string Randomly generated password string.
110
     * @throws \Exception Validation errors.
111
     */
112 1
    public function getPasswordString($length = 10, $stronger = true)
113
    {
114 1
        $this->applyLengthValidation($length);
115
116 1
        if ($stronger) {
117 1
            $password = $this->randomnessSource->getAscii($length);
118
        } else {
119 1
            $password = '';
120
121 1
            for ($i = 1; $i <= $length; $i++) {
122 1
                $case = $this->randomnessSource->getInt(1, 4);
123
124 1
                $password .= $this->getPasswordCharacter($case);
125
            }
126
        }
127
128 1
        return $password;
129
    }
130
131
    /**
132
     * Generate a random HMAC key for hashing purposes.
133
     *
134
     * Note: The output string can be in raw bytes of the `$printable` parameter is set to `true`.
135
     *
136
     * @param int $length The desired output length (default => 128).
137
     * @param bool|int $printable Flag for using only printable characters instead of bytes (default => true).
138
     *
139
     * @return string Randomly generated HMAC key.
140
     * @throws \Exception Validation errors.
141
     */
142 1
    public function getHashingKey($length = 128, $printable = true)
143
    {
144 1
        $this->applyLengthValidation($length);
145
146 1
        return ($printable) ? $this->randomnessSource->getAscii($length) : $this->randomnessSource->getBytes($length);
147
    }
148
149
    /**
150
     * Generate a random salt string for hashing purposes.
151
     *
152
     * Note: The output string can be in raw bytes of the `$printable` parameter is set to `true`.
153
     *
154
     * @param int $length The desired output length (default => 128).
155
     * @param bool|int $printable Flag for using only printable characters instead of bytes (default => true).
156
     *
157
     * @return string Randomly generated hashing salt.
158
     * @throws \Exception Validation errors.
159
     */
160 1
    public function getHashingSalt($length = 128, $printable = true)
161
    {
162 1
        $this->applyLengthValidation($length);
163
164 1
        return ($printable) ? $this->randomnessSource->getAscii($length) : $this->randomnessSource->getBytes($length);
165
    }
166
167
    /**
168
     * Generate a random encryption key for symmetrical cyphers.
169
     *
170
     * Note: The output string can be in raw bytes of the `$printable` parameter is set to `true`.
171
     *
172
     * @param int $length The desired output length (default => 128).
173
     * @param bool|int $printable Flag for using only printable characters instead of bytes (default => true).
174
     *
175
     * @return string Randomly generated encryption key.
176
     * @throws \Exception Validation errors.
177
     */
178 1
    public function getEncryptionKey($length = 128, $printable = true)
179
    {
180 1
        $this->applyLengthValidation($length);
181
182 1
        return ($printable) ? $this->randomnessSource->getAscii($length) : $this->randomnessSource->getBytes($length);
183
    }
184
185
    /**
186
     * Generate a random initialization vector (IV) for encryption purposes.
187
     *
188
     * Note: The output string can be in raw bytes of the `$printable` parameter is set to `true`.
189
     *
190
     * @param int $length The desired output length (default => 128).
191
     * @param bool|int $printable Flag for using only printable characters instead of bytes (default => true).
192
     *
193
     * @return string Randomly generated encryption initialization vector.
194
     * @throws \Exception Validation errors.
195
     */
196 1
    public function getEncryptionInitializationVector($length = 128, $printable = true)
197
    {
198 1
        $this->applyLengthValidation($length);
199
200 1
        return ($printable) ? $this->randomnessSource->getAscii($length) : $this->randomnessSource->getBytes($length);
201
    }
202
}
203