-
Notifications
You must be signed in to change notification settings - Fork 108
/
Util.php
218 lines (203 loc) · 5.57 KB
/
Util.php
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
<?php
declare(strict_types=1);
namespace ParagonIE\Paseto;
use ParagonIE\ConstantTime\{
Base64UrlSafe,
Binary
};
use ParagonIE\Paseto\Exception\{
EncodingException,
ExceptionCode,
PasetoException
};
use SodiumException;
use TypeError;
use function array_pop,
array_slice,
count,
explode,
hash_equals,
implode,
pack,
preg_replace,
preg_match_all,
sodium_memzero,
str_replace;
/**
* Class Util
* @package ParagonIE\Paseto
*/
abstract class Util
{
/**
* Calculate the depth of a JSON string without passing it to json_decode()
*
* @param string $json
* @return int
*
* @throws EncodingException
*/
public static function calculateJsonDepth(string $json): int
{
// Remove quotes quotes first:
$stripped = str_replace('\"', '', $json);
// Remove whitespace:
$stripped = preg_replace('/\s+/', '', $stripped);
// Strip everything out of quotes:
$stripped = preg_replace('#"[^"]+"([:,}\]])#', '$1', $stripped);
// Remove everything that isn't a map or list definition
$stripped = preg_replace('#[^\[\]{}]#', '', $stripped);
$previous = '';
$depth = 1;
/** @psalm-suppress RiskyTruthyFalsyComparison */
while (!empty($stripped) && $stripped !== $previous) {
$previous = $stripped;
// Remove pairs of tokens
$stripped = str_replace(['[]', '{}'], [], $stripped);
++$depth;
}
/** @psalm-suppress RiskyTruthyFalsyComparison */
if (!empty($stripped)) {
throw new EncodingException(
'Invalid JSON string provided',
ExceptionCode::INVALID_JSON
);
}
return $depth;
}
/**
* Count the number of instances of `":` without a preceding backslash.
*
* @param string $json
* @return int
*/
public static function countJsonKeys(string $json): int
{
return preg_match_all('#[^\\\]":#', $json);
}
/**
* Normalize line-endings to UNIX-style (LF rather than CRLF).
*
* @param string $in
* @return string
*/
public static function dos2unix(string $in): string
{
return str_replace("\r\n", "\n", $in);
}
/**
* @param int $long
* @return string
*/
public static function longToBytes(int $long): string
{
return pack('P', $long);
}
/**
* Format the Additional Associated Data.
*
* Prefix with the length (64-bit unsigned little-endian integer)
* followed by each message. This provides a more explicit domain
* separation between each piece of the message.
*
* Each length is masked with PHP_INT_MAX using bitwise AND (&) to
* clear out the MSB of the total string length.
*
* @param string ...$pieces
* @return string
*/
public static function preAuthEncode(string ...$pieces): string
{
$accumulator = self::longToBytes(count($pieces) & PHP_INT_MAX);
foreach ($pieces as $piece) {
$len = Binary::safeStrlen($piece);
$accumulator .= self::longToBytes($len & PHP_INT_MAX);
$accumulator .= $piece;
}
return $accumulator;
}
/**
* If a footer was included with the message, extract it.
* Otherwise, return an empty string.
*
* @param string $payload
* @return string
*
* @throws TypeError
*/
public static function extractFooter(string $payload): string
{
$pieces = explode('.', $payload);
if (count($pieces) > 3) {
return Base64UrlSafe::decodeNoPadding(array_pop($pieces));
}
return '';
}
/**
* If a footer was included with the message, remove it.
*
* @param string $payload
* @return string
*
* @throws TypeError
*/
public static function removeFooter(string $payload): string
{
$pieces = explode('.', $payload);
if (count($pieces) > 3) {
return implode('.', array_slice($pieces, 0, 3));
}
return $payload;
}
/**
* If a footer was included with the message, first verify that
* it's equivalent to the one we expect, then remove it from the
* token payload.
*
* @param string $payload
* @param string $footer
* @return string
*
* @throws PasetoException
* @throws TypeError
*/
public static function validateAndRemoveFooter(
string $payload,
string $footer = ''
): string {
if (empty($footer)) {
return $payload;
}
$footer = Base64UrlSafe::encodeUnpadded($footer);
$payload_len = Binary::safeStrlen($payload);
$footer_len = Binary::safeStrlen($footer) + 1;
$trailing = Binary::safeSubstr(
$payload,
$payload_len - $footer_len,
$footer_len
);
if (!hash_equals('.' . $footer, $trailing)) {
throw new PasetoException(
'Invalid message footer',
ExceptionCode::FOOTER_MISMATCH_EXPECTED
);
}
return Binary::safeSubstr($payload, 0, $payload_len - $footer_len);
}
/**
* Wipe this value from memory.
*
* @param string $byRef
* @return void
* @param-out ?string $byRef
*/
public static function wipe(string &$byRef): void
{
try {
sodium_memzero($byRef);
} catch (SodiumException $ex) {
$byRef ^= $byRef;
unset($byRef);
}
}
}