Debian Codegraph @

lib/3rdParty/composer/paragonie/sodium_compat/src/Core/Util.php

raw symbols SCIP
1 <?php
2 declare(strict_types=1);
3
4 if (class_exists('ParagonIE_Sodium_Core_Util', false)) {
5 return;
6 }
7
8 /**
9 * Class ParagonIE_Sodium_Core_Util
10 */
11 abstract class ParagonIE_Sodium_Core_Util
12 {
13 const U32_MAX = 0xFFFFFFFF;
14
15 /**
16 * @param int $integer
17 * @param int $size (16, 32, 64)
18 * @return int
19 */
20 public static function abs(
21 #[SensitiveParameter]
22 int $integer,
23 int $size = 0
24 ): int {
25 $realSize = (PHP_INT_SIZE << 3) - 1;
26 if ($size) {
27 --$size;
28 } else {
29 $size = $realSize;
30 }
31
32 $negative = -(($integer >> $size) & 1);
33 return (
34 ($integer ^ $negative)
35 +
36 (($negative >> $realSize) & 1)
37 );
38 }
39
40 /**
41 * @param string $a
42 * @param string $b
43 * @return string
44 * @throws SodiumException
45 */
46 public static function andStrings(
47 #[SensitiveParameter]
48 string $a,
49 #[SensitiveParameter]
50 string $b
51 ): string {
52 $len = self::strlen($a);
53 if (self::strlen($b) !== $len) {
54 throw new SodiumException('Both strings must be of equal length to combine with bitwise AND');
55 }
56 return $a & $b;
57 }
58
59 /**
60 * Convert a binary string into a hexadecimal string without cache-timing
61 * leaks
62 *
63 * @internal You should not use this directly from another application
64 *
65 * @param string $binaryString (raw binary)
66 * @return string
67 * @throws TypeError
68 */
69 public static function bin2hex(
70 #[SensitiveParameter]
71 string $binaryString
72 ): string {
73 $hex = '';
74 $len = self::strlen($binaryString);
75 for ($i = 0; $i < $len; ++$i) {
76 /** @var array<int, int> $chunk */
77 $chunk = unpack('C', $binaryString[$i]);
78 /** @var int $c */
79 $c = $chunk[1] & 0xf;
80 /** @var int $b */
81 $b = $chunk[1] >> 4;
82 $hex .= pack(
83 'CC',
84 (87 + $b + ((($b - 10) >> 8) & ~38)),
85 (87 + $c + ((($c - 10) >> 8) & ~38))
86 );
87 }
88 return $hex;
89 }
90
91 /**
92 * Cache-timing-safe variant of ord()
93 *
94 * @internal You should not use this directly from another application
95 *
96 * @param string $chr
97 * @return int
98 * @throws SodiumException
99 * @throws TypeError
100 */
101 public static function chrToInt(
102 #[SensitiveParameter]
103 string $chr
104 ): int {
105 if (self::strlen($chr) !== 1) {
106 throw new SodiumException('chrToInt() expects a string that is exactly 1 character long');
107 }
108 /** @var array<int, int> $chunk */
109 $chunk = unpack('C', $chr);
110 return $chunk[1];
111 }
112
113 /**
114 * Compares two strings.
115 *
116 * @internal You should not use this directly from another application
117 *
118 * @param string $left
119 * @param string $right
120 * @param ?int $len
121 * @return int
122 * @throws SodiumException
123 * @throws TypeError
124 */
125 public static function compare(
126 #[SensitiveParameter]
127 string $left,
128 #[SensitiveParameter]
129 string $right,
130 ?int $len = null
131 ): int {
132 $leftLen = self::strlen($left);
133 $rightLen = self::strlen($right);
134 if ($len === null) {
135 $len = max($leftLen, $rightLen);
136 $left = str_pad($left, $len, "\x00");
137 $right = str_pad($right, $len, "\x00");
138 } elseif ($leftLen !== $rightLen) {
139 throw new SodiumException("Argument #1 and argument #2 must have the same length");
140 }
141
142 $gt = 0;
143 $eq = 1;
144 $i = $len;
145 while ($i !== 0) {
146 --$i;
147 $gt |= ((self::chrToInt($right[$i]) - self::chrToInt($left[$i])) >> 8) & $eq;
148 $eq &= ((self::chrToInt($right[$i]) ^ self::chrToInt($left[$i])) - 1) >> 8;
149 }
150 return ($gt + $gt + $eq) - 1;
151 }
152
153 /**
154 * Evaluate whether or not two strings are equal (in constant-time)
155 *
156 * @param string $left
157 * @param string $right
158 * @return bool
159 *
160 * @throws TypeError
161 */
162 public static function hashEquals(
163 #[SensitiveParameter]
164 string $left,
165 #[SensitiveParameter]
166 string $right
167 ): bool {
168 return hash_equals($left, $right);
169 }
170
171 /**
172 * Convert a hexadecimal string into a binary string without cache-timing
173 * leaks
174 *
175 * @internal You should not use this directly from another application
176 *
177 * @param string $hexString
178 * @param string $ignore
179 * @param bool $strictPadding
180 * @return string (raw binary)
181 * @throws SodiumException
182 * @throws TypeError
183 */
184 public static function hex2bin(
185 #[SensitiveParameter]
186 string $hexString,
187 string $ignore = '',
188 bool $strictPadding = false
189 ): string {
190 $hex_pos = 0;
191 $bin = '';
192 $c_acc = 0;
193 $hex_len = self::strlen($hexString);
194 $state = 0;
195 $chunk = unpack('C*', $hexString);
196 while ($hex_pos < $hex_len) {
197 ++$hex_pos;
198 /** @var int $c */
199 $c = $chunk[$hex_pos];
200 $c_num = $c ^ 48;
201 $c_num0 = ($c_num - 10) >> 8;
202 $c_alpha = ($c & ~32) - 55;
203 $c_alpha0 = (($c_alpha - 10) ^ ($c_alpha - 16)) >> 8;
204 if (($c_num0 | $c_alpha0) === 0) {
205 if ($ignore && $state === 0 && str_contains($ignore, self::intToChr($c))) {
206 continue;
207 }
208 throw new SodiumException(
209 'hex2bin() only expects hexadecimal characters'
210 );
211 }
212 $c_val = ($c_num0 & $c_num) | ($c_alpha & $c_alpha0);
213 if ($state === 0) {
214 $c_acc = $c_val * 16;
215 } else {
216 $bin .= pack('C', $c_acc | $c_val);
217 }
218 $state ^= 1;
219 }
220 if ($strictPadding && $state !== 0) {
221 throw new SodiumException(
222 'Expected an even number of hexadecimal characters'
223 );
224 }
225 return $bin;
226 }
227
228 /**
229 * Turn an array of integers into a string
230 *
231 * @internal You should not use this directly from another application
232 *
233 * @param array<int, int> $ints
234 * @return string
235 */
236 public static function intArrayToString(array $ints): string
237 {
238 $args = $ints;
239 foreach ($args as $i => $v) {
240 $args[$i] = ($v & 0xff);
241 }
242 array_unshift($args, str_repeat('C', count($ints)));
243 return (string) (call_user_func_array('pack', $args));
244 }
245
246 /**
247 * Cache-timing-safe variant of ord()
248 *
249 * @internal You should not use this directly from another application
250 *
251 * @param int $int
252 * @return string
253 * @throws TypeError
254 */
255 public static function intToChr(
256 #[SensitiveParameter]
257 int $int
258 ): string {
259 return pack('C', $int);
260 }
261
262 /**
263 * Load a 3 character substring into an integer
264 *
265 * @internal You should not use this directly from another application
266 *
267 * @param string $string
268 * @return int
269 * @throws RangeException
270 * @throws TypeError
271 */
272 public static function load_3(
273 #[SensitiveParameter]
274 string $string
275 ): int {
276 /* Input validation: */
277 if (self::strlen($string) < 3) {
278 throw new RangeException(
279 'String must be 3 bytes or more; ' . self::strlen($string) . ' given.'
280 );
281 }
282 /** @var array<int, int> $unpacked */
283 $unpacked = unpack('V', $string . "\0");
284 return ($unpacked[1] & 0xffffff);
285 }
286
287 /**
288 * Load a 4 character substring into an integer
289 *
290 * @internal You should not use this directly from another application
291 *
292 * @param string $string
293 * @return int
294 * @throws RangeException
295 * @throws TypeError
296 */
297 public static function load_4(
298 #[SensitiveParameter]
299 string $string
300 ): int {
301 /* Input validation: */
302 if (self::strlen($string) < 4) {
303 throw new RangeException(
304 'String must be 4 bytes or more; ' . self::strlen($string) . ' given.'
305 );
306 }
307 /** @var array<int, int> $unpacked */
308 $unpacked = unpack('V', $string);
309 return $unpacked[1];
310 }
311
312 /**
313 * Load a 8 character substring into an integer
314 *
315 * @internal You should not use this directly from another application
316 *
317 * @param string $string
318 * @return int
319 *
320 * @throws RangeException
321 * @throws SodiumException
322 * @throws TypeError
323 */
324 public static function load64_le(
325 #[SensitiveParameter]
326 string $string
327 ): int {
328 /* Input validation: */
329 if (self::strlen($string) < 4) {
330 throw new RangeException(
331 'String must be 4 bytes or more; ' . self::strlen($string) . ' given.'
332 );
333 }
334 $unpacked = unpack('P', $string);
335 return (int) $unpacked[1];
336 }
337
338 /**
339 * @internal You should not use this directly from another application
340 *
341 * @param string $left
342 * @param string $right
343 * @return int
344 * @throws TypeError
345 */
346 public static function memcmp(
347 #[SensitiveParameter]
348 string $left,
349 #[SensitiveParameter]
350 string $right
351 ): int {
352 $e = (int) !self::hashEquals($left, $right);
353 return 0 - $e;
354 }
355
356 /**
357 * Multiply two integers in constant-time
358 *
359 * Micro-architecture timing side-channels caused by how your CPU
360 * implements multiplication are best prevented by never using the
361 * multiplication operators and ensuring that our code always takes
362 * the same number of operations to complete, regardless of the values
363 * of $a and $b.
364 *
365 * @internal You should not use this directly from another application
366 *
367 * @param int $a
368 * @param int $b
369 * @param int $size Limits the number of operations (useful for small,
370 * constant operands)
371 * @return int
372 */
373 public static function mul(
374 #[SensitiveParameter]
375 int $a,
376 #[SensitiveParameter]
377 int $b,
378 int $size = 0
379 ): int {
380 if (ParagonIE_Sodium_Compat::$fastMult) {
381 return (int) ($a * $b);
382 }
383
384 static $defaultSize = null;
385 if (!$defaultSize) {
386 $defaultSize = (PHP_INT_SIZE << 3) - 1;
387 }
388 if ($size < 1) {
389 $size = $defaultSize;
390 }
391 /** @var int $size */
392
393 $c = 0;
394
395 /**
396 * Mask is either -1 or 0.
397 *
398 * -1 in binary looks like 0x1111 ... 1111
399 * 0 in binary looks like 0x0000 ... 0000
400 */
401 $mask = -(($b >> ($defaultSize)) & 1);
402
403 /**
404 * Ensure $b is a positive integer, without creating
405 * a branching side-channel
406 *
407 * @var int $b
408 */
409 $b = ($b & ~$mask) | ($mask & -$b);
410
411 /**
412 * Unless $size is provided:
413 *
414 * This loop always runs 32 times when PHP_INT_SIZE is 4.
415 * This loop always runs 64 times when PHP_INT_SIZE is 8.
416 */
417 for ($i = $size; $i >= 0; --$i) {
418 $c += ($a & -($b & 1));
419 $a <<= 1;
420 $b >>= 1;
421 }
422 $c = (int) @($c & -1);
423
424 /**
425 * If $b was negative, we then apply the same value to $c here.
426 * It doesn't matter much if $a was negative; the $c += above would
427 * have produced a negative integer to begin with. But a negative $b
428 * makes $b >>= 1 never return 0, so we would end up with incorrect
429 * results.
430 *
431 * The end result is what we'd expect from integer multiplication.
432 */
433 return (($c & ~$mask) | ($mask & -$c));
434 }
435
436 /**
437 * Convert any arbitrary numbers into two 32-bit integers that represent
438 * a 64-bit integer.
439 *
440 * @internal You should not use this directly from another application
441 *
442 * @param int|float $num
443 * @return array<int, int>
444 * @psalm-suppress RedundantCastGivenDocblockType
445 */
446 public static function numericTo64BitInteger(int|float $num): array
447 {
448 $high = 0;
449 /** @var int $low */
450 if (PHP_INT_SIZE === 4) {
451 $low = (int) $num;
452 } else {
453 $low = $num & 0xffffffff;
454 }
455
456 if ((+(abs($num))) >= 1) {
457 if ($num > 0) {
458 /** @var int $high */
459 $high = min((+(floor($num/4294967296))), 4294967295);
460 } else {
461 $high = ~~((+(ceil(($num - (+((~~($num)))))/4294967296))));
462 }
463 }
464 /**
465 * @var int $high
466 * @var int $low
467 */
468 return array((int) $high, (int) $low);
469 }
470
471 /**
472 * Store a 32-bit integer into a string, treating it as little-endian.
473 *
474 * @internal You should not use this directly from another application
475 *
476 * @param int $int
477 * @return string
478 * @throws TypeError
479 */
480 public static function store32_le(int $int): string
481 {
482 return pack('V', $int);
483 }
484
485 /**
486 * Stores a 64-bit integer as an string, treating it as little-endian.
487 *
488 * @internal You should not use this directly from another application
489 *
490 * @param int $int
491 * @return string
492 * @throws TypeError
493 */
494 public static function store64_le(int $int): string
495 {
496 return pack('P', $int);
497 }
498
499 /**
500 * Safe string length
501 *
502 * @internal You should not use this directly from another application
503 *
504 * @param string $str
505 * @return int
506 * @throws TypeError
507 */
508 public static function strlen(
509 #[SensitiveParameter]
510 string $str
511 ): int {
512 return strlen($str);
513 }
514
515 /**
516 * Turn a string into an array of integers
517 *
518 * @internal You should not use this directly from another application
519 *
520 * @param string $string
521 * @return array<int, int>
522 * @throws TypeError
523 */
524 public static function stringToIntArray(string $string): array
525 {
526 return array_values(
527 unpack('C*', $string)
528 );
529 }
530
531 /**
532 * Safe substring
533 *
534 * @internal You should not use this directly from another application
535 *
536 * @param string $str
537 * @param int $start
538 * @param ?int $length
539 * @return string
540 * @throws TypeError
541 */
542 public static function substr(
543 #[SensitiveParameter]
544 string $str,
545 int $start = 0,
546 ?int $length = null
547 ): string {
548 if ($length === 0) {
549 return '';
550 }
551
552 return substr($str, $start, $length);
553 }
554
555 /**
556 * Compare a 16-character byte string in constant time.
557 *
558 * @internal You should not use this directly from another application
559 *
560 * @param string $a
561 * @param string $b
562 * @return bool
563 * @throws TypeError
564 */
565 public static function verify_16(
566 #[SensitiveParameter]
567 string $a,
568 #[SensitiveParameter]
569 string $b
570 ): bool {
571 return self::hashEquals(
572 self::substr($a, 0, 16),
573 self::substr($b, 0, 16)
574 );
575 }
576
577 /**
578 * Compare a 32-character byte string in constant time.
579 *
580 * @internal You should not use this directly from another application
581 *
582 * @param string $a
583 * @param string $b
584 * @return bool
585 *
586 * @throws SodiumException
587 * @throws TypeError
588 */
589 public static function verify_32(
590 #[SensitiveParameter]
591 string $a,
592 #[SensitiveParameter]
593 string $b
594 ): bool {
595 return self::hashEquals(
596 self::substr($a, 0, 32),
597 self::substr($b, 0, 32)
598 );
599 }
600
601 /**
602 * Calculate $a ^ $b for two strings.
603 *
604 * @internal You should not use this directly from another application
605 *
606 * @param string $a
607 * @param string $b
608 * @return string
609 * @throws TypeError
610 */
611 public static function xorStrings(
612 #[SensitiveParameter]
613 string $a,
614 #[SensitiveParameter]
615 string $b
616 ): string {
617 return $a ^ $b;
618 }
619
620 }