1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Yiisoft\Security; |
||
6 | |||
7 | use Yiisoft\Strings\StringHelper; |
||
8 | |||
9 | /** |
||
10 | * TokenMask helps to mitigate BREACH attack by randomizing how token is outputted on each request. |
||
11 | * A random mask is applied to the token making the string always unique. |
||
12 | */ |
||
13 | final class TokenMask |
||
14 | { |
||
15 | /** |
||
16 | * Masks a token to make it incompressible. |
||
17 | * Applies a random mask to the token and prepends the mask used to the result making the string always unique. |
||
18 | * |
||
19 | * @param string $token An unmasked token. |
||
20 | * |
||
21 | * @throws \Exception if unable to securely generate random bytes |
||
22 | * |
||
23 | * @return string A masked token. |
||
24 | */ |
||
25 | 5 | public static function apply(string $token): string |
|
26 | { |
||
27 | // The number of bytes in a mask is always equal to the number of bytes in a token. |
||
28 | /** @psalm-suppress ArgumentTypeCoercion */ |
||
29 | 5 | $mask = random_bytes(StringHelper::byteLength($token)); |
|
30 | 4 | return StringHelper::base64UrlEncode($mask . ($mask ^ $token)); |
|
31 | } |
||
32 | |||
33 | /** |
||
34 | * Unmasks a token previously masked by `mask`. |
||
35 | * |
||
36 | * @param string $maskedToken A masked token. |
||
37 | * |
||
38 | * @return string An unmasked token, or an empty string in case of token format is invalid. |
||
39 | */ |
||
40 | 6 | public static function remove(string $maskedToken): string |
|
41 | { |
||
42 | 6 | $decoded = StringHelper::base64UrlDecode($maskedToken); |
|
43 | 6 | $length = StringHelper::byteLength($decoded) / 2; |
|
44 | // Check if the masked token has an even length. |
||
45 | 6 | if (!is_int($length)) { |
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
46 | 1 | return ''; |
|
47 | } |
||
48 | |||
49 | 5 | return StringHelper::byteSubstring($decoded, $length, $length) ^ StringHelper::byteSubstring($decoded, 0, $length); |
|
50 | } |
||
51 | } |
||
52 |