Passed
Push — master ( bdfe7b...8f2aab )
by Alexander
01:12
created

TokenMasker   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
dl 0
loc 31
rs 10
c 1
b 0
f 0
ccs 9
cts 9
cp 1
wmc 3

2 Methods

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