Debian Codegraph @

lib/3rdParty/composer/paragonie/sodium_compat/src/Crypto.php

raw symbols SCIP
1 <?php
2 declare(strict_types=1);
3
4 if (class_exists('ParagonIE_Sodium_Crypto', false)) {
5 return;
6 }
7
8 /**
9 * Class ParagonIE_Sodium_Crypto
10 *
11 * ATTENTION!
12 *
13 * If you are using this library, you should be using
14 * ParagonIE_Sodium_Compat in your code, not this class.
15 */
16 abstract class ParagonIE_Sodium_Crypto
17 {
18 const aead_chacha20poly1305_KEYBYTES = 32;
19 const aead_chacha20poly1305_NSECBYTES = 0;
20 const aead_chacha20poly1305_NPUBBYTES = 8;
21 const aead_chacha20poly1305_ABYTES = 16;
22
23 const aead_chacha20poly1305_IETF_KEYBYTES = 32;
24 const aead_chacha20poly1305_IETF_NSECBYTES = 0;
25 const aead_chacha20poly1305_IETF_NPUBBYTES = 12;
26 const aead_chacha20poly1305_IETF_ABYTES = 16;
27
28 const aead_xchacha20poly1305_IETF_KEYBYTES = 32;
29 const aead_xchacha20poly1305_IETF_NSECBYTES = 0;
30 const aead_xchacha20poly1305_IETF_NPUBBYTES = 24;
31 const aead_xchacha20poly1305_IETF_ABYTES = 16;
32
33 const box_curve25519xsalsa20poly1305_SEEDBYTES = 32;
34 const box_curve25519xsalsa20poly1305_PUBLICKEYBYTES = 32;
35 const box_curve25519xsalsa20poly1305_SECRETKEYBYTES = 32;
36 const box_curve25519xsalsa20poly1305_BEFORENMBYTES = 32;
37 const box_curve25519xsalsa20poly1305_NONCEBYTES = 24;
38 const box_curve25519xsalsa20poly1305_MACBYTES = 16;
39 const box_curve25519xsalsa20poly1305_BOXZEROBYTES = 16;
40 const box_curve25519xsalsa20poly1305_ZEROBYTES = 32;
41
42 const onetimeauth_poly1305_BYTES = 16;
43 const onetimeauth_poly1305_KEYBYTES = 32;
44
45 const secretbox_xsalsa20poly1305_KEYBYTES = 32;
46 const secretbox_xsalsa20poly1305_NONCEBYTES = 24;
47 const secretbox_xsalsa20poly1305_MACBYTES = 16;
48 const secretbox_xsalsa20poly1305_BOXZEROBYTES = 16;
49 const secretbox_xsalsa20poly1305_ZEROBYTES = 32;
50
51 const secretbox_xchacha20poly1305_KEYBYTES = 32;
52 const secretbox_xchacha20poly1305_NONCEBYTES = 24;
53 const secretbox_xchacha20poly1305_MACBYTES = 16;
54 const secretbox_xchacha20poly1305_BOXZEROBYTES = 16;
55 const secretbox_xchacha20poly1305_ZEROBYTES = 32;
56
57 const stream_salsa20_KEYBYTES = 32;
58
59 /**
60 * AEAD Decryption with ChaCha20-Poly1305
61 *
62 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
63 *
64 * @param string $message
65 * @param string $ad
66 * @param string $nonce
67 * @param string $key
68 * @return string
69 * @throws SodiumException
70 * @throws TypeError
71 */
72 public static function aead_chacha20poly1305_decrypt(
73 string $message = '',
74 string $ad = '',
75 string $nonce = '',
76 #[SensitiveParameter]
77 string $key = ''
78 ): string {
79 /* Length of message (ciphertext + MAC) */
80 $len = ParagonIE_Sodium_Core_Util::strlen($message);
81
82 /* Length of ciphertext */
83 $clen = $len - self::aead_chacha20poly1305_ABYTES;
84
85 /* Length of associated data */
86 $adlen = ParagonIE_Sodium_Core_Util::strlen($ad);
87
88 /* Message authentication code */
89 $mac = ParagonIE_Sodium_Core_Util::substr(
90 $message,
91 $clen,
92 self::aead_chacha20poly1305_ABYTES
93 );
94
95 /* The encrypted message (sans MAC) */
96 $ciphertext = ParagonIE_Sodium_Core_Util::substr($message, 0, $clen);
97
98 /* The first block of the chacha20 keystream, used as a poly1305 key */
99 $block0 = ParagonIE_Sodium_Core_ChaCha20::stream(
100 32,
101 $nonce,
102 $key
103 );
104
105 /* Recalculate the Poly1305 authentication tag (MAC): */
106 $state = new ParagonIE_Sodium_Core_Poly1305_State($block0);
107 try {
108 ParagonIE_Sodium_Compat::memzero($block0);
109 } catch (SodiumException) {
110 $block0 = null;
111 }
112 $state->update($ad);
113 $state->update(ParagonIE_Sodium_Core_Util::store64_le($adlen));
114 $state->update($ciphertext);
115 $state->update(ParagonIE_Sodium_Core_Util::store64_le($clen));
116 $computed_mac = $state->finish();
117
118 /* Compare the given MAC with the recalculated MAC: */
119 if (!ParagonIE_Sodium_Core_Util::verify_16($computed_mac, $mac)) {
120 throw new SodiumException('Invalid MAC');
121 }
122
123 // Here, we know that the MAC is valid, so we decrypt and return the plaintext
124 return ParagonIE_Sodium_Core_ChaCha20::streamXorIc(
125 $ciphertext,
126 $nonce,
127 $key,
128 ParagonIE_Sodium_Core_Util::store64_le(1)
129 );
130 }
131
132 /**
133 * AEAD Encryption with ChaCha20-Poly1305
134 *
135 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
136 *
137 * @param string $message
138 * @param string $ad
139 * @param string $nonce
140 * @param string $key
141 * @return string
142 * @throws SodiumException
143 * @throws TypeError
144 */
145 public static function aead_chacha20poly1305_encrypt(
146 #[SensitiveParameter]
147 string $message = '',
148 string $ad = '',
149 string $nonce = '',
150 #[SensitiveParameter]
151 string $key = ''
152 ): string {
153 /* Length of the plaintext message */
154 $len = ParagonIE_Sodium_Core_Util::strlen($message);
155
156 /* Length of the associated data */
157 $adlen = ParagonIE_Sodium_Core_Util::strlen($ad);
158
159 /* The first block of the chacha20 keystream, used as a poly1305 key */
160 $block0 = ParagonIE_Sodium_Core_ChaCha20::stream(
161 32,
162 $nonce,
163 $key
164 );
165 $state = new ParagonIE_Sodium_Core_Poly1305_State($block0);
166 try {
167 ParagonIE_Sodium_Compat::memzero($block0);
168 } catch (SodiumException) {
169 $block0 = null;
170 }
171
172 /** @var string $ciphertext - Raw encrypted data */
173 $ciphertext = ParagonIE_Sodium_Core_ChaCha20::streamXorIc(
174 $message,
175 $nonce,
176 $key,
177 ParagonIE_Sodium_Core_Util::store64_le(1)
178 );
179
180 $state->update($ad);
181 $state->update(ParagonIE_Sodium_Core_Util::store64_le($adlen));
182 $state->update($ciphertext);
183 $state->update(ParagonIE_Sodium_Core_Util::store64_le($len));
184 return $ciphertext . $state->finish();
185 }
186
187 /**
188 * AEAD Decryption with ChaCha20-Poly1305, IETF mode (96-bit nonce)
189 *
190 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
191 *
192 * @param string $message
193 * @param string $ad
194 * @param string $nonce
195 * @param string $key
196 * @return string
197 * @throws SodiumException
198 * @throws TypeError
199 */
200 public static function aead_chacha20poly1305_ietf_decrypt(
201 string $message = '',
202 string $ad = '',
203 string $nonce = '',
204 #[SensitiveParameter]
205 string $key = ''
206 ): string {
207 /* Length of associated data */
208 $adlen = ParagonIE_Sodium_Core_Util::strlen($ad);
209
210 /* Length of message (ciphertext + MAC) */
211 $len = ParagonIE_Sodium_Core_Util::strlen($message);
212
213 /* Length of ciphertext */
214 $clen = $len - self::aead_chacha20poly1305_IETF_ABYTES;
215
216 /* The first block of the chacha20 keystream, used as a poly1305 key */
217 $block0 = ParagonIE_Sodium_Core_ChaCha20::ietfStream(
218 32,
219 $nonce,
220 $key
221 );
222
223 /** @var string $mac - Message authentication code */
224 $mac = ParagonIE_Sodium_Core_Util::substr(
225 $message,
226 $len - self::aead_chacha20poly1305_IETF_ABYTES,
227 self::aead_chacha20poly1305_IETF_ABYTES
228 );
229
230 /** @var string $ciphertext - The encrypted message (sans MAC) */
231 $ciphertext = ParagonIE_Sodium_Core_Util::substr(
232 $message,
233 0,
234 $len - self::aead_chacha20poly1305_IETF_ABYTES
235 );
236
237 /* Recalculate the Poly1305 authentication tag (MAC): */
238 $state = new ParagonIE_Sodium_Core_Poly1305_State($block0);
239 try {
240 ParagonIE_Sodium_Compat::memzero($block0);
241 } catch (SodiumException) {
242 $block0 = null;
243 }
244 $state->update($ad);
245 $state->update(str_repeat("\x00", ((0x10 - $adlen) & 0xf)));
246 $state->update($ciphertext);
247 $state->update(str_repeat("\x00", (0x10 - $clen) & 0xf));
248 $state->update(ParagonIE_Sodium_Core_Util::store64_le($adlen));
249 $state->update(ParagonIE_Sodium_Core_Util::store64_le($clen));
250 $computed_mac = $state->finish();
251
252 /* Compare the given MAC with the recalculated MAC: */
253 if (!ParagonIE_Sodium_Core_Util::verify_16($computed_mac, $mac)) {
254 throw new SodiumException('Invalid MAC');
255 }
256
257 // Here, we know that the MAC is valid, so we decrypt and return the plaintext
258 return ParagonIE_Sodium_Core_ChaCha20::ietfStreamXorIc(
259 $ciphertext,
260 $nonce,
261 $key,
262 ParagonIE_Sodium_Core_Util::store64_le(1)
263 );
264 }
265
266 /**
267 * AEAD Encryption with ChaCha20-Poly1305, IETF mode (96-bit nonce)
268 *
269 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
270 *
271 * @param string $message
272 * @param string $ad
273 * @param string $nonce
274 * @param string $key
275 * @return string
276 * @throws SodiumException
277 * @throws TypeError
278 */
279 public static function aead_chacha20poly1305_ietf_encrypt(
280 #[SensitiveParameter]
281 string $message = '',
282 string $ad = '',
283 string $nonce = '',
284 #[SensitiveParameter]
285 string $key = ''
286 ): string {
287 /* Length of the plaintext message */
288 $len = ParagonIE_Sodium_Core_Util::strlen($message);
289
290 /* Length of the associated data */
291 $adlen = ParagonIE_Sodium_Core_Util::strlen($ad);
292
293 /* The first block of the chacha20 keystream, used as a poly1305 key */
294 $block0 = ParagonIE_Sodium_Core_ChaCha20::ietfStream(
295 32,
296 $nonce,
297 $key
298 );
299 $state = new ParagonIE_Sodium_Core_Poly1305_State($block0);
300 try {
301 ParagonIE_Sodium_Compat::memzero($block0);
302 } catch (SodiumException) {
303 $block0 = null;
304 }
305
306 /** @var string $ciphertext - Raw encrypted data */
307 $ciphertext = ParagonIE_Sodium_Core_ChaCha20::ietfStreamXorIc(
308 $message,
309 $nonce,
310 $key,
311 ParagonIE_Sodium_Core_Util::store64_le(1)
312 );
313
314 $state->update($ad);
315 $state->update(str_repeat("\x00", ((0x10 - $adlen) & 0xf)));
316 $state->update($ciphertext);
317 $state->update(str_repeat("\x00", ((0x10 - $len) & 0xf)));
318 $state->update(ParagonIE_Sodium_Core_Util::store64_le($adlen));
319 $state->update(ParagonIE_Sodium_Core_Util::store64_le($len));
320 return $ciphertext . $state->finish();
321 }
322
323 /**
324 * AEAD Decryption with ChaCha20-Poly1305, IETF mode (96-bit nonce)
325 *
326 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
327 *
328 * @param string $message
329 * @param string $ad
330 * @param string $nonce
331 * @param string $key
332 * @return string
333 * @throws SodiumException
334 * @throws TypeError
335 */
336 public static function aead_xchacha20poly1305_ietf_decrypt(
337 string $message = '',
338 string $ad = '',
339 string $nonce = '',
340 #[SensitiveParameter]
341 string $key = ''
342 ): string {
343 $subkey = ParagonIE_Sodium_Core_HChaCha20::hChaCha20(
344 ParagonIE_Sodium_Core_Util::substr($nonce, 0, 16),
345 $key
346 );
347 $nonceLast = "\x00\x00\x00\x00" .
348 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8);
349
350 return self::aead_chacha20poly1305_ietf_decrypt($message, $ad, $nonceLast, $subkey);
351 }
352
353 /**
354 * AEAD Encryption with ChaCha20-Poly1305, IETF mode (96-bit nonce)
355 *
356 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
357 *
358 * @param string $message
359 * @param string $ad
360 * @param string $nonce
361 * @param string $key
362 * @return string
363 * @throws SodiumException
364 * @throws TypeError
365 */
366 public static function aead_xchacha20poly1305_ietf_encrypt(
367 #[SensitiveParameter]
368 string $message = '',
369 string $ad = '',
370 string $nonce = '',
371 #[SensitiveParameter]
372 string $key = ''
373 ): string {
374 $subkey = ParagonIE_Sodium_Core_HChaCha20::hChaCha20(
375 ParagonIE_Sodium_Core_Util::substr($nonce, 0, 16),
376 $key
377 );
378 $nonceLast = "\x00\x00\x00\x00" .
379 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8);
380
381 return self::aead_chacha20poly1305_ietf_encrypt($message, $ad, $nonceLast, $subkey);
382 }
383
384 /**
385 * HMAC-SHA-512-256 (a.k.a. the leftmost 256 bits of HMAC-SHA-512)
386 *
387 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
388 *
389 * @param string $message
390 * @param string $key
391 * @return string
392 * @throws TypeError
393 */
394 public static function auth(
395 string $message,
396 #[SensitiveParameter]
397 string $key
398 ): string {
399 return ParagonIE_Sodium_Core_Util::substr(
400 hash_hmac('sha512', $message, $key, true),
401 0,
402 32
403 );
404 }
405
406 /**
407 * HMAC-SHA-512-256 validation. Constant-time via hash_equals().
408 *
409 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
410 *
411 * @param string $mac
412 * @param string $message
413 * @param string $key
414 * @return bool
415 * @throws SodiumException
416 * @throws TypeError
417 */
418 public static function auth_verify(
419 string $mac,
420 string $message,
421 #[SensitiveParameter]
422 string $key
423 ): bool {
424 return ParagonIE_Sodium_Core_Util::hashEquals(
425 $mac,
426 self::auth($message, $key)
427 );
428 }
429
430 /**
431 * X25519 key exchange followed by XSalsa20Poly1305 symmetric encryption
432 *
433 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
434 *
435 * @param string $plaintext
436 * @param string $nonce
437 * @param string $keypair
438 * @return string
439 * @throws SodiumException
440 * @throws TypeError
441 */
442 public static function box(
443 #[SensitiveParameter]
444 string $plaintext,
445 string $nonce,
446 #[SensitiveParameter]
447 string $keypair
448 ): string {
449 return self::secretbox(
450 $plaintext,
451 $nonce,
452 self::box_beforenm(
453 self::box_secretkey($keypair),
454 self::box_publickey($keypair)
455 )
456 );
457 }
458
459 /**
460 * X25519-XSalsa20-Poly1305 with one ephemeral X25519 keypair.
461 *
462 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
463 *
464 * @param string $message
465 * @param string $publicKey
466 * @return string
467 * @throws SodiumException
468 * @throws TypeError
469 */
470 public static function box_seal(
471 #[SensitiveParameter]
472 string $message,
473 string $publicKey
474 ): string {
475 /** @var string $ephemeralKeypair */
476 $ephemeralKeypair = self::box_keypair();
477
478 /** @var string $ephemeralSK */
479 $ephemeralSK = self::box_secretkey($ephemeralKeypair);
480
481 /** @var string $ephemeralPK */
482 $ephemeralPK = self::box_publickey($ephemeralKeypair);
483
484 /** @var string $nonce */
485 $nonce = self::generichash(
486 $ephemeralPK . $publicKey,
487 '',
488 24
489 );
490
491 /** @var string $keypair - The combined keypair used in crypto_box() */
492 $keypair = self::box_keypair_from_secretkey_and_publickey($ephemeralSK, $publicKey);
493
494 /** @var string $ciphertext Ciphertext + MAC from crypto_box */
495 $ciphertext = self::box($message, $nonce, $keypair);
496 try {
497 ParagonIE_Sodium_Compat::memzero($ephemeralKeypair);
498 ParagonIE_Sodium_Compat::memzero($ephemeralSK);
499 ParagonIE_Sodium_Compat::memzero($nonce);
500 } catch (SodiumException) {
501 $ephemeralKeypair = null;
502 $ephemeralSK = null;
503 $nonce = null;
504 }
505 return $ephemeralPK . $ciphertext;
506 }
507
508 /**
509 * Opens a message encrypted via box_seal().
510 *
511 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
512 *
513 * @param string $message
514 * @param string $keypair
515 * @return string
516 * @throws SodiumException
517 * @throws TypeError
518 */
519 public static function box_seal_open(
520 string $message,
521 #[SensitiveParameter]
522 string $keypair
523 ): string {
524 /** @var string $ephemeralPK */
525 $ephemeralPK = ParagonIE_Sodium_Core_Util::substr($message, 0, 32);
526
527 /** @var string $ciphertext (ciphertext + MAC) */
528 $ciphertext = ParagonIE_Sodium_Core_Util::substr($message, 32);
529
530 /** @var string $secretKey */
531 $secretKey = self::box_secretkey($keypair);
532
533 /** @var string $publicKey */
534 $publicKey = self::box_publickey($keypair);
535
536 /** @var string $nonce */
537 $nonce = self::generichash(
538 $ephemeralPK . $publicKey,
539 '',
540 24
541 );
542
543 /** @var string $keypair */
544 $keypair = self::box_keypair_from_secretkey_and_publickey($secretKey, $ephemeralPK);
545
546 /** @var string $m */
547 $m = self::box_open($ciphertext, $nonce, $keypair);
548 try {
549 ParagonIE_Sodium_Compat::memzero($secretKey);
550 ParagonIE_Sodium_Compat::memzero($ephemeralPK);
551 ParagonIE_Sodium_Compat::memzero($nonce);
552 } catch (SodiumException) {
553 $secretKey = null;
554 $ephemeralPK = null;
555 $nonce = null;
556 }
557 return $m;
558 }
559
560 /**
561 * Used by crypto_box() to get the crypto_secretbox() key.
562 *
563 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
564 *
565 * @param string $sk
566 * @param string $pk
567 * @return string
568 * @throws SodiumException
569 * @throws TypeError
570 */
571 public static function box_beforenm(
572 #[SensitiveParameter]
573 string $sk,
574 string $pk
575 ): string
576 {
577 return ParagonIE_Sodium_Core_HSalsa20::hsalsa20(
578 str_repeat("\x00", 16),
579 self::scalarmult($sk, $pk)
580 );
581 }
582
583 /**
584 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
585 *
586 * @return string
587 * @throws Exception
588 * @throws SodiumException
589 * @throws TypeError
590 */
591 public static function box_keypair(): string
592 {
593 $sKey = random_bytes(32);
594 $pKey = self::scalarmult_base($sKey);
595 return $sKey . $pKey;
596 }
597
598 /**
599 * @param string $seed
600 * @return string
601 * @throws SodiumException
602 * @throws TypeError
603 */
604 public static function box_seed_keypair(
605 #[SensitiveParameter]
606 string $seed
607 ): string
608 {
609 $sKey = ParagonIE_Sodium_Core_Util::substr(
610 hash('sha512', $seed, true),
611 0,
612 32
613 );
614 $pKey = self::scalarmult_base($sKey);
615 return $sKey . $pKey;
616 }
617
618 /**
619 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
620 *
621 * @param string $sKey
622 * @param string $pKey
623 * @return string
624 * @throws TypeError
625 */
626 public static function box_keypair_from_secretkey_and_publickey(
627 #[SensitiveParameter]
628 string $sKey,
629 string $pKey
630 ): string {
631 return ParagonIE_Sodium_Core_Util::substr($sKey, 0, 32) .
632 ParagonIE_Sodium_Core_Util::substr($pKey, 0, 32);
633 }
634
635 /**
636 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
637 *
638 * @param string $keypair
639 * @return string
640 * @throws RangeException
641 * @throws TypeError
642 */
643 public static function box_secretkey(
644 #[SensitiveParameter]
645 string $keypair
646 ): string {
647 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== 64) {
648 throw new RangeException(
649 'Must be ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES bytes long.'
650 );
651 }
652 return ParagonIE_Sodium_Core_Util::substr($keypair, 0, 32);
653 }
654
655 /**
656 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
657 *
658 * @param string $keypair
659 * @return string
660 * @throws RangeException
661 * @throws TypeError
662 */
663 public static function box_publickey(
664 #[SensitiveParameter]
665 string $keypair
666 ): string {
667 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES) {
668 throw new RangeException(
669 'Must be ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES bytes long.'
670 );
671 }
672 return ParagonIE_Sodium_Core_Util::substr($keypair, 32, 32);
673 }
674
675 /**
676 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
677 *
678 * @param string $sKey
679 * @return string
680 * @throws RangeException
681 * @throws SodiumException
682 * @throws TypeError
683 */
684 public static function box_publickey_from_secretkey(
685 #[SensitiveParameter]
686 string $sKey
687 ): string {
688 if (ParagonIE_Sodium_Core_Util::strlen($sKey) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_SECRETKEYBYTES) {
689 throw new RangeException(
690 'Must be ParagonIE_Sodium_Compat::CRYPTO_BOX_SECRETKEYBYTES bytes long.'
691 );
692 }
693 return self::scalarmult_base($sKey);
694 }
695
696 /**
697 * Decrypt a message encrypted with box().
698 *
699 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
700 *
701 * @param string $ciphertext
702 * @param string $nonce
703 * @param string $keypair
704 * @return string
705 * @throws SodiumException
706 * @throws TypeError
707 */
708 public static function box_open(
709 string $ciphertext,
710 string $nonce,
711 #[SensitiveParameter]
712 string $keypair
713 ): string {
714 return self::secretbox_open(
715 $ciphertext,
716 $nonce,
717 self::box_beforenm(
718 self::box_secretkey($keypair),
719 self::box_publickey($keypair)
720 )
721 );
722 }
723
724 /**
725 * Calculate a BLAKE2b hash.
726 *
727 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
728 *
729 * @param string $message
730 * @param string|null $key
731 * @param int $outlen
732 * @return string
733 * @throws RangeException
734 * @throws SodiumException
735 * @throws TypeError
736 */
737 public static function generichash(
738 string $message,
739 #[SensitiveParameter]
740 ?string $key = '',
741 int $outlen = 32
742 ): string {
743 // This ensures that ParagonIE_Sodium_Core_BLAKE2b::$iv is initialized
744 ParagonIE_Sodium_Core_BLAKE2b::pseudoConstructor();
745
746 $k = null;
747 /** @psalm-suppress RiskyTruthyFalsyComparison */
748 if (!empty($key)) {
749 /** @var SplFixedArray $k */
750 $k = ParagonIE_Sodium_Core_BLAKE2b::stringToSplFixedArray($key);
751 if ($k->count() > ParagonIE_Sodium_Core_BLAKE2b::KEYBYTES) {
752 throw new RangeException('Invalid key size');
753 }
754 }
755
756 /** @var SplFixedArray $in */
757 $in = ParagonIE_Sodium_Core_BLAKE2b::stringToSplFixedArray($message);
758
759 /** @var SplFixedArray $ctx */
760 $ctx = ParagonIE_Sodium_Core_BLAKE2b::init($k, $outlen);
761 ParagonIE_Sodium_Core_BLAKE2b::update($ctx, $in, $in->count());
762
763 /** @var SplFixedArray $out */
764 $out = new SplFixedArray($outlen);
765 $out = ParagonIE_Sodium_Core_BLAKE2b::finish($ctx, $out);
766
767 /** @var array<int, int> */
768 $outArray = $out->toArray();
769 return ParagonIE_Sodium_Core_Util::intArrayToString($outArray);
770 }
771
772 /**
773 * Finalize a BLAKE2b hashing context, returning the hash.
774 *
775 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
776 *
777 * @param string $ctx
778 * @param int $outlen
779 * @return string
780 * @throws SodiumException
781 * @throws TypeError
782 */
783 public static function generichash_final(string $ctx, int $outlen = 32): string
784 {
785 $out = new SplFixedArray($outlen);
786 $context = ParagonIE_Sodium_Core_BLAKE2b::stringToContext($ctx);
787 $out = ParagonIE_Sodium_Core_BLAKE2b::finish($context, $out);
788 $outArray = $out->toArray();
789 return ParagonIE_Sodium_Core_Util::intArrayToString($outArray);
790 }
791
792 /**
793 * Initialize a hashing context for BLAKE2b.
794 *
795 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
796 *
797 * @param string $key
798 * @param int $outputLength
799 * @return string
800 * @throws RangeException
801 * @throws SodiumException
802 * @throws TypeError
803 */
804 public static function generichash_init(
805 #[SensitiveParameter]
806 string $key = '',
807 int $outputLength = 32
808 ): string {
809 // This ensures that ParagonIE_Sodium_Core_BLAKE2b::$iv is initialized
810 ParagonIE_Sodium_Core_BLAKE2b::pseudoConstructor();
811
812 $k = null;
813 if (!empty($key)) {
814 $k = ParagonIE_Sodium_Core_BLAKE2b::stringToSplFixedArray($key);
815 if ($k->count() > ParagonIE_Sodium_Core_BLAKE2b::KEYBYTES) {
816 throw new RangeException('Invalid key size');
817 }
818 }
819
820 /** @var SplFixedArray $ctx */
821 $ctx = ParagonIE_Sodium_Core_BLAKE2b::init($k, $outputLength);
822
823 return ParagonIE_Sodium_Core_BLAKE2b::contextToString($ctx);
824 }
825
826 /**
827 * Initialize a hashing context for BLAKE2b.
828 *
829 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
830 *
831 * @param string $key
832 * @param int $outputLength
833 * @param string $salt
834 * @param string $personal
835 * @return string
836 * @throws RangeException
837 * @throws SodiumException
838 * @throws TypeError
839 */
840 public static function generichash_init_salt_personal(
841 #[SensitiveParameter]
842 string $key = '',
843 int $outputLength = 32,
844 string $salt = '',
845 string $personal = ''
846 ): string {
847 // This ensures that ParagonIE_Sodium_Core_BLAKE2b::$iv is initialized
848 ParagonIE_Sodium_Core_BLAKE2b::pseudoConstructor();
849
850 $k = null;
851 if (!empty($key)) {
852 $k = ParagonIE_Sodium_Core_BLAKE2b::stringToSplFixedArray($key);
853 if ($k->count() > ParagonIE_Sodium_Core_BLAKE2b::KEYBYTES) {
854 throw new RangeException('Invalid key size');
855 }
856 }
857 if (!empty($salt)) {
858 $s = ParagonIE_Sodium_Core_BLAKE2b::stringToSplFixedArray($salt);
859 } else {
860 $s = null;
861 }
862 if (!empty($salt)) {
863 $p = ParagonIE_Sodium_Core_BLAKE2b::stringToSplFixedArray($personal);
864 } else {
865 $p = null;
866 }
867 $ctx = ParagonIE_Sodium_Core_BLAKE2b::init($k, $outputLength, $s, $p);
868 return ParagonIE_Sodium_Core_BLAKE2b::contextToString($ctx);
869 }
870
871 /**
872 * Update a hashing context for BLAKE2b with $message
873 *
874 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
875 *
876 * @param string $ctx
877 * @param string $message
878 * @return string
879 * @throws SodiumException
880 * @throws TypeError
881 */
882 public static function generichash_update(string $ctx, string $message): string
883 {
884 // This ensures that ParagonIE_Sodium_Core_BLAKE2b::$iv is initialized
885 ParagonIE_Sodium_Core_BLAKE2b::pseudoConstructor();
886 $context = ParagonIE_Sodium_Core_BLAKE2b::stringToContext($ctx);
887 $in = ParagonIE_Sodium_Core_BLAKE2b::stringToSplFixedArray($message);
888 ParagonIE_Sodium_Core_BLAKE2b::update($context, $in, $in->count());
889 return ParagonIE_Sodium_Core_BLAKE2b::contextToString($context);
890 }
891
892 /**
893 * Libsodium's crypto_kx().
894 *
895 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
896 *
897 * @param string $my_sk
898 * @param string $their_pk
899 * @param string $client_pk
900 * @param string $server_pk
901 * @return string
902 * @throws SodiumException
903 * @throws TypeError
904 */
905 public static function keyExchange(
906 #[SensitiveParameter]
907 string $my_sk,
908 string $their_pk,
909 string $client_pk,
910 string $server_pk
911 ): string {
912 return ParagonIE_Sodium_Compat::crypto_generichash(
913 ParagonIE_Sodium_Compat::crypto_scalarmult($my_sk, $their_pk) .
914 $client_pk .
915 $server_pk
916 );
917 }
918
919 /**
920 * ECDH over Curve25519
921 *
922 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
923 *
924 * @param string $sKey
925 * @param string $pKey
926 * @return string
927 *
928 * @throws SodiumException
929 * @throws TypeError
930 */
931 public static function scalarmult(
932 #[SensitiveParameter]
933 string $sKey,
934 string $pKey
935 ): string {
936 $q = ParagonIE_Sodium_Core_X25519::crypto_scalarmult_curve25519_ref10($sKey, $pKey);
937 self::scalarmult_throw_if_zero($q);
938 return $q;
939 }
940
941 /**
942 * ECDH over Curve25519, using the basepoint.
943 * Used to get a secret key from a public key.
944 *
945 * @param string $secret
946 * @return string
947 *
948 * @throws SodiumException
949 * @throws TypeError
950 */
951 public static function scalarmult_base(
952 #[SensitiveParameter]
953 string $secret
954 ): string {
955 $q = ParagonIE_Sodium_Core_X25519::crypto_scalarmult_curve25519_ref10_base($secret);
956 self::scalarmult_throw_if_zero($q);
957 return $q;
958 }
959
960 /**
961 * This throws an Error if a zero public key was passed to the function.
962 *
963 * @param string $q
964 * @return void
965 * @throws SodiumException
966 * @throws TypeError
967 */
968 protected static function scalarmult_throw_if_zero(
969 #[SensitiveParameter]
970 string $q
971 ): void {
972 $d = 0;
973 for ($i = 0; $i < self::box_curve25519xsalsa20poly1305_SECRETKEYBYTES; ++$i) {
974 $d |= ParagonIE_Sodium_Core_Util::chrToInt($q[$i]);
975 }
976
977 /* branch-free variant of === 0 */
978 if (-(1 & (($d - 1) >> 8))) {
979 throw new SodiumException('Zero public key is not allowed');
980 }
981 }
982
983 /**
984 * XSalsa20-Poly1305 authenticated symmetric-key encryption.
985 *
986 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
987 *
988 * @param string $plaintext
989 * @param string $nonce
990 * @param string $key
991 * @return string
992 * @throws SodiumException
993 * @throws TypeError
994 */
995 public static function secretbox(
996 #[SensitiveParameter]
997 string $plaintext,
998 string $nonce,
999 #[SensitiveParameter]
1000 string $key
1001 ): string {
1002 $subkey = ParagonIE_Sodium_Core_HSalsa20::hsalsa20($nonce, $key);
1003 $block0 = str_repeat("\x00", 32);
1004
1005 /* Length of the plaintext message */
1006 $mlen = ParagonIE_Sodium_Core_Util::strlen($plaintext);
1007 $mlen0 = min($mlen, 64 - self::secretbox_xsalsa20poly1305_ZEROBYTES);
1008 $block0 .= ParagonIE_Sodium_Core_Util::substr($plaintext, 0, $mlen0);
1009
1010 /** @var string $block0 */
1011 $block0 = ParagonIE_Sodium_Core_Salsa20::salsa20_xor(
1012 $block0,
1013 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
1014 $subkey
1015 );
1016
1017 /** @var string $c */
1018 $c = ParagonIE_Sodium_Core_Util::substr(
1019 $block0,
1020 self::secretbox_xsalsa20poly1305_ZEROBYTES
1021 );
1022 if ($mlen > $mlen0) {
1023 $c .= ParagonIE_Sodium_Core_Salsa20::salsa20_xor_ic(
1024 ParagonIE_Sodium_Core_Util::substr(
1025 $plaintext,
1026 self::secretbox_xsalsa20poly1305_ZEROBYTES
1027 ),
1028 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
1029 1,
1030 $subkey
1031 );
1032 }
1033 $state = new ParagonIE_Sodium_Core_Poly1305_State(
1034 ParagonIE_Sodium_Core_Util::substr(
1035 $block0,
1036 0,
1037 self::onetimeauth_poly1305_KEYBYTES
1038 )
1039 );
1040 try {
1041 ParagonIE_Sodium_Compat::memzero($block0);
1042 ParagonIE_Sodium_Compat::memzero($subkey);
1043 } catch (SodiumException) {
1044 $block0 = null;
1045 $subkey = null;
1046 }
1047
1048 $state->update($c);
1049
1050 /** @var string $c - MAC || ciphertext */
1051 $c = $state->finish() . $c;
1052 unset($state);
1053
1054 return $c;
1055 }
1056
1057 /**
1058 * Decrypt a ciphertext generated via secretbox().
1059 *
1060 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
1061 *
1062 * @param string $ciphertext
1063 * @param string $nonce
1064 * @param string $key
1065 * @return string
1066 * @throws SodiumException
1067 * @throws TypeError
1068 */
1069 public static function secretbox_open(
1070 string $ciphertext,
1071 string $nonce,
1072 #[SensitiveParameter]
1073 string $key
1074 ): string {
1075 $mac = ParagonIE_Sodium_Core_Util::substr(
1076 $ciphertext,
1077 0,
1078 self::secretbox_xsalsa20poly1305_MACBYTES
1079 );
1080
1081 $c = ParagonIE_Sodium_Core_Util::substr(
1082 $ciphertext,
1083 self::secretbox_xsalsa20poly1305_MACBYTES
1084 );
1085
1086 $clen = ParagonIE_Sodium_Core_Util::strlen($c);
1087
1088 $subkey = ParagonIE_Sodium_Core_HSalsa20::hsalsa20($nonce, $key);
1089
1090 $block0 = ParagonIE_Sodium_Core_Salsa20::salsa20(
1091 64,
1092 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
1093 $subkey
1094 );
1095 $verified = ParagonIE_Sodium_Core_Poly1305::onetimeauth_verify(
1096 $mac,
1097 $c,
1098 ParagonIE_Sodium_Core_Util::substr($block0, 0, 32)
1099 );
1100 if (!$verified) {
1101 try {
1102 ParagonIE_Sodium_Compat::memzero($subkey);
1103 } catch (SodiumException) {
1104 $subkey = null;
1105 }
1106 throw new SodiumException('Invalid MAC');
1107 }
1108
1109 /* Decrypted message */
1110 $m = ParagonIE_Sodium_Core_Util::xorStrings(
1111 ParagonIE_Sodium_Core_Util::substr($block0, self::secretbox_xsalsa20poly1305_ZEROBYTES),
1112 ParagonIE_Sodium_Core_Util::substr($c, 0, self::secretbox_xsalsa20poly1305_ZEROBYTES)
1113 );
1114 if ($clen > self::secretbox_xsalsa20poly1305_ZEROBYTES) {
1115 // We had more than 1 block, so let's continue to decrypt the rest.
1116 $m .= ParagonIE_Sodium_Core_Salsa20::salsa20_xor_ic(
1117 ParagonIE_Sodium_Core_Util::substr(
1118 $c,
1119 self::secretbox_xsalsa20poly1305_ZEROBYTES
1120 ),
1121 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
1122 1,
1123 $subkey
1124 );
1125 }
1126 return $m;
1127 }
1128
1129 /**
1130 * XChaCha20-Poly1305 authenticated symmetric-key encryption.
1131 *
1132 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
1133 *
1134 * @param string $plaintext
1135 * @param string $nonce
1136 * @param string $key
1137 * @return string
1138 * @throws SodiumException
1139 * @throws TypeError
1140 */
1141 public static function secretbox_xchacha20poly1305(
1142 #[SensitiveParameter]
1143 string $plaintext,
1144 string $nonce,
1145 #[SensitiveParameter]
1146 string $key
1147 ): string {
1148 $subkey = ParagonIE_Sodium_Core_HChaCha20::hChaCha20(
1149 ParagonIE_Sodium_Core_Util::substr($nonce, 0, 16),
1150 $key
1151 );
1152 $nonceLast = ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8);
1153 $block0 = str_repeat("\x00", 32);
1154
1155 /*Length of the plaintext message */
1156 $mlen = ParagonIE_Sodium_Core_Util::strlen($plaintext);
1157 $mlen0 = $mlen;
1158 if ($mlen0 > 64 - self::secretbox_xchacha20poly1305_ZEROBYTES) {
1159 $mlen0 = 64 - self::secretbox_xchacha20poly1305_ZEROBYTES;
1160 }
1161 $block0 .= ParagonIE_Sodium_Core_Util::substr($plaintext, 0, $mlen0);
1162
1163 /** @var string $block0 */
1164 $block0 = ParagonIE_Sodium_Core_ChaCha20::streamXorIc(
1165 $block0,
1166 $nonceLast,
1167 $subkey
1168 );
1169
1170 /** @var string $c */
1171 $c = ParagonIE_Sodium_Core_Util::substr(
1172 $block0,
1173 self::secretbox_xchacha20poly1305_ZEROBYTES
1174 );
1175 if ($mlen > $mlen0) {
1176 $c .= ParagonIE_Sodium_Core_ChaCha20::streamXorIc(
1177 ParagonIE_Sodium_Core_Util::substr(
1178 $plaintext,
1179 self::secretbox_xchacha20poly1305_ZEROBYTES
1180 ),
1181 $nonceLast,
1182 $subkey,
1183 ParagonIE_Sodium_Core_Util::store64_le(1)
1184 );
1185 }
1186 $state = new ParagonIE_Sodium_Core_Poly1305_State(
1187 ParagonIE_Sodium_Core_Util::substr(
1188 $block0,
1189 0,
1190 self::onetimeauth_poly1305_KEYBYTES
1191 )
1192 );
1193 try {
1194 ParagonIE_Sodium_Compat::memzero($block0);
1195 ParagonIE_Sodium_Compat::memzero($subkey);
1196 } catch (SodiumException) {
1197 $block0 = null;
1198 $subkey = null;
1199 }
1200
1201 $state->update($c);
1202
1203 /** @var string $c - MAC || ciphertext */
1204 $c = $state->finish() . $c;
1205 unset($state);
1206
1207 return $c;
1208 }
1209
1210 /**
1211 * Decrypt a ciphertext generated via secretbox_xchacha20poly1305().
1212 *
1213 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
1214 *
1215 * @param string $ciphertext
1216 * @param string $nonce
1217 * @param string $key
1218 * @return string
1219 * @throws SodiumException
1220 * @throws TypeError
1221 */
1222 public static function secretbox_xchacha20poly1305_open(
1223 string $ciphertext,
1224 string $nonce,
1225 #[SensitiveParameter]
1226 string $key
1227 ): string {
1228 $mac = ParagonIE_Sodium_Core_Util::substr(
1229 $ciphertext,
1230 0,
1231 self::secretbox_xchacha20poly1305_MACBYTES
1232 );
1233
1234 $c = ParagonIE_Sodium_Core_Util::substr(
1235 $ciphertext,
1236 self::secretbox_xchacha20poly1305_MACBYTES
1237 );
1238
1239 $clen = ParagonIE_Sodium_Core_Util::strlen($c);
1240
1241 $subkey = ParagonIE_Sodium_Core_HChaCha20::hchacha20(
1242 ParagonIE_Sodium_Core_Util::substr($nonce, 0, 16),
1243 $key
1244 );
1245
1246 $block0 = ParagonIE_Sodium_Core_ChaCha20::stream(
1247 64,
1248 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
1249 $subkey
1250 );
1251 $verified = ParagonIE_Sodium_Core_Poly1305::onetimeauth_verify(
1252 $mac,
1253 $c,
1254 ParagonIE_Sodium_Core_Util::substr($block0, 0, 32)
1255 );
1256
1257 if (!$verified) {
1258 try {
1259 ParagonIE_Sodium_Compat::memzero($subkey);
1260 } catch (SodiumException) {
1261 $subkey = null;
1262 }
1263 throw new SodiumException('Invalid MAC');
1264 }
1265
1266 /* Decrypted message */
1267 $m = ParagonIE_Sodium_Core_Util::xorStrings(
1268 ParagonIE_Sodium_Core_Util::substr($block0, self::secretbox_xchacha20poly1305_ZEROBYTES),
1269 ParagonIE_Sodium_Core_Util::substr($c, 0, self::secretbox_xchacha20poly1305_ZEROBYTES)
1270 );
1271
1272 if ($clen > self::secretbox_xchacha20poly1305_ZEROBYTES) {
1273 // We had more than 1 block, so let's continue to decrypt the rest.
1274 $m .= ParagonIE_Sodium_Core_ChaCha20::streamXorIc(
1275 ParagonIE_Sodium_Core_Util::substr(
1276 $c,
1277 self::secretbox_xchacha20poly1305_ZEROBYTES
1278 ),
1279 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
1280 $subkey,
1281 ParagonIE_Sodium_Core_Util::store64_le(1)
1282 );
1283 }
1284 return $m;
1285 }
1286
1287 /**
1288 * @param string $key
1289 * @return array<int, string> Returns a state and a header.
1290 * @throws Exception
1291 * @throws SodiumException
1292 */
1293 public static function secretstream_xchacha20poly1305_init_push(
1294 #[SensitiveParameter]
1295 string $key
1296 ): array {
1297 # randombytes_buf(out, crypto_secretstream_xchacha20poly1305_HEADERBYTES);
1298 $out = random_bytes(24);
1299
1300 # crypto_core_hchacha20(state->k, out, k, NULL);
1301 $subkey = ParagonIE_Sodium_Core_HChaCha20::hChaCha20(
1302 ParagonIE_Sodium_Core_Util::substr($out, 0, 16),
1303 $key
1304 );
1305 $state = new ParagonIE_Sodium_Core_SecretStream_State(
1306 $subkey,
1307 ParagonIE_Sodium_Core_Util::substr($out, 16, 8) . str_repeat("\0", 4)
1308 );
1309
1310 # _crypto_secretstream_xchacha20poly1305_counter_reset(state);
1311 $state->counterReset();
1312
1313 # memcpy(STATE_INONCE(state), out + crypto_core_hchacha20_INPUTBYTES,
1314 # crypto_secretstream_xchacha20poly1305_INONCEBYTES);
1315 # memset(state->_pad, 0, sizeof state->_pad);
1316 return array(
1317 $state->toString(),
1318 $out
1319 );
1320 }
1321
1322 /**
1323 * @param string $key
1324 * @param string $header
1325 * @return string Returns a state.
1326 * @throws Exception
1327 */
1328 public static function secretstream_xchacha20poly1305_init_pull(
1329 #[SensitiveParameter]
1330 string $key,
1331 string $header
1332 ): string {
1333 # crypto_core_hchacha20(state->k, in, k, NULL);
1334 $subkey = ParagonIE_Sodium_Core_HChaCha20::hChaCha20(
1335 ParagonIE_Sodium_Core_Util::substr($header, 0, 16),
1336 $key
1337 );
1338 $state = new ParagonIE_Sodium_Core_SecretStream_State(
1339 $subkey,
1340 ParagonIE_Sodium_Core_Util::substr($header, 16)
1341 );
1342 $state->counterReset();
1343 # memcpy(STATE_INONCE(state), in + crypto_core_hchacha20_INPUTBYTES,
1344 # crypto_secretstream_xchacha20poly1305_INONCEBYTES);
1345 # memset(state->_pad, 0, sizeof state->_pad);
1346 # return 0;
1347 return $state->toString();
1348 }
1349
1350 /**
1351 * @param string $state
1352 * @param string $msg
1353 * @param string $aad
1354 * @param int $tag
1355 * @return string
1356 * @throws SodiumException
1357 */
1358 public static function secretstream_xchacha20poly1305_push(
1359 #[SensitiveParameter]
1360 string &$state,
1361 #[SensitiveParameter]
1362 string $msg,
1363 string $aad = '',
1364 int $tag = 0
1365 ): string {
1366 $st = ParagonIE_Sodium_Core_SecretStream_State::fromString($state);
1367 # crypto_onetimeauth_poly1305_state poly1305_state;
1368 # unsigned char block[64U];
1369 # unsigned char slen[8U];
1370 # unsigned char *c;
1371 # unsigned char *mac;
1372
1373 $msglen = ParagonIE_Sodium_Core_Util::strlen($msg);
1374 $aadlen = ParagonIE_Sodium_Core_Util::strlen($aad);
1375
1376 if ((($msglen + 63) >> 6) > 0xfffffffe) {
1377 throw new SodiumException(
1378 'message cannot be larger than SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX bytes'
1379 );
1380 }
1381
1382 # if (outlen_p != NULL) {
1383 # *outlen_p = 0U;
1384 # }
1385 # if (mlen > crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX) {
1386 # sodium_misuse();
1387 # }
1388
1389 # crypto_stream_chacha20_ietf(block, sizeof block, state->nonce, state->k);
1390 # crypto_onetimeauth_poly1305_init(&poly1305_state, block);
1391 # sodium_memzero(block, sizeof block);
1392 $auth = new ParagonIE_Sodium_Core_Poly1305_State(
1393 ParagonIE_Sodium_Core_ChaCha20::ietfStream(32, $st->getCombinedNonce(), $st->getKey())
1394 );
1395
1396 # crypto_onetimeauth_poly1305_update(&poly1305_state, ad, adlen);
1397 $auth->update($aad);
1398
1399 # crypto_onetimeauth_poly1305_update(&poly1305_state, _pad0,
1400 # (0x10 - adlen) & 0xf);
1401 $auth->update(str_repeat("\0", ((0x10 - $aadlen) & 0xf)));
1402
1403 # memset(block, 0, sizeof block);
1404 # block[0] = tag;
1405 # crypto_stream_chacha20_ietf_xor_ic(block, block, sizeof block,
1406 # state->nonce, 1U, state->k);
1407 $block = ParagonIE_Sodium_Core_ChaCha20::ietfStreamXorIc(
1408 ParagonIE_Sodium_Core_Util::intToChr($tag) . str_repeat("\0", 63),
1409 $st->getCombinedNonce(),
1410 $st->getKey(),
1411 ParagonIE_Sodium_Core_Util::store64_le(1)
1412 );
1413
1414 # crypto_onetimeauth_poly1305_update(&poly1305_state, block, sizeof block);
1415 $auth->update($block);
1416
1417 # out[0] = block[0];
1418 $out = $block[0];
1419 # c = out + (sizeof tag);
1420 # crypto_stream_chacha20_ietf_xor_ic(c, m, mlen, state->nonce, 2U, state->k);
1421 $cipher = ParagonIE_Sodium_Core_ChaCha20::ietfStreamXorIc(
1422 $msg,
1423 $st->getCombinedNonce(),
1424 $st->getKey(),
1425 ParagonIE_Sodium_Core_Util::store64_le(2)
1426 );
1427
1428 # crypto_onetimeauth_poly1305_update(&poly1305_state, c, mlen);
1429 $auth->update($cipher);
1430
1431 $out .= $cipher;
1432 unset($cipher);
1433
1434 # crypto_onetimeauth_poly1305_update
1435 # (&poly1305_state, _pad0, (0x10 - (sizeof block) + mlen) & 0xf);
1436 $auth->update(str_repeat("\0", ((0x10 - 64 + $msglen) & 0xf)));
1437
1438 # STORE64_LE(slen, (uint64_t) adlen);
1439 $slen = ParagonIE_Sodium_Core_Util::store64_le($aadlen);
1440
1441 # crypto_onetimeauth_poly1305_update(&poly1305_state, slen, sizeof slen);
1442 $auth->update($slen);
1443
1444 # STORE64_LE(slen, (sizeof block) + mlen);
1445 $slen = ParagonIE_Sodium_Core_Util::store64_le(64 + $msglen);
1446
1447 # crypto_onetimeauth_poly1305_update(&poly1305_state, slen, sizeof slen);
1448 $auth->update($slen);
1449
1450 # mac = c + mlen;
1451 # crypto_onetimeauth_poly1305_final(&poly1305_state, mac);
1452 $mac = $auth->finish();
1453 $out .= $mac;
1454
1455 # sodium_memzero(&poly1305_state, sizeof poly1305_state);
1456 unset($auth);
1457
1458
1459 # XOR_BUF(STATE_INONCE(state), mac,
1460 # crypto_secretstream_xchacha20poly1305_INONCEBYTES);
1461 $st->xorNonce($mac);
1462
1463 # sodium_increment(STATE_COUNTER(state),
1464 # crypto_secretstream_xchacha20poly1305_COUNTERBYTES);
1465 $st->incrementCounter();
1466 // Overwrite by reference:
1467 $state = $st->toString();
1468
1469 /** @var bool $rekey */
1470 $rekey = ($tag & ParagonIE_Sodium_Compat::CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY) !== 0;
1471 # if ((tag & crypto_secretstream_xchacha20poly1305_TAG_REKEY) != 0 ||
1472 # sodium_is_zero(STATE_COUNTER(state),
1473 # crypto_secretstream_xchacha20poly1305_COUNTERBYTES)) {
1474 # crypto_secretstream_xchacha20poly1305_rekey(state);
1475 # }
1476 if ($rekey || $st->needsRekey()) {
1477 // DO REKEY
1478 self::secretstream_xchacha20poly1305_rekey($state);
1479 }
1480 # if (outlen_p != NULL) {
1481 # *outlen_p = crypto_secretstream_xchacha20poly1305_ABYTES + mlen;
1482 # }
1483 return $out;
1484 }
1485
1486 /**
1487 * @param string $state
1488 * @param string $cipher
1489 * @param string $aad
1490 * @return bool|array{0: string, 1: int}
1491 * @throws SodiumException
1492 */
1493 public static function secretstream_xchacha20poly1305_pull(
1494 #[SensitiveParameter]
1495 string &$state,
1496 string $cipher,
1497 string $aad = ''
1498 ): bool|array {
1499 $st = ParagonIE_Sodium_Core_SecretStream_State::fromString($state);
1500
1501 $cipherlen = ParagonIE_Sodium_Core_Util::strlen($cipher);
1502 # mlen = inlen - crypto_secretstream_xchacha20poly1305_ABYTES;
1503 $msglen = $cipherlen - ParagonIE_Sodium_Compat::CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES;
1504 $aadlen = ParagonIE_Sodium_Core_Util::strlen($aad);
1505
1506 # if (mlen > crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX) {
1507 # sodium_misuse();
1508 # }
1509 if ((($msglen + 63) >> 6) > 0xfffffffe) {
1510 throw new SodiumException(
1511 'message cannot be larger than SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX bytes'
1512 );
1513 }
1514
1515 # crypto_stream_chacha20_ietf(block, sizeof block, state->nonce, state->k);
1516 # crypto_onetimeauth_poly1305_init(&poly1305_state, block);
1517 # sodium_memzero(block, sizeof block);
1518 $auth = new ParagonIE_Sodium_Core_Poly1305_State(
1519 ParagonIE_Sodium_Core_ChaCha20::ietfStream(32, $st->getCombinedNonce(), $st->getKey())
1520 );
1521
1522 # crypto_onetimeauth_poly1305_update(&poly1305_state, ad, adlen);
1523 $auth->update($aad);
1524
1525 # crypto_onetimeauth_poly1305_update(&poly1305_state, _pad0,
1526 # (0x10 - adlen) & 0xf);
1527 $auth->update(str_repeat("\0", ((0x10 - $aadlen) & 0xf)));
1528
1529
1530 # memset(block, 0, sizeof block);
1531 # block[0] = in[0];
1532 # crypto_stream_chacha20_ietf_xor_ic(block, block, sizeof block,
1533 # state->nonce, 1U, state->k);
1534 $block = ParagonIE_Sodium_Core_ChaCha20::ietfStreamXorIc(
1535 $cipher[0] . str_repeat("\0", 63),
1536 $st->getCombinedNonce(),
1537 $st->getKey(),
1538 ParagonIE_Sodium_Core_Util::store64_le(1)
1539 );
1540 # tag = block[0];
1541 # block[0] = in[0];
1542 # crypto_onetimeauth_poly1305_update(&poly1305_state, block, sizeof block);
1543 $tag = ParagonIE_Sodium_Core_Util::chrToInt($block[0]);
1544 $block[0] = $cipher[0];
1545 $auth->update($block);
1546
1547
1548 # c = in + (sizeof tag);
1549 # crypto_onetimeauth_poly1305_update(&poly1305_state, c, mlen);
1550 $auth->update(ParagonIE_Sodium_Core_Util::substr($cipher, 1, $msglen));
1551
1552 # crypto_onetimeauth_poly1305_update
1553 # (&poly1305_state, _pad0, (0x10 - (sizeof block) + mlen) & 0xf);
1554 $auth->update(str_repeat("\0", ((0x10 - 64 + $msglen) & 0xf)));
1555
1556 # STORE64_LE(slen, (uint64_t) adlen);
1557 # crypto_onetimeauth_poly1305_update(&poly1305_state, slen, sizeof slen);
1558 $slen = ParagonIE_Sodium_Core_Util::store64_le($aadlen);
1559 $auth->update($slen);
1560
1561 # STORE64_LE(slen, (sizeof block) + mlen);
1562 # crypto_onetimeauth_poly1305_update(&poly1305_state, slen, sizeof slen);
1563 $slen = ParagonIE_Sodium_Core_Util::store64_le(64 + $msglen);
1564 $auth->update($slen);
1565
1566 # crypto_onetimeauth_poly1305_final(&poly1305_state, mac);
1567 # sodium_memzero(&poly1305_state, sizeof poly1305_state);
1568 $mac = $auth->finish();
1569
1570 # stored_mac = c + mlen;
1571 # if (sodium_memcmp(mac, stored_mac, sizeof mac) != 0) {
1572 # sodium_memzero(mac, sizeof mac);
1573 # return -1;
1574 # }
1575
1576 $stored = ParagonIE_Sodium_Core_Util::substr($cipher, $msglen + 1, 16);
1577 if (!ParagonIE_Sodium_Core_Util::hashEquals($mac, $stored)) {
1578 return false;
1579 }
1580
1581 # crypto_stream_chacha20_ietf_xor_ic(m, c, mlen, state->nonce, 2U, state->k);
1582 $out = ParagonIE_Sodium_Core_ChaCha20::ietfStreamXorIc(
1583 ParagonIE_Sodium_Core_Util::substr($cipher, 1, $msglen),
1584 $st->getCombinedNonce(),
1585 $st->getKey(),
1586 ParagonIE_Sodium_Core_Util::store64_le(2)
1587 );
1588
1589 # XOR_BUF(STATE_INONCE(state), mac,
1590 # crypto_secretstream_xchacha20poly1305_INONCEBYTES);
1591 $st->xorNonce($mac);
1592
1593 # sodium_increment(STATE_COUNTER(state),
1594 # crypto_secretstream_xchacha20poly1305_COUNTERBYTES);
1595 $st->incrementCounter();
1596
1597 # if ((tag & crypto_secretstream_xchacha20poly1305_TAG_REKEY) != 0 ||
1598 # sodium_is_zero(STATE_COUNTER(state),
1599 # crypto_secretstream_xchacha20poly1305_COUNTERBYTES)) {
1600 # crypto_secretstream_xchacha20poly1305_rekey(state);
1601 # }
1602
1603 // Overwrite by reference:
1604 $state = $st->toString();
1605
1606 /** @var bool $rekey */
1607 $rekey = ($tag & ParagonIE_Sodium_Compat::CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY) !== 0;
1608 if ($rekey || $st->needsRekey()) {
1609 // DO REKEY
1610 self::secretstream_xchacha20poly1305_rekey($state);
1611 }
1612 return array($out, $tag);
1613 }
1614
1615 /**
1616 * @param string $state
1617 * @return void
1618 * @throws SodiumException
1619 */
1620 public static function secretstream_xchacha20poly1305_rekey(
1621 #[SensitiveParameter]
1622 string &$state
1623 ): void {
1624 $st = ParagonIE_Sodium_Core_SecretStream_State::fromString($state);
1625 # unsigned char new_key_and_inonce[crypto_stream_chacha20_ietf_KEYBYTES +
1626 # crypto_secretstream_xchacha20poly1305_INONCEBYTES];
1627 # size_t i;
1628 # for (i = 0U; i < crypto_stream_chacha20_ietf_KEYBYTES; i++) {
1629 # new_key_and_inonce[i] = state->k[i];
1630 # }
1631 $new_key_and_inonce = $st->getKey();
1632
1633 # for (i = 0U; i < crypto_secretstream_xchacha20poly1305_INONCEBYTES; i++) {
1634 # new_key_and_inonce[crypto_stream_chacha20_ietf_KEYBYTES + i] =
1635 # STATE_INONCE(state)[i];
1636 # }
1637 $new_key_and_inonce .= ParagonIE_Sodium_Core_Util::substR($st->getNonce(), 0, 8);
1638
1639 # crypto_stream_chacha20_ietf_xor(new_key_and_inonce, new_key_and_inonce,
1640 # sizeof new_key_and_inonce,
1641 # state->nonce, state->k);
1642
1643 $st->rekey(ParagonIE_Sodium_Core_ChaCha20::ietfStreamXorIc(
1644 $new_key_and_inonce,
1645 $st->getCombinedNonce(),
1646 $st->getKey(),
1647 ParagonIE_Sodium_Core_Util::store64_le(0)
1648 ));
1649
1650 # for (i = 0U; i < crypto_stream_chacha20_ietf_KEYBYTES; i++) {
1651 # state->k[i] = new_key_and_inonce[i];
1652 # }
1653 # for (i = 0U; i < crypto_secretstream_xchacha20poly1305_INONCEBYTES; i++) {
1654 # STATE_INONCE(state)[i] =
1655 # new_key_and_inonce[crypto_stream_chacha20_ietf_KEYBYTES + i];
1656 # }
1657 # _crypto_secretstream_xchacha20poly1305_counter_reset(state);
1658 $st->counterReset();
1659
1660 $state = $st->toString();
1661 }
1662
1663 /**
1664 * Detached Ed25519 signature.
1665 *
1666 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
1667 *
1668 * @param string $message
1669 * @param string $sk
1670 * @return string
1671 * @throws SodiumException
1672 * @throws TypeError
1673 */
1674 public static function sign_detached(
1675 string $message,
1676 #[SensitiveParameter]
1677 string $sk
1678 ): string {
1679 return ParagonIE_Sodium_Core_Ed25519::sign_detached($message, $sk);
1680 }
1681
1682 /**
1683 * Attached Ed25519 signature. (Returns a signed message.)
1684 *
1685 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
1686 *
1687 * @param string $message
1688 * @param string $sk
1689 * @return string
1690 * @throws SodiumException
1691 * @throws TypeError
1692 */
1693 public static function sign(
1694 string $message,
1695 #[SensitiveParameter]
1696 string $sk
1697 ): string {
1698 return ParagonIE_Sodium_Core_Ed25519::sign($message, $sk);
1699 }
1700
1701 /**
1702 * Opens a signed message. If valid, returns the message.
1703 *
1704 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
1705 *
1706 * @param string $signedMessage
1707 * @param string $pk
1708 * @return string
1709 * @throws SodiumException
1710 * @throws TypeError
1711 */
1712 public static function sign_open(
1713 string $signedMessage,
1714 #[SensitiveParameter]
1715 string $pk
1716 ): string {
1717 return ParagonIE_Sodium_Core_Ed25519::sign_open($signedMessage, $pk);
1718 }
1719
1720 /**
1721 * Verify a detached signature of a given message and public key.
1722 *
1723 * @internal Do not use this directly. Use ParagonIE_Sodium_Compat.
1724 *
1725 * @param string $signature
1726 * @param string $message
1727 * @param string $pk
1728 * @return bool
1729 * @throws SodiumException
1730 * @throws TypeError
1731 */
1732 public static function sign_verify_detached(
1733 string $signature,
1734 string $message,
1735 string $pk
1736 ): bool {
1737 return ParagonIE_Sodium_Core_Ed25519::verify_detached($signature, $message, $pk);
1738 }
1739 }