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

TokenMasker::unmask()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 10
c 1
b 0
f 0
ccs 6
cts 6
cp 1
crap 2
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