-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathEncodeHS256Strong.php
More file actions
50 lines (42 loc) · 1.36 KB
/
EncodeHS256Strong.php
File metadata and controls
50 lines (42 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace ReallySimpleJWT\Encoders;
use ReallySimpleJWT\Exception\EncodeException;
/**
* An implementation of EncodeHS256 which enforces a strong secret. This will
* generate more secure tokens.
*/
class EncodeHS256Strong extends EncodeHS256
{
/**
* This class only instantiates if the secret provided is strong enough.
*/
public function __construct(string $secret, array $options)
{
if (!$this->validSecret($secret, !!$options['fixed_secret_length_enabled'])) {
throw new EncodeException('Invalid secret.', 9);
}
parent::__construct($secret);
}
/**
* The secret should contain a number, a upper and a lowercase letter, and a
* special character *&!@%^#$. It should be at least 12 characters in
* length. The regex here uses lookahead assertions.
* nonEmptyOnlyValidation is an option to only validate secret is empty or not.
*/
private function validSecret(string $secret, bool $fixedSecretLengthEnabled = true): bool
{
if (!$fixedSecretLengthEnabled) {
return !empty($secret);
}
if (
!preg_match(
'/^.*(?=.{12,}+)(?=.*\d+)(?=.*[A-Z]+)(?=.*[a-z]+)(?=.*[\*&!@%\^#\$]+).*$/',
$secret
)
) {
return false;
}
return true;
}
}