Debian Codegraph @

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

raw symbols SCIP
1 <?php
2 declare(strict_types=1);
3
4 /**
5 * Libsodium compatibility layer
6 *
7 * This is the only class you should be interfacing with, as a user of
8 * sodium_compat.
9 *
10 * If the PHP extension for libsodium is installed, it will always use that
11 * instead of our implementations. You get better performance and stronger
12 * guarantees against side-channels that way.
13 *
14 * However, if your users don't have the PHP extension installed, we offer a
15 * compatible interface here. It will give you the correct results as if the
16 * PHP extension was installed. It won't be as fast, of course.
17 *
18 * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION *
19 * *
20 * Until audited, this is probably not safe to use! DANGER WILL ROBINSON *
21 * *
22 * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION *
23 */
24
25 if (class_exists('ParagonIE_Sodium_Compat', false)) {
26 return;
27 }
28
29 /**
30 * @api
31 *
32 * This class cannot be final due to the namespaced API.
33 */
34 class ParagonIE_Sodium_Compat
35 {
36 /**
37 * This parameter prevents the use of the PECL extension.
38 * It should only be used for unit testing.
39 *
40 * @var bool
41 */
42 public static bool $disableFallbackForUnitTests = false;
43
44 /**
45 * Use fast multiplication rather than our constant-time multiplication
46 * implementation. Can be enabled at runtime. Only enable this if you
47 * are absolutely certain that there is no timing leak on your platform.
48 *
49 * @var bool
50 */
51 public static bool $fastMult = false;
52
53 const LIBRARY_MAJOR_VERSION = 9;
54 const LIBRARY_MINOR_VERSION = 1;
55 const LIBRARY_VERSION_MAJOR = 9;
56 const LIBRARY_VERSION_MINOR = 1;
57 const VERSION_STRING = 'polyfill-1.0.8';
58
59 // From libsodium
60 const BASE64_VARIANT_ORIGINAL = 1;
61 const BASE64_VARIANT_ORIGINAL_NO_PADDING = 3;
62 const BASE64_VARIANT_URLSAFE = 5;
63 const BASE64_VARIANT_URLSAFE_NO_PADDING = 7;
64 const CRYPTO_AEAD_AES256GCM_KEYBYTES = 32;
65 const CRYPTO_AEAD_AES256GCM_NSECBYTES = 0;
66 const CRYPTO_AEAD_AES256GCM_NPUBBYTES = 12;
67 const CRYPTO_AEAD_AES256GCM_ABYTES = 16;
68 const CRYPTO_AEAD_AEGIS128L_KEYBYTES = 16;
69 const CRYPTO_AEAD_AEGIS128L_NSECBYTES = 0;
70 const CRYPTO_AEAD_AEGIS128L_NPUBBYTES = 16;
71 const CRYPTO_AEAD_AEGIS128L_ABYTES = 32;
72 const CRYPTO_AEAD_AEGIS256_KEYBYTES = 32;
73 const CRYPTO_AEAD_AEGIS256_NSECBYTES = 0;
74 const CRYPTO_AEAD_AEGIS256_NPUBBYTES = 32;
75 const CRYPTO_AEAD_AEGIS256_ABYTES = 32;
76 const CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = 32;
77 const CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES = 0;
78 const CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = 8;
79 const CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = 16;
80 const CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES = 32;
81 const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES = 0;
82 const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES = 12;
83 const CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES = 16;
84 const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES = 32;
85 const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES = 0;
86 const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES = 24;
87 const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES = 16;
88 const CRYPTO_AUTH_BYTES = 32;
89 const CRYPTO_AUTH_KEYBYTES = 32;
90 const CRYPTO_BOX_SEALBYTES = 16;
91 const CRYPTO_BOX_SECRETKEYBYTES = 32;
92 const CRYPTO_BOX_PUBLICKEYBYTES = 32;
93 const CRYPTO_BOX_KEYPAIRBYTES = 64;
94 const CRYPTO_BOX_MACBYTES = 16;
95 const CRYPTO_BOX_NONCEBYTES = 24;
96 const CRYPTO_BOX_SEEDBYTES = 32;
97 const CRYPTO_CORE_RISTRETTO255_BYTES = 32;
98 const CRYPTO_CORE_RISTRETTO255_SCALARBYTES = 32;
99 const CRYPTO_CORE_RISTRETTO255_HASHBYTES = 64;
100 const CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES = 64;
101 const CRYPTO_KDF_BYTES_MIN = 16;
102 const CRYPTO_KDF_BYTES_MAX = 64;
103 const CRYPTO_KDF_CONTEXTBYTES = 8;
104 const CRYPTO_KDF_KEYBYTES = 32;
105 const CRYPTO_KX_BYTES = 32;
106 const CRYPTO_KX_PRIMITIVE = 'x25519blake2b';
107 const CRYPTO_KX_SEEDBYTES = 32;
108 const CRYPTO_KX_KEYPAIRBYTES = 64;
109 const CRYPTO_KX_PUBLICKEYBYTES = 32;
110 const CRYPTO_KX_SECRETKEYBYTES = 32;
111 const CRYPTO_KX_SESSIONKEYBYTES = 32;
112 const CRYPTO_GENERICHASH_BYTES = 32;
113 const CRYPTO_GENERICHASH_BYTES_MIN = 16;
114 const CRYPTO_GENERICHASH_BYTES_MAX = 64;
115 const CRYPTO_GENERICHASH_KEYBYTES = 32;
116 const CRYPTO_GENERICHASH_KEYBYTES_MIN = 16;
117 const CRYPTO_GENERICHASH_KEYBYTES_MAX = 64;
118 const CRYPTO_PWHASH_SALTBYTES = 16;
119 const CRYPTO_PWHASH_STRPREFIX = '$argon2id$';
120 const CRYPTO_PWHASH_ALG_ARGON2I13 = 1;
121 const CRYPTO_PWHASH_ALG_ARGON2ID13 = 2;
122 const CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE = 33554432;
123 const CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE = 4;
124 const CRYPTO_PWHASH_MEMLIMIT_MODERATE = 134217728;
125 const CRYPTO_PWHASH_OPSLIMIT_MODERATE = 6;
126 const CRYPTO_PWHASH_MEMLIMIT_SENSITIVE = 536870912;
127 const CRYPTO_PWHASH_OPSLIMIT_SENSITIVE = 8;
128 const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES = 32;
129 const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX = '$7$';
130 const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE = 534288;
131 const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE = 16777216;
132 const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE = 33554432;
133 const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE = 1073741824;
134 const CRYPTO_SCALARMULT_BYTES = 32;
135 const CRYPTO_SCALARMULT_SCALARBYTES = 32;
136 const CRYPTO_SCALARMULT_RISTRETTO255_BYTES = 32;
137 const CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES = 32;
138 const CRYPTO_SHORTHASH_BYTES = 8;
139 const CRYPTO_SHORTHASH_KEYBYTES = 16;
140 const CRYPTO_SECRETBOX_KEYBYTES = 32;
141 const CRYPTO_SECRETBOX_MACBYTES = 16;
142 const CRYPTO_SECRETBOX_NONCEBYTES = 24;
143 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES = 17;
144 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES = 24;
145 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES = 32;
146 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH = 0;
147 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PULL = 1;
148 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY = 2;
149 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL = 3;
150 const CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX = 0x3fffffff80;
151 const CRYPTO_SIGN_BYTES = 64;
152 const CRYPTO_SIGN_SEEDBYTES = 32;
153 const CRYPTO_SIGN_PUBLICKEYBYTES = 32;
154 const CRYPTO_SIGN_SECRETKEYBYTES = 64;
155 const CRYPTO_SIGN_KEYPAIRBYTES = 96;
156 const CRYPTO_STREAM_KEYBYTES = 32;
157 const CRYPTO_STREAM_NONCEBYTES = 24;
158 const CRYPTO_STREAM_XCHACHA20_KEYBYTES = 32;
159 const CRYPTO_STREAM_XCHACHA20_NONCEBYTES = 24;
160
161 /**
162 * Add two numbers (little-endian unsigned), storing the value in the first
163 * parameter.
164 *
165 * This mutates $val.
166 *
167 * @param string $val
168 * @param string $addv
169 * @return void
170 * @throws SodiumException
171 */
172 public static function add(
173 #[SensitiveParameter]
174 string &$val,
175 #[SensitiveParameter]
176 string $addv
177 ): void {
178 $val_len = ParagonIE_Sodium_Core_Util::strlen($val);
179 $addv_len = ParagonIE_Sodium_Core_Util::strlen($addv);
180 if ($val_len !== $addv_len) {
181 throw new SodiumException('values must have the same length');
182 }
183 $A = ParagonIE_Sodium_Core_Util::stringToIntArray($val);
184 $B = ParagonIE_Sodium_Core_Util::stringToIntArray($addv);
185
186 $c = 0;
187 for ($i = 0; $i < $val_len; $i++) {
188 $c += ($A[$i] + $B[$i]);
189 $A[$i] = ($c & 0xff);
190 $c >>= 8;
191 }
192 $val = ParagonIE_Sodium_Core_Util::intArrayToString($A);
193 }
194
195 /**
196 * @param string $encoded
197 * @param int $variant
198 * @param string $ignore
199 * @return string
200 * @throws SodiumException
201 */
202 public static function base642bin(
203 #[SensitiveParameter]
204 string $encoded,
205 int $variant,
206 string $ignore = ''
207 ): string {
208 // Just strip before decoding
209 if (!empty($ignore)) {
210 $encoded = str_replace($ignore, '', $encoded);
211 }
212
213 try {
214 return match ($variant) {
215 self::BASE64_VARIANT_ORIGINAL =>
216 ParagonIE_Sodium_Core_Base64_Original::decode($encoded, true),
217 self::BASE64_VARIANT_ORIGINAL_NO_PADDING =>
218 ParagonIE_Sodium_Core_Base64_Original::decodeNoPadding($encoded),
219 self::BASE64_VARIANT_URLSAFE =>
220 ParagonIE_Sodium_Core_Base64_UrlSafe::decode($encoded, true),
221 self::BASE64_VARIANT_URLSAFE_NO_PADDING =>
222 ParagonIE_Sodium_Core_Base64_UrlSafe::decodeNoPadding($encoded),
223 default =>
224 throw new SodiumException('invalid base64 variant identifier'),
225 };
226 } catch (Exception $ex) {
227 if ($ex instanceof SodiumException) {
228 throw $ex;
229 }
230 throw new SodiumException('invalid base64 string', 0, $ex);
231 }
232 }
233
234 /**
235 * @param string $decoded
236 * @param int $variant
237 * @return string
238 * @throws SodiumException
239 */
240 public static function bin2base64(
241 #[SensitiveParameter]
242 string $decoded,
243 int $variant
244 ): string {
245 return match ($variant) {
246 self::BASE64_VARIANT_ORIGINAL =>
247 ParagonIE_Sodium_Core_Base64_Original::encode($decoded),
248 self::BASE64_VARIANT_ORIGINAL_NO_PADDING =>
249 ParagonIE_Sodium_Core_Base64_Original::encodeUnpadded($decoded),
250 self::BASE64_VARIANT_URLSAFE =>
251 ParagonIE_Sodium_Core_Base64_UrlSafe::encode($decoded),
252 self::BASE64_VARIANT_URLSAFE_NO_PADDING =>
253 ParagonIE_Sodium_Core_Base64_UrlSafe::encodeUnpadded($decoded),
254 default => throw new SodiumException('invalid base64 variant identifier'),
255 };
256 }
257
258 /**
259 * Cache-timing-safe implementation of bin2hex().
260 *
261 * @param string $string A string (probably raw binary)
262 * @return string A hexadecimal-encoded string
263 * @throws SodiumException
264 * @throws TypeError
265 */
266 public static function bin2hex(
267 #[SensitiveParameter]
268 string $string
269 ): string {
270 if (self::useNewSodiumAPI()) {
271 return sodium_bin2hex($string);
272 }
273 if (self::use_fallback('bin2hex')) {
274 return (string) call_user_func('\\Sodium\\bin2hex', $string);
275 }
276 return ParagonIE_Sodium_Core_Util::bin2hex($string);
277 }
278
279 /**
280 * Compare two strings, in constant-time.
281 * Compared to memcmp(), compare() is more useful for sorting.
282 *
283 * @param string $left The left operand; must be a string
284 * @param string $right The right operand; must be a string
285 * @return int If < 0 if the left operand is less than the right
286 * If = 0 if both strings are equal
287 * If > 0 if the right operand is less than the left
288 * @throws SodiumException
289 * @throws TypeError
290 */
291 public static function compare(
292 #[SensitiveParameter]
293 string $left,
294 #[SensitiveParameter]
295 string $right
296 ): int {
297 if (self::useNewSodiumAPI()) {
298 return sodium_compare($left, $right);
299 }
300 if (self::use_fallback('compare')) {
301 return (int) call_user_func('\\Sodium\\compare', $left, $right);
302 }
303 return ParagonIE_Sodium_Core_Util::compare($left, $right);
304 }
305
306 /**
307 * Authenticated Encryption with Associated Data: Decryption
308 *
309 * Algorithm:
310 * AEGIS-128L
311 *
312 * @param string $ciphertext Encrypted message (with MAC appended)
313 * @param string $assocData Authenticated Associated Data (unencrypted)
314 * @param string $nonce Number to be used only Once; must be 32 bytes
315 * @param string $key Encryption key
316 *
317 * @return string The original plaintext message
318 * @throws SodiumException
319 * @throws TypeError
320 */
321 public static function crypto_aead_aegis128l_decrypt(
322 string $ciphertext = '',
323 string $assocData = '',
324 string $nonce = '',
325 #[SensitiveParameter]
326 string $key = ''
327 ): string {
328 /* Input validation: */
329 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_AEGIS128L_NPUBBYTES) {
330 throw new SodiumException('Nonce must be CRYPTO_AEAD_AEGIS128L_NPUBBYTES long');
331 }
332 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_AEGIS128L_KEYBYTES) {
333 throw new SodiumException('Key must be CRYPTO_AEAD_AEGIS128L_KEYBYTES long');
334 }
335 $ct_length = ParagonIE_Sodium_Core_Util::strlen($ciphertext);
336 if ($ct_length < self::CRYPTO_AEAD_AEGIS128L_ABYTES) {
337 throw new SodiumException('Message must be at least CRYPTO_AEAD_AEGIS128L_ABYTES long');
338 }
339
340 $ct = ParagonIE_Sodium_Core_Util::substr(
341 $ciphertext,
342 0,
343 $ct_length - self::CRYPTO_AEAD_AEGIS128L_ABYTES
344 );
345 $tag = ParagonIE_Sodium_Core_Util::substr(
346 $ciphertext,
347 $ct_length - self::CRYPTO_AEAD_AEGIS128L_ABYTES,
348 self::CRYPTO_AEAD_AEGIS128L_ABYTES
349 );
350 return ParagonIE_Sodium_Core_AEGIS128L::decrypt($ct, $tag, $assocData, $key, $nonce);
351 }
352
353 /**
354 * Authenticated Encryption with Associated Data: Encryption
355 *
356 * Algorithm:
357 * AEGIS-128L
358 *
359 * @param string $plaintext Message to be encrypted
360 * @param string $assocData Authenticated Associated Data (unencrypted)
361 * @param string $nonce Number to be used only Once; must be 32 bytes
362 * @param string $key Encryption key
363 *
364 * @return string Ciphertext with 32-byte authentication tag appended
365 * @throws SodiumException
366 * @throws TypeError
367 */
368 public static function crypto_aead_aegis128l_encrypt(
369 #[SensitiveParameter]
370 string $plaintext = '',
371 string $assocData = '',
372 string $nonce = '',
373 #[SensitiveParameter]
374 string $key = ''
375 ): string {
376 /* Input validation: */
377 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_AEGIS128L_NPUBBYTES) {
378 throw new SodiumException('Nonce must be CRYPTO_AEAD_AEGIS128L_NPUBBYTES long');
379 }
380 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_AEGIS128L_KEYBYTES) {
381 throw new SodiumException('Key must be CRYPTO_AEAD_AEGIS128L_KEYBYTES long');
382 }
383
384 list($ct, $tag) = ParagonIE_Sodium_Core_AEGIS128L::encrypt($plaintext, $assocData, $key, $nonce);
385 return $ct . $tag;
386 }
387
388 /**
389 * Return a secure random key for use with the AEGIS-128L
390 * symmetric AEAD interface.
391 *
392 * @return string
393 * @throws Exception
394 * @throws Error
395 */
396 public static function crypto_aead_aegis128l_keygen(): string
397 {
398 return random_bytes(self::CRYPTO_AEAD_AEGIS128L_KEYBYTES);
399 }
400
401 /**
402 * Authenticated Encryption with Associated Data: Decryption
403 *
404 * Algorithm:
405 * AEGIS-256
406 *
407 * @param string $ciphertext Encrypted message (with MAC appended)
408 * @param string $assocData Authenticated Associated Data (unencrypted)
409 * @param string $nonce Number to be used only Once; must be 32 bytes
410 * @param string $key Encryption key
411 *
412 * @return string|bool The original plaintext message
413 * @throws SodiumException
414 * @throws TypeError
415 */
416 public static function crypto_aead_aegis256_decrypt(
417 string $ciphertext = '',
418 string $assocData = '',
419 string $nonce = '',
420 #[SensitiveParameter]
421 string $key = ''
422 ): string|bool {
423 /* Input validation: */
424 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_AEGIS256_NPUBBYTES) {
425 throw new SodiumException('Nonce must be CRYPTO_AEAD_AEGIS256_NPUBBYTES long');
426 }
427 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_AEGIS256_KEYBYTES) {
428 throw new SodiumException('Key must be CRYPTO_AEAD_AEGIS256_KEYBYTES long');
429 }
430 $ct_length = ParagonIE_Sodium_Core_Util::strlen($ciphertext);
431 if ($ct_length < self::CRYPTO_AEAD_AEGIS256_ABYTES) {
432 throw new SodiumException('Message must be at least CRYPTO_AEAD_AEGIS256_ABYTES long');
433 }
434
435 $ct = ParagonIE_Sodium_Core_Util::substr(
436 $ciphertext,
437 0,
438 $ct_length - self::CRYPTO_AEAD_AEGIS256_ABYTES
439 );
440 $tag = ParagonIE_Sodium_Core_Util::substr(
441 $ciphertext,
442 $ct_length - self::CRYPTO_AEAD_AEGIS256_ABYTES,
443 self::CRYPTO_AEAD_AEGIS256_ABYTES
444 );
445 return ParagonIE_Sodium_Core_AEGIS256::decrypt($ct, $tag, $assocData, $key, $nonce);
446 }
447
448 /**
449 * Authenticated Encryption with Associated Data: Encryption
450 *
451 * Algorithm:
452 * AEGIS-256
453 *
454 * @param string $plaintext Message to be encrypted
455 * @param string $assocData Authenticated Associated Data (unencrypted)
456 * @param string $nonce Number to be used only Once; must be 32 bytes
457 * @param string $key Encryption key
458 *
459 * @return string Ciphertext with 32-byte authentication tag appended
460 * @throws SodiumException
461 * @throws TypeError
462 */
463 public static function crypto_aead_aegis256_encrypt(
464 #[SensitiveParameter]
465 string $plaintext = '',
466 string $assocData = '',
467 string $nonce = '',
468 #[SensitiveParameter]
469 string $key = ''
470 ): string {
471 /* Input validation: */
472 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_AEGIS256_NPUBBYTES) {
473 throw new SodiumException('Nonce must be CRYPTO_AEAD_AEGIS256_NPUBBYTES long');
474 }
475 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_AEGIS256_KEYBYTES) {
476 throw new SodiumException('Key must be CRYPTO_AEAD_AEGIS256_KEYBYTES long');
477 }
478
479 list($ct, $tag) = ParagonIE_Sodium_Core_AEGIS256::encrypt($plaintext, $assocData, $key, $nonce);
480 return $ct . $tag;
481 }
482
483 /**
484 * Return a secure random key for use with the AEGIS-256
485 * symmetric AEAD interface.
486 *
487 * @return string
488 * @throws Exception
489 * @throws Error
490 */
491 public static function crypto_aead_aegis256_keygen(): string
492 {
493 return random_bytes(self::CRYPTO_AEAD_AEGIS256_KEYBYTES);
494 }
495
496 /**
497 * Is AES-256-GCM even available to use?
498 *
499 * @return bool
500 */
501 public static function crypto_aead_aes256gcm_is_available(): bool
502 {
503 if (self::useNewSodiumAPI()) {
504 return sodium_crypto_aead_aes256gcm_is_available();
505 }
506 if (self::use_fallback('crypto_aead_aes256gcm_is_available')) {
507 return call_user_func('\\Sodium\\crypto_aead_aes256gcm_is_available');
508 }
509 if (!extension_loaded('openssl')) {
510 return false;
511 }
512 if (!is_callable('openssl_encrypt') || !is_callable('openssl_decrypt')) {
513 // OpenSSL isn't installed
514 return false;
515 }
516 return in_array('aes-256-gcm', openssl_get_cipher_methods(), true);
517 }
518
519 /**
520 * Authenticated Encryption with Associated Data: Decryption
521 *
522 * Algorithm:
523 * AES-256-GCM
524 *
525 * This mode uses a 64-bit random nonce with a 64-bit counter.
526 * IETF mode uses a 96-bit random nonce with a 32-bit counter.
527 *
528 * @param string $ciphertext Encrypted message (with Poly1305 MAC appended)
529 * @param string $assocData Authenticated Associated Data (unencrypted)
530 * @param string $nonce Number to be used only Once; must be 8 bytes
531 * @param string $key Encryption key
532 *
533 * @return string|bool The original plaintext message
534 * @throws SodiumException
535 * @throws TypeError
536 */
537 public static function crypto_aead_aes256gcm_decrypt(
538 string $ciphertext = '',
539 string $assocData = '',
540 string $nonce = '',
541 #[SensitiveParameter]
542 string $key = ''
543 ): string|bool {
544 if (!self::crypto_aead_aes256gcm_is_available()) {
545 throw new SodiumException('AES-256-GCM is not available');
546 }
547 /* Input validation: */
548 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_AES256GCM_NPUBBYTES) {
549 throw new SodiumException('Nonce must be CRYPTO_AEAD_AES256GCM_NPUBBYTES long');
550 }
551 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_AES256GCM_KEYBYTES) {
552 throw new SodiumException('Key must be CRYPTO_AEAD_AES256GCM_KEYBYTES long');
553 }
554 if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) < self::CRYPTO_AEAD_AES256GCM_ABYTES) {
555 throw new SodiumException('Message must be at least CRYPTO_AEAD_AES256GCM_ABYTES long');
556 }
557 if (!extension_loaded('openssl')) {
558 throw new SodiumException('The OpenSSL extension is not installed');
559 }
560 if (!is_callable('openssl_decrypt')) {
561 throw new SodiumException('The OpenSSL extension is not installed, or openssl_decrypt() is not available');
562 }
563
564 $ctext = ParagonIE_Sodium_Core_Util::substr($ciphertext, 0, -self::CRYPTO_AEAD_AES256GCM_ABYTES);
565 $authTag = ParagonIE_Sodium_Core_Util::substr($ciphertext, -self::CRYPTO_AEAD_AES256GCM_ABYTES, 16);
566 return openssl_decrypt(
567 $ctext,
568 'aes-256-gcm',
569 $key,
570 OPENSSL_RAW_DATA,
571 $nonce,
572 $authTag,
573 $assocData
574 );
575 }
576
577 /**
578 * Authenticated Encryption with Associated Data: Encryption
579 *
580 * Algorithm:
581 * AES-256-GCM
582 *
583 * @param string $plaintext Message to be encrypted
584 * @param string $assocData Authenticated Associated Data (unencrypted)
585 * @param string $nonce Number to be used only Once; must be 8 bytes
586 * @param string $key Encryption key
587 *
588 * @return string Ciphertext with a 16-byte GCM message
589 * authentication code appended
590 * @throws SodiumException
591 * @throws TypeError
592 */
593 public static function crypto_aead_aes256gcm_encrypt(
594 #[SensitiveParameter]
595 string $plaintext = '',
596 string $assocData = '',
597 string $nonce = '',
598 #[SensitiveParameter]
599 string $key = ''
600 ): string {
601 if (!self::crypto_aead_aes256gcm_is_available()) {
602 throw new SodiumException('AES-256-GCM is not available');
603 }
604
605 /* Input validation: */
606 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_AES256GCM_NPUBBYTES) {
607 throw new SodiumException('Nonce must be CRYPTO_AEAD_AES256GCM_NPUBBYTES long');
608 }
609 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_AES256GCM_KEYBYTES) {
610 throw new SodiumException('Key must be CRYPTO_AEAD_AES256GCM_KEYBYTES long');
611 }
612
613 if (!extension_loaded('openssl')) {
614 throw new SodiumException('The OpenSSL extension is not installed');
615 }
616 if (!is_callable('openssl_encrypt')) {
617 throw new SodiumException('The OpenSSL extension is not installed, or openssl_encrypt() is not available');
618 }
619
620 $authTag = '';
621 $ciphertext = openssl_encrypt(
622 $plaintext,
623 'aes-256-gcm',
624 $key,
625 OPENSSL_RAW_DATA,
626 $nonce,
627 $authTag,
628 $assocData
629 );
630 if (!is_string($ciphertext)) {
631 throw new SodiumException('sodium_compat - openssl_encrypt() failed somehow)');
632 }
633 return $ciphertext . $authTag;
634 }
635
636 /**
637 * Return a secure random key for use with the AES-256-GCM
638 * symmetric AEAD interface.
639 *
640 * @return string
641 * @throws Exception
642 * @throws Error
643 */
644 public static function crypto_aead_aes256gcm_keygen(): string
645 {
646 return random_bytes(self::CRYPTO_AEAD_AES256GCM_KEYBYTES);
647 }
648
649 /**
650 * Authenticated Encryption with Associated Data: Decryption
651 *
652 * Algorithm:
653 * ChaCha20-Poly1305
654 *
655 * This mode uses a 64-bit random nonce with a 64-bit counter.
656 * IETF mode uses a 96-bit random nonce with a 32-bit counter.
657 *
658 * @param string $ciphertext Encrypted message (with Poly1305 MAC appended)
659 * @param string $assocData Authenticated Associated Data (unencrypted)
660 * @param string $nonce Number to be used only Once; must be 8 bytes
661 * @param string $key Encryption key
662 *
663 * @return string|bool The original plaintext message
664 * @throws SodiumException
665 * @throws TypeError
666 */
667 public static function crypto_aead_chacha20poly1305_decrypt(
668 string $ciphertext = '',
669 string $assocData = '',
670 string $nonce = '',
671 #[SensitiveParameter]
672 string $key = ''
673 ): string|bool {
674 /* Input validation: */
675 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES) {
676 throw new SodiumException('Nonce must be CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES long');
677 }
678 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
679 throw new SodiumException('Key must be CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
680 }
681 if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) < self::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES) {
682 throw new SodiumException('Message must be at least CRYPTO_AEAD_CHACHA20POLY1305_ABYTES long');
683 }
684
685 if (self::useNewSodiumAPI()) {
686 return sodium_crypto_aead_chacha20poly1305_decrypt(
687 $ciphertext,
688 $assocData,
689 $nonce,
690 $key
691 );
692 }
693 if (self::use_fallback('crypto_aead_chacha20poly1305_decrypt')) {
694 return call_user_func(
695 '\\Sodium\\crypto_aead_chacha20poly1305_decrypt',
696 $ciphertext,
697 $assocData,
698 $nonce,
699 $key
700 );
701 }
702 return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_decrypt(
703 $ciphertext,
704 $assocData,
705 $nonce,
706 $key
707 );
708 }
709
710 /**
711 * Authenticated Encryption with Associated Data
712 *
713 * Algorithm:
714 * ChaCha20-Poly1305
715 *
716 * This mode uses a 64-bit random nonce with a 64-bit counter.
717 * IETF mode uses a 96-bit random nonce with a 32-bit counter.
718 *
719 * @param string $plaintext Message to be encrypted
720 * @param string $assocData Authenticated Associated Data (unencrypted)
721 * @param string $nonce Number to be used only Once; must be 8 bytes
722 * @param string $key Encryption key
723 *
724 * @return string Ciphertext with a 16-byte Poly1305 message
725 * authentication code appended
726 * @throws SodiumException
727 * @throws TypeError
728 */
729 public static function crypto_aead_chacha20poly1305_encrypt(
730 #[SensitiveParameter]
731 string $plaintext = '',
732 string $assocData = '',
733 string $nonce = '',
734 #[SensitiveParameter]
735 string $key = ''
736 ): string {
737 /* Input validation: */
738 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES) {
739 throw new SodiumException('Nonce must be CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES long');
740 }
741 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
742 throw new SodiumException('Key must be CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
743 }
744
745 if (self::useNewSodiumAPI()) {
746 return sodium_crypto_aead_chacha20poly1305_encrypt(
747 $plaintext,
748 $assocData,
749 $nonce,
750 $key
751 );
752 }
753 if (self::use_fallback('crypto_aead_chacha20poly1305_encrypt')) {
754 return (string) call_user_func(
755 '\\Sodium\\crypto_aead_chacha20poly1305_encrypt',
756 $plaintext,
757 $assocData,
758 $nonce,
759 $key
760 );
761 }
762 return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_encrypt(
763 $plaintext,
764 $assocData,
765 $nonce,
766 $key
767 );
768 }
769
770 /**
771 * Authenticated Encryption with Associated Data: Decryption
772 *
773 * Algorithm:
774 * ChaCha20-Poly1305
775 *
776 * IETF mode uses a 96-bit random nonce with a 32-bit counter.
777 * Regular mode uses a 64-bit random nonce with a 64-bit counter.
778 *
779 * @param string $ciphertext Encrypted message (with Poly1305 MAC appended)
780 * @param string $assocData Authenticated Associated Data (unencrypted)
781 * @param string $nonce Number to be used only Once; must be 12 bytes
782 * @param string $key Encryption key
783 *
784 * @return string|bool The original plaintext message
785 * @throws SodiumException
786 * @throws TypeError
787 */
788 public static function crypto_aead_chacha20poly1305_ietf_decrypt(
789 string $ciphertext = '',
790 string $assocData = '',
791 string $nonce = '',
792 #[SensitiveParameter]
793 string $key = ''
794 ): string|bool {
795 /* Input validation: */
796 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES) {
797 throw new SodiumException('Nonce must be CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES long');
798 }
799 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
800 throw new SodiumException('Key must be CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
801 }
802 if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) < self::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES) {
803 throw new SodiumException('Message must be at least CRYPTO_AEAD_CHACHA20POLY1305_ABYTES long');
804 }
805
806 if (self::useNewSodiumAPI()) {
807 return sodium_crypto_aead_chacha20poly1305_ietf_decrypt(
808 $ciphertext,
809 $assocData,
810 $nonce,
811 $key
812 );
813 }
814 if (self::use_fallback('crypto_aead_chacha20poly1305_ietf_decrypt')) {
815 return call_user_func(
816 '\\Sodium\\crypto_aead_chacha20poly1305_ietf_decrypt',
817 $ciphertext,
818 $assocData,
819 $nonce,
820 $key
821 );
822 }
823 return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_ietf_decrypt(
824 $ciphertext,
825 $assocData,
826 $nonce,
827 $key
828 );
829 }
830
831 /**
832 * Return a secure random key for use with the ChaCha20-Poly1305
833 * symmetric AEAD interface.
834 *
835 * @return string
836 * @throws Exception
837 * @throws Error
838 */
839 public static function crypto_aead_chacha20poly1305_keygen(): string
840 {
841 return random_bytes(self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES);
842 }
843
844 /**
845 * Authenticated Encryption with Associated Data
846 *
847 * Algorithm:
848 * ChaCha20-Poly1305
849 *
850 * IETF mode uses a 96-bit random nonce with a 32-bit counter.
851 * Regular mode uses a 64-bit random nonce with a 64-bit counter.
852 *
853 * @param string $plaintext Message to be encrypted
854 * @param string $assocData Authenticated Associated Data (unencrypted)
855 * @param string $nonce Number to be used only Once; must be 8 bytes
856 * @param string $key Encryption key
857 *
858 * @return string Ciphertext with a 16-byte Poly1305 message
859 * authentication code appended
860 * @throws SodiumException
861 * @throws TypeError
862 */
863 public static function crypto_aead_chacha20poly1305_ietf_encrypt(
864 #[SensitiveParameter]
865 string $plaintext = '',
866 string $assocData = '',
867 string $nonce = '',
868 #[SensitiveParameter]
869 string $key = ''
870 ): string {
871 /* Input validation: */
872 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES) {
873 throw new SodiumException('Nonce must be CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES long');
874 }
875 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
876 throw new SodiumException('Key must be CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
877 }
878
879 if (self::useNewSodiumAPI()) {
880 return sodium_crypto_aead_chacha20poly1305_ietf_encrypt(
881 $plaintext,
882 $assocData,
883 $nonce,
884 $key
885 );
886 }
887 if (self::use_fallback('crypto_aead_chacha20poly1305_ietf_encrypt')) {
888 return (string) call_user_func(
889 '\\Sodium\\crypto_aead_chacha20poly1305_ietf_encrypt',
890 $plaintext,
891 $assocData,
892 $nonce,
893 $key
894 );
895 }
896 return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_ietf_encrypt(
897 $plaintext,
898 $assocData,
899 $nonce,
900 $key
901 );
902 }
903
904 /**
905 * Return a secure random key for use with the ChaCha20-Poly1305
906 * symmetric AEAD interface. (IETF version)
907 *
908 * @return string
909 * @throws Exception
910 * @throws Error
911 */
912 public static function crypto_aead_chacha20poly1305_ietf_keygen(): string
913 {
914 return random_bytes(self::CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES);
915 }
916
917 /**
918 * Authenticated Encryption with Associated Data: Decryption
919 *
920 * Algorithm:
921 * XChaCha20-Poly1305
922 *
923 * This mode uses a 64-bit random nonce with a 64-bit counter.
924 * IETF mode uses a 96-bit random nonce with a 32-bit counter.
925 *
926 * @param string $ciphertext Encrypted message (with Poly1305 MAC appended)
927 * @param string $assocData Authenticated Associated Data (unencrypted)
928 * @param string $nonce Number to be used only Once; must be 8 bytes
929 * @param string $key Encryption key
930 * @param bool $dontFallback Don't fallback to ext/sodium
931 *
932 * @return string|bool The original plaintext message
933 * @throws SodiumException
934 * @throws TypeError
935 */
936 public static function crypto_aead_xchacha20poly1305_ietf_decrypt(
937 string $ciphertext = '',
938 string $assocData = '',
939 string $nonce = '',
940 #[SensitiveParameter]
941 string $key = '',
942 bool $dontFallback = false
943 ): string|bool {
944 /* Input validation: */
945 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES) {
946 throw new SodiumException('Nonce must be CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES long');
947 }
948 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES) {
949 throw new SodiumException('Key must be CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES long');
950 }
951 if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) < self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES) {
952 throw new SodiumException('Message must be at least CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES long');
953 }
954 if (self::useNewSodiumAPI() && !$dontFallback) {
955 if (is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_decrypt')) {
956 return sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
957 $ciphertext,
958 $assocData,
959 $nonce,
960 $key
961 );
962 }
963 }
964
965 return ParagonIE_Sodium_Crypto::aead_xchacha20poly1305_ietf_decrypt(
966 $ciphertext,
967 $assocData,
968 $nonce,
969 $key
970 );
971 }
972
973 /**
974 * Authenticated Encryption with Associated Data
975 *
976 * Algorithm:
977 * XChaCha20-Poly1305
978 *
979 * This mode uses a 64-bit random nonce with a 64-bit counter.
980 * IETF mode uses a 96-bit random nonce with a 32-bit counter.
981 *
982 * @param string $plaintext Message to be encrypted
983 * @param string $assocData Authenticated Associated Data (unencrypted)
984 * @param string $nonce Number to be used only Once; must be 8 bytes
985 * @param string $key Encryption key
986 * @param bool $dontFallback Don't fallback to ext/sodium
987 *
988 * @return string Ciphertext with a 16-byte Poly1305 message
989 * authentication code appended
990 * @throws SodiumException
991 * @throws TypeError
992 */
993 public static function crypto_aead_xchacha20poly1305_ietf_encrypt(
994 #[SensitiveParameter]
995 string $plaintext = '',
996 string $assocData = '',
997 string $nonce = '',
998 #[SensitiveParameter]
999 string $key = '',
1000 bool $dontFallback = false
1001 ): string {
1002 /* Input validation: */
1003 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES) {
1004 throw new SodiumException('Nonce must be CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES long');
1005 }
1006 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES) {
1007 throw new SodiumException('Key must be CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES long');
1008 }
1009 if (self::useNewSodiumAPI() && !$dontFallback) {
1010 if (is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
1011 return sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
1012 $plaintext,
1013 $assocData,
1014 $nonce,
1015 $key
1016 );
1017 }
1018 }
1019
1020 return ParagonIE_Sodium_Crypto::aead_xchacha20poly1305_ietf_encrypt(
1021 $plaintext,
1022 $assocData,
1023 $nonce,
1024 $key
1025 );
1026 }
1027
1028 /**
1029 * Return a secure random key for use with the XChaCha20-Poly1305
1030 * symmetric AEAD interface.
1031 *
1032 * @return string
1033 * @throws Exception
1034 * @throws Error
1035 */
1036 public static function crypto_aead_xchacha20poly1305_ietf_keygen(): string
1037 {
1038 return random_bytes(self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES);
1039 }
1040
1041 /**
1042 * Authenticate a message. Uses symmetric-key cryptography.
1043 *
1044 * Algorithm:
1045 * HMAC-SHA512-256. Which is HMAC-SHA-512 truncated to 256 bits.
1046 * Not to be confused with HMAC-SHA-512/256 which would use the
1047 * SHA-512/256 hash function (uses different initial parameters
1048 * but still truncates to 256 bits to sidestep length-extension
1049 * attacks).
1050 *
1051 * @param string $message Message to be authenticated
1052 * @param string $key Symmetric authentication key
1053 * @return string Message authentication code
1054 * @throws SodiumException
1055 * @throws TypeError
1056 */
1057 public static function crypto_auth(
1058 string $message,
1059 #[SensitiveParameter]
1060 string $key
1061 ): string {
1062 /* Input validation: */
1063 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AUTH_KEYBYTES) {
1064 throw new SodiumException('Argument 2 must be CRYPTO_AUTH_KEYBYTES long.');
1065 }
1066
1067 if (self::useNewSodiumAPI()) {
1068 return sodium_crypto_auth($message, $key);
1069 }
1070 if (self::use_fallback('crypto_auth')) {
1071 return (string) call_user_func('\\Sodium\\crypto_auth', $message, $key);
1072 }
1073 return ParagonIE_Sodium_Crypto::auth($message, $key);
1074 }
1075
1076 /**
1077 * @return string
1078 * @throws Exception
1079 * @throws Error
1080 */
1081 public static function crypto_auth_keygen(): string
1082 {
1083 return random_bytes(self::CRYPTO_AUTH_KEYBYTES);
1084 }
1085
1086 /**
1087 * Verify the MAC of a message previously authenticated with crypto_auth.
1088 *
1089 * @param string $mac Message authentication code
1090 * @param string $message Message whose authenticity you are attempting to
1091 * verify (with a given MAC and key)
1092 * @param string $key Symmetric authentication key
1093 * @return bool TRUE if authenticated, FALSE otherwise
1094 * @throws SodiumException
1095 * @throws TypeError
1096 */
1097 public static function crypto_auth_verify(
1098 string $mac,
1099 string $message,
1100 #[SensitiveParameter]
1101 string $key
1102 ): bool {
1103
1104 /* Input validation: */
1105 if (ParagonIE_Sodium_Core_Util::strlen($mac) !== self::CRYPTO_AUTH_BYTES) {
1106 throw new SodiumException('Argument 1 must be CRYPTO_AUTH_BYTES long.');
1107 }
1108 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_AUTH_KEYBYTES) {
1109 throw new SodiumException('Argument 3 must be CRYPTO_AUTH_KEYBYTES long.');
1110 }
1111
1112 if (self::useNewSodiumAPI()) {
1113 return sodium_crypto_auth_verify($mac, $message, $key);
1114 }
1115 if (self::use_fallback('crypto_auth_verify')) {
1116 return (bool) call_user_func('\\Sodium\\crypto_auth_verify', $mac, $message, $key);
1117 }
1118 return ParagonIE_Sodium_Crypto::auth_verify($mac, $message, $key);
1119 }
1120
1121 /**
1122 * Authenticated asymmetric-key encryption. Both the sender and recipient
1123 * may decrypt messages.
1124 *
1125 * Algorithm: X25519-XSalsa20-Poly1305.
1126 * X25519: Elliptic-Curve Diffie Hellman over Curve25519.
1127 * XSalsa20: Extended-nonce variant of salsa20.
1128 * Poyl1305: Polynomial MAC for one-time message authentication.
1129 *
1130 * @param string $plaintext The message to be encrypted
1131 * @param string $nonce A Number to only be used Once; must be 24 bytes
1132 * @param string $keypair Your secret key and your recipient's public key
1133 * @return string Ciphertext with 16-byte Poly1305 MAC
1134 * @throws SodiumException
1135 * @throws TypeError
1136 */
1137 public static function crypto_box(
1138 #[SensitiveParameter]
1139 string $plaintext,
1140 string $nonce,
1141 #[SensitiveParameter]
1142 string $keypair
1143 ): string {
1144 /* Input validation: */
1145 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_BOX_NONCEBYTES) {
1146 throw new SodiumException('Argument 2 must be CRYPTO_BOX_NONCEBYTES long.');
1147 }
1148 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_BOX_KEYPAIRBYTES) {
1149 throw new SodiumException('Argument 3 must be CRYPTO_BOX_KEYPAIRBYTES long.');
1150 }
1151
1152 if (self::useNewSodiumAPI()) {
1153 return sodium_crypto_box($plaintext, $nonce, $keypair);
1154 }
1155 if (self::use_fallback('crypto_box')) {
1156 return (string) call_user_func('\\Sodium\\crypto_box', $plaintext, $nonce, $keypair);
1157 }
1158 return ParagonIE_Sodium_Crypto::box($plaintext, $nonce, $keypair);
1159 }
1160
1161 /**
1162 * Anonymous public-key encryption. Only the recipient may decrypt messages.
1163 *
1164 * Algorithm: X25519-XSalsa20-Poly1305, as with crypto_box.
1165 * The sender's X25519 keypair is ephemeral.
1166 * Nonce is generated from the BLAKE2b hash of both public keys.
1167 *
1168 * This provides ciphertext integrity.
1169 *
1170 * @param string $plaintext Message to be sealed
1171 * @param string $publicKey Your recipient's public key
1172 * @return string Sealed message that only your recipient can
1173 * decrypt
1174 * @throws SodiumException
1175 * @throws TypeError
1176 */
1177 public static function crypto_box_seal(
1178 #[SensitiveParameter]
1179 string $plaintext,
1180 string $publicKey
1181 ): string {
1182 /* Input validation: */
1183 if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !== self::CRYPTO_BOX_PUBLICKEYBYTES) {
1184 throw new SodiumException('Argument 2 must be CRYPTO_BOX_PUBLICKEYBYTES long.');
1185 }
1186
1187 if (self::useNewSodiumAPI()) {
1188 return sodium_crypto_box_seal($plaintext, $publicKey);
1189 }
1190 if (self::use_fallback('crypto_box_seal')) {
1191 return (string) call_user_func('\\Sodium\\crypto_box_seal', $plaintext, $publicKey);
1192 }
1193 return ParagonIE_Sodium_Crypto::box_seal($plaintext, $publicKey);
1194 }
1195
1196 /**
1197 * Opens a message encrypted with crypto_box_seal(). Requires
1198 * the recipient's keypair (sk || pk) to decrypt successfully.
1199 *
1200 * This validates ciphertext integrity.
1201 *
1202 * @param string $ciphertext Sealed message to be opened
1203 * @param string $keypair Your crypto_box keypair
1204 * @return string|bool The original plaintext message
1205 * @throws SodiumException
1206 * @throws TypeError
1207 */
1208 public static function crypto_box_seal_open(
1209 string $ciphertext,
1210 string $keypair
1211 ): string|bool {
1212 /* Input validation: */
1213 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_BOX_KEYPAIRBYTES) {
1214 throw new SodiumException('Argument 2 must be CRYPTO_BOX_KEYPAIRBYTES long.');
1215 }
1216
1217 if (self::useNewSodiumAPI()) {
1218 return sodium_crypto_box_seal_open($ciphertext, $keypair);
1219 }
1220 if (self::use_fallback('crypto_box_seal_open')) {
1221 return call_user_func('\\Sodium\\crypto_box_seal_open', $ciphertext, $keypair);
1222 }
1223 return ParagonIE_Sodium_Crypto::box_seal_open($ciphertext, $keypair);
1224 }
1225
1226 /**
1227 * Generate a new random X25519 keypair.
1228 *
1229 * @return string A 64-byte string; the first 32 are your secret key, while
1230 * the last 32 are your public key. crypto_box_secretkey()
1231 * and crypto_box_publickey() exist to separate them so you
1232 * don't accidentally get them mixed up!
1233 * @throws SodiumException
1234 * @throws TypeError
1235 */
1236 public static function crypto_box_keypair(): string
1237 {
1238 if (self::useNewSodiumAPI()) {
1239 return sodium_crypto_box_keypair();
1240 }
1241 if (self::use_fallback('crypto_box_keypair')) {
1242 return (string) call_user_func('\\Sodium\\crypto_box_keypair');
1243 }
1244 return ParagonIE_Sodium_Crypto::box_keypair();
1245 }
1246
1247 /**
1248 * Combine two keys into a keypair for use in library methods that expect
1249 * a keypair. This doesn't necessarily have to be the same person's keys.
1250 *
1251 * @param string $secretKey Secret key
1252 * @param string $publicKey Public key
1253 * @return string Keypair
1254 * @throws SodiumException
1255 * @throws TypeError
1256 */
1257 public static function crypto_box_keypair_from_secretkey_and_publickey(
1258 #[SensitiveParameter]
1259 string $secretKey,
1260 string $publicKey
1261 ): string {
1262 /* Input validation: */
1263 if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !== self::CRYPTO_BOX_SECRETKEYBYTES) {
1264 throw new SodiumException('Argument 1 must be CRYPTO_BOX_SECRETKEYBYTES long.');
1265 }
1266 if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !== self::CRYPTO_BOX_PUBLICKEYBYTES) {
1267 throw new SodiumException('Argument 2 must be CRYPTO_BOX_PUBLICKEYBYTES long.');
1268 }
1269
1270 if (self::useNewSodiumAPI()) {
1271 return sodium_crypto_box_keypair_from_secretkey_and_publickey($secretKey, $publicKey);
1272 }
1273 if (self::use_fallback('crypto_box_keypair_from_secretkey_and_publickey')) {
1274 return (string) call_user_func('\\Sodium\\crypto_box_keypair_from_secretkey_and_publickey', $secretKey, $publicKey);
1275 }
1276 return ParagonIE_Sodium_Crypto::box_keypair_from_secretkey_and_publickey($secretKey, $publicKey);
1277 }
1278
1279 /**
1280 * Decrypt a message previously encrypted with crypto_box().
1281 *
1282 * @param string $ciphertext Encrypted message
1283 * @param string $nonce Number to only be used Once; must be 24 bytes
1284 * @param string $keypair Your secret key and the sender's public key
1285 * @return string|bool The original plaintext message
1286 * @throws SodiumException
1287 * @throws TypeError
1288 */
1289 public static function crypto_box_open(
1290 string $ciphertext,
1291 string $nonce,
1292 #[SensitiveParameter]
1293 string $keypair
1294 ): string|bool {
1295 /* Input validation: */
1296 if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) < self::CRYPTO_BOX_MACBYTES) {
1297 throw new SodiumException('Argument 1 must be at least CRYPTO_BOX_MACBYTES long.');
1298 }
1299 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_BOX_NONCEBYTES) {
1300 throw new SodiumException('Argument 2 must be CRYPTO_BOX_NONCEBYTES long.');
1301 }
1302 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_BOX_KEYPAIRBYTES) {
1303 throw new SodiumException('Argument 3 must be CRYPTO_BOX_KEYPAIRBYTES long.');
1304 }
1305
1306 if (self::useNewSodiumAPI()) {
1307 return sodium_crypto_box_open($ciphertext, $nonce, $keypair);
1308 }
1309 if (self::use_fallback('crypto_box_open')) {
1310 return call_user_func('\\Sodium\\crypto_box_open', $ciphertext, $nonce, $keypair);
1311 }
1312 return ParagonIE_Sodium_Crypto::box_open($ciphertext, $nonce, $keypair);
1313 }
1314
1315 /**
1316 * Extract the public key from a crypto_box keypair.
1317 *
1318 * @param string $keypair Keypair containing secret and public key
1319 * @return string Your crypto_box public key
1320 * @throws SodiumException
1321 * @throws TypeError
1322 */
1323 public static function crypto_box_publickey(
1324 #[SensitiveParameter]
1325 string $keypair
1326 ): string {
1327 /* Input validation: */
1328 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_BOX_KEYPAIRBYTES) {
1329 throw new SodiumException('Argument 1 must be CRYPTO_BOX_KEYPAIRBYTES long.');
1330 }
1331
1332 if (self::useNewSodiumAPI()) {
1333 return sodium_crypto_box_publickey($keypair);
1334 }
1335 if (self::use_fallback('crypto_box_publickey')) {
1336 return (string) call_user_func('\\Sodium\\crypto_box_publickey', $keypair);
1337 }
1338 return ParagonIE_Sodium_Crypto::box_publickey($keypair);
1339 }
1340
1341 /**
1342 * Calculate the X25519 public key from a given X25519 secret key.
1343 *
1344 * @param string $secretKey Any X25519 secret key
1345 * @return string The corresponding X25519 public key
1346 * @throws SodiumException
1347 * @throws TypeError
1348 */
1349 public static function crypto_box_publickey_from_secretkey(
1350 string $secretKey
1351 ): string {
1352 /* Input validation: */
1353 if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !== self::CRYPTO_BOX_SECRETKEYBYTES) {
1354 throw new SodiumException('Argument 1 must be CRYPTO_BOX_SECRETKEYBYTES long.');
1355 }
1356
1357 if (self::useNewSodiumAPI()) {
1358 return sodium_crypto_box_publickey_from_secretkey($secretKey);
1359 }
1360 if (self::use_fallback('crypto_box_publickey_from_secretkey')) {
1361 return (string) call_user_func('\\Sodium\\crypto_box_publickey_from_secretkey', $secretKey);
1362 }
1363 return ParagonIE_Sodium_Crypto::box_publickey_from_secretkey($secretKey);
1364 }
1365
1366 /**
1367 * Extract the secret key from a crypto_box keypair.
1368 *
1369 * @param string $keypair
1370 * @return string Your crypto_box secret key
1371 * @throws SodiumException
1372 * @throws TypeError
1373 */
1374 public static function crypto_box_secretkey(
1375 #[SensitiveParameter]
1376 string $keypair
1377 ): string {
1378 /* Input validation: */
1379 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_BOX_KEYPAIRBYTES) {
1380 throw new SodiumException('Argument 1 must be CRYPTO_BOX_KEYPAIRBYTES long.');
1381 }
1382
1383 if (self::useNewSodiumAPI()) {
1384 return sodium_crypto_box_secretkey($keypair);
1385 }
1386 if (self::use_fallback('crypto_box_secretkey')) {
1387 return (string) call_user_func('\\Sodium\\crypto_box_secretkey', $keypair);
1388 }
1389 return ParagonIE_Sodium_Crypto::box_secretkey($keypair);
1390 }
1391
1392 /**
1393 * Generate an X25519 keypair from a seed.
1394 *
1395 * @param string $seed
1396 * @return string
1397 * @throws SodiumException
1398 * @throws TypeError
1399 */
1400 public static function crypto_box_seed_keypair(
1401 #[SensitiveParameter]
1402 string $seed
1403 ): string {
1404 if (self::useNewSodiumAPI()) {
1405 return sodium_crypto_box_seed_keypair($seed);
1406 }
1407 if (self::use_fallback('crypto_box_seed_keypair')) {
1408 return (string) call_user_func('\\Sodium\\crypto_box_seed_keypair', $seed);
1409 }
1410 return ParagonIE_Sodium_Crypto::box_seed_keypair($seed);
1411 }
1412
1413 /**
1414 * Calculates a BLAKE2b hash, with an optional key.
1415 *
1416 * @param string $message The message to be hashed
1417 * @param string|null $key If specified, must be a string between 16
1418 * and 64 bytes long
1419 * @param int $length Output length in bytes; must be between 16
1420 * and 64 (default = 32)
1421 * @return string Raw binary
1422 * @throws SodiumException
1423 * @throws TypeError
1424 */
1425 public static function crypto_generichash(
1426 string $message,
1427 #[SensitiveParameter]
1428 ?string $key = '',
1429 int $length = self::CRYPTO_GENERICHASH_BYTES
1430 ): string {
1431 if (is_null($key)) {
1432 $key = '';
1433 }
1434 /* Input validation: */
1435 if (!empty($key)) {
1436 if (ParagonIE_Sodium_Core_Util::strlen($key) < self::CRYPTO_GENERICHASH_KEYBYTES_MIN) {
1437 throw new SodiumException('Unsupported key size. Must be at least CRYPTO_GENERICHASH_KEYBYTES_MIN bytes long.');
1438 }
1439 if (ParagonIE_Sodium_Core_Util::strlen($key) > self::CRYPTO_GENERICHASH_KEYBYTES_MAX) {
1440 throw new SodiumException('Unsupported key size. Must be at most CRYPTO_GENERICHASH_KEYBYTES_MAX bytes long.');
1441 }
1442 }
1443
1444 if (self::useNewSodiumAPI()) {
1445 return sodium_crypto_generichash($message, $key, $length);
1446 }
1447 if (self::use_fallback('crypto_generichash')) {
1448 return (string) call_user_func('\\Sodium\\crypto_generichash', $message, $key, $length);
1449 }
1450 return ParagonIE_Sodium_Crypto::generichash($message, $key, $length);
1451 }
1452
1453 /**
1454 * Get the final BLAKE2b hash output for a given context.
1455 *
1456 * @param string $ctx BLAKE2 hashing context. Generated by crypto_generichash_init().
1457 * @param int $length Hash output size.
1458 * @return string Final BLAKE2b hash.
1459 * @throws SodiumException
1460 * @throws TypeError
1461 * @psalm-suppress ReferenceConstraintViolation
1462 */
1463 public static function crypto_generichash_final(
1464 string &$ctx,
1465 int $length = self::CRYPTO_GENERICHASH_BYTES
1466 ): string {
1467 if (self::useNewSodiumAPI()) {
1468 return sodium_crypto_generichash_final($ctx, $length);
1469 }
1470 if (self::use_fallback('crypto_generichash_final')) {
1471 $func = '\\Sodium\\crypto_generichash_final';
1472 return (string) $func($ctx, $length);
1473 }
1474 if ($length < 1) {
1475 try {
1476 self::memzero($ctx);
1477 } catch (SodiumException) {
1478 unset($ctx);
1479 }
1480 return '';
1481 }
1482 $result = ParagonIE_Sodium_Crypto::generichash_final($ctx, $length);
1483 try {
1484 self::memzero($ctx);
1485 } catch (SodiumException) {
1486 unset($ctx);
1487 }
1488 return $result;
1489 }
1490
1491 /**
1492 * Initialize a BLAKE2b hashing context, for use in a streaming interface.
1493 *
1494 * @param string|null $key If specified must be a string between 16 and 64 bytes
1495 * @param int $length The size of the desired hash output
1496 * @return string A BLAKE2 hashing context, encoded as a string
1497 * (To be 100% compatible with ext/libsodium)
1498 * @throws SodiumException
1499 * @throws TypeError
1500 */
1501 public static function crypto_generichash_init(
1502 #[SensitiveParameter]
1503 ?string $key = '',
1504 int $length = self::CRYPTO_GENERICHASH_BYTES
1505 ): string {
1506 if (is_null($key)) {
1507 $key = '';
1508 }
1509
1510 /* Input validation: */
1511 if (!empty($key)) {
1512 if (ParagonIE_Sodium_Core_Util::strlen($key) < self::CRYPTO_GENERICHASH_KEYBYTES_MIN) {
1513 throw new SodiumException('Unsupported key size. Must be at least CRYPTO_GENERICHASH_KEYBYTES_MIN bytes long.');
1514 }
1515 if (ParagonIE_Sodium_Core_Util::strlen($key) > self::CRYPTO_GENERICHASH_KEYBYTES_MAX) {
1516 throw new SodiumException('Unsupported key size. Must be at most CRYPTO_GENERICHASH_KEYBYTES_MAX bytes long.');
1517 }
1518 }
1519
1520 if (self::useNewSodiumAPI()) {
1521 return sodium_crypto_generichash_init($key, $length);
1522 }
1523 if (self::use_fallback('crypto_generichash_init')) {
1524 return (string) call_user_func('\\Sodium\\crypto_generichash_init', $key, $length);
1525 }
1526 return ParagonIE_Sodium_Crypto::generichash_init($key, $length);
1527 }
1528
1529 /**
1530 * Initialize a BLAKE2b hashing context, for use in a streaming interface.
1531 *
1532 * @param string|null $key If specified must be a string between 16 and 64 bytes
1533 * @param int $length The size of the desired hash output
1534 * @param string $salt Salt (up to 16 bytes)
1535 * @param string $personal Personalization string (up to 16 bytes)
1536 * @return string A BLAKE2 hashing context, encoded as a string
1537 * (To be 100% compatible with ext/libsodium)
1538 * @throws SodiumException
1539 * @throws TypeError
1540 */
1541 public static function crypto_generichash_init_salt_personal(
1542 #[SensitiveParameter]
1543 ?string $key = '',
1544 int $length = self::CRYPTO_GENERICHASH_BYTES,
1545 string $salt = '',
1546 string $personal = ''
1547 ): string {
1548 if (is_null($key)) {
1549 $key = '';
1550 }
1551 $salt = str_pad($salt, 16, "\0");
1552 $personal = str_pad($personal, 16, "\0");
1553
1554 /* Input validation: */
1555 if (!empty($key)) {
1556 if (ParagonIE_Sodium_Core_Util::strlen($key) > self::CRYPTO_GENERICHASH_KEYBYTES_MAX) {
1557 throw new SodiumException('Unsupported key size. Must be at most CRYPTO_GENERICHASH_KEYBYTES_MAX bytes long.');
1558 }
1559 }
1560 return ParagonIE_Sodium_Crypto::generichash_init_salt_personal($key, $length, $salt, $personal);
1561 }
1562
1563 /**
1564 * Update a BLAKE2b hashing context with additional data.
1565 *
1566 * @param string $ctx BLAKE2 hashing context. Generated by crypto_generichash_init().
1567 * $ctx is passed by reference and gets updated in-place.
1568 * @param-out string $ctx
1569 * @param string $message The message to append to the existing hash state.
1570 * @return void
1571 * @throws SodiumException
1572 * @throws TypeError
1573 */
1574 public static function crypto_generichash_update(string &$ctx, string $message): void
1575 {
1576 if (self::useNewSodiumAPI()) {
1577 sodium_crypto_generichash_update($ctx, $message);
1578 return;
1579 }
1580 if (self::use_fallback('crypto_generichash_update')) {
1581 $func = '\\Sodium\\crypto_generichash_update';
1582 $func($ctx, $message);
1583 return;
1584 }
1585 $ctx = ParagonIE_Sodium_Crypto::generichash_update($ctx, $message);
1586 }
1587
1588 /**
1589 * @return string
1590 * @throws Exception
1591 * @throws Error
1592 */
1593 public static function crypto_generichash_keygen(): string
1594 {
1595 return random_bytes(self::CRYPTO_GENERICHASH_KEYBYTES);
1596 }
1597
1598 /**
1599 * @param int $subkey_len
1600 * @param int $subkey_id
1601 * @param string $context
1602 * @param string $key
1603 * @return string
1604 * @throws SodiumException
1605 */
1606 public static function crypto_kdf_derive_from_key(
1607 int $subkey_len,
1608 int $subkey_id,
1609 string $context,
1610 #[SensitiveParameter]
1611 string $key
1612 ): string {
1613 if ($subkey_len < self::CRYPTO_KDF_BYTES_MIN) {
1614 throw new SodiumException('subkey cannot be smaller than SODIUM_CRYPTO_KDF_BYTES_MIN');
1615 }
1616 if ($subkey_len > self::CRYPTO_KDF_BYTES_MAX) {
1617 throw new SodiumException('subkey cannot be larger than SODIUM_CRYPTO_KDF_BYTES_MAX');
1618 }
1619 if ($subkey_id < 0) {
1620 throw new SodiumException('subkey_id cannot be negative');
1621 }
1622 if (ParagonIE_Sodium_Core_Util::strlen($context) !== self::CRYPTO_KDF_CONTEXTBYTES) {
1623 throw new SodiumException('context should be SODIUM_CRYPTO_KDF_CONTEXTBYTES bytes');
1624 }
1625 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_KDF_KEYBYTES) {
1626 throw new SodiumException('key should be SODIUM_CRYPTO_KDF_KEYBYTES bytes');
1627 }
1628
1629 $salt = ParagonIE_Sodium_Core_Util::store64_le($subkey_id);
1630 $state = self::crypto_generichash_init_salt_personal(
1631 $key,
1632 $subkey_len,
1633 $salt,
1634 $context
1635 );
1636 return self::crypto_generichash_final($state, $subkey_len);
1637 }
1638
1639 /**
1640 * @return string
1641 * @throws Exception
1642 * @throws Error
1643 */
1644 public static function crypto_kdf_keygen(): string
1645 {
1646 return random_bytes(self::CRYPTO_KDF_KEYBYTES);
1647 }
1648
1649 /**
1650 * Perform a key exchange, between a designated client and a server.
1651 *
1652 * Typically, you would designate one machine to be the client and the
1653 * other to be the server. The first two keys are what you'd expect for
1654 * scalarmult() below, but the latter two public keys don't swap places.
1655 *
1656 * | ALICE | BOB |
1657 * | Client | Server |
1658 * |--------------------------------|-------------------------------------|
1659 * | shared = crypto_kx( | shared = crypto_kx( |
1660 * | alice_sk, | bob_sk, | <- contextual
1661 * | bob_pk, | alice_pk, | <- contextual
1662 * | alice_pk, | alice_pk, | <----- static
1663 * | bob_pk | bob_pk | <----- static
1664 * | ) | ) |
1665 *
1666 * They are used along with the scalarmult product to generate a 256-bit
1667 * BLAKE2b hash unique to the client and server keys.
1668 *
1669 * @param string $my_secret
1670 * @param string $their_public
1671 * @param string $client_public
1672 * @param string $server_public
1673 * @param bool $dontFallback
1674 * @return string
1675 * @throws SodiumException
1676 * @throws TypeError
1677 */
1678 public static function crypto_kx(
1679 #[SensitiveParameter]
1680 string $my_secret,
1681 string $their_public,
1682 string $client_public,
1683 string $server_public,
1684 bool $dontFallback = false
1685 ): string {
1686 /* Input validation: */
1687 if (ParagonIE_Sodium_Core_Util::strlen($my_secret) !== self::CRYPTO_BOX_SECRETKEYBYTES) {
1688 throw new SodiumException('Argument 1 must be CRYPTO_BOX_SECRETKEYBYTES long.');
1689 }
1690 if (ParagonIE_Sodium_Core_Util::strlen($their_public) !== self::CRYPTO_BOX_PUBLICKEYBYTES) {
1691 throw new SodiumException('Argument 2 must be CRYPTO_BOX_PUBLICKEYBYTES long.');
1692 }
1693 if (ParagonIE_Sodium_Core_Util::strlen($client_public) !== self::CRYPTO_BOX_PUBLICKEYBYTES) {
1694 throw new SodiumException('Argument 3 must be CRYPTO_BOX_PUBLICKEYBYTES long.');
1695 }
1696 if (ParagonIE_Sodium_Core_Util::strlen($server_public) !== self::CRYPTO_BOX_PUBLICKEYBYTES) {
1697 throw new SodiumException('Argument 4 must be CRYPTO_BOX_PUBLICKEYBYTES long.');
1698 }
1699
1700 if (self::useNewSodiumAPI() && !$dontFallback) {
1701 if (is_callable('sodium_crypto_kx')) {
1702 return sodium_crypto_kx(
1703 $my_secret,
1704 $their_public,
1705 $client_public,
1706 $server_public
1707 );
1708 }
1709 }
1710 if (self::use_fallback('crypto_kx')) {
1711 return call_user_func(
1712 '\\Sodium\\crypto_kx',
1713 $my_secret,
1714 $their_public,
1715 $client_public,
1716 $server_public
1717 );
1718 }
1719 return ParagonIE_Sodium_Crypto::keyExchange(
1720 $my_secret,
1721 $their_public,
1722 $client_public,
1723 $server_public
1724 );
1725 }
1726
1727 /**
1728 * @param string $seed
1729 * @return string
1730 * @throws SodiumException
1731 */
1732 public static function crypto_kx_seed_keypair(
1733 #[SensitiveParameter]
1734 string $seed
1735 ): string {
1736 if (ParagonIE_Sodium_Core_Util::strlen($seed) !== self::CRYPTO_KX_SEEDBYTES) {
1737 throw new SodiumException('seed must be SODIUM_CRYPTO_KX_SEEDBYTES bytes');
1738 }
1739
1740 $sk = self::crypto_generichash($seed, '', self::CRYPTO_KX_SECRETKEYBYTES);
1741 $pk = self::crypto_scalarmult_base($sk);
1742 return $sk . $pk;
1743 }
1744
1745 /**
1746 * @return string
1747 * @throws Exception
1748 */
1749 public static function crypto_kx_keypair(): string
1750 {
1751 $sk = self::randombytes_buf(self::CRYPTO_KX_SECRETKEYBYTES);
1752 $pk = self::crypto_scalarmult_base($sk);
1753 return $sk . $pk;
1754 }
1755
1756 /**
1757 * @param string $keypair
1758 * @param string $serverPublicKey
1759 * @return array{0: string, 1: string}
1760 * @throws SodiumException
1761 */
1762 public static function crypto_kx_client_session_keys(
1763 #[SensitiveParameter]
1764 string $keypair,
1765 string $serverPublicKey
1766 ): array {
1767 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_KX_KEYPAIRBYTES) {
1768 throw new SodiumException('keypair should be SODIUM_CRYPTO_KX_KEYPAIRBYTES bytes');
1769 }
1770 if (ParagonIE_Sodium_Core_Util::strlen($serverPublicKey) !== self::CRYPTO_KX_PUBLICKEYBYTES) {
1771 throw new SodiumException('public keys must be SODIUM_CRYPTO_KX_PUBLICKEYBYTES bytes');
1772 }
1773
1774 $sk = self::crypto_kx_secretkey($keypair);
1775 $pk = self::crypto_kx_publickey($keypair);
1776 $h = self::crypto_generichash_init(null, self::CRYPTO_KX_SESSIONKEYBYTES * 2);
1777 self::crypto_generichash_update($h, self::crypto_scalarmult($sk, $serverPublicKey));
1778 self::crypto_generichash_update($h, $pk);
1779 self::crypto_generichash_update($h, $serverPublicKey);
1780 $sessionKeys = self::crypto_generichash_final($h, self::CRYPTO_KX_SESSIONKEYBYTES * 2);
1781 return array(
1782 ParagonIE_Sodium_Core_Util::substr(
1783 $sessionKeys,
1784 0,
1785 self::CRYPTO_KX_SESSIONKEYBYTES
1786 ),
1787 ParagonIE_Sodium_Core_Util::substr(
1788 $sessionKeys,
1789 self::CRYPTO_KX_SESSIONKEYBYTES,
1790 self::CRYPTO_KX_SESSIONKEYBYTES
1791 )
1792 );
1793 }
1794
1795 /**
1796 * @param string $keypair
1797 * @param string $clientPublicKey
1798 * @return array{0: string, 1: string}
1799 * @throws SodiumException
1800 */
1801 public static function crypto_kx_server_session_keys(
1802 #[SensitiveParameter]
1803 string $keypair,
1804 string $clientPublicKey
1805 ): array {
1806 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_KX_KEYPAIRBYTES) {
1807 throw new SodiumException('keypair should be SODIUM_CRYPTO_KX_KEYPAIRBYTES bytes');
1808 }
1809 if (ParagonIE_Sodium_Core_Util::strlen($clientPublicKey) !== self::CRYPTO_KX_PUBLICKEYBYTES) {
1810 throw new SodiumException('public keys must be SODIUM_CRYPTO_KX_PUBLICKEYBYTES bytes');
1811 }
1812
1813 $sk = self::crypto_kx_secretkey($keypair);
1814 $pk = self::crypto_kx_publickey($keypair);
1815 $h = self::crypto_generichash_init(null, self::CRYPTO_KX_SESSIONKEYBYTES * 2);
1816 self::crypto_generichash_update($h, self::crypto_scalarmult($sk, $clientPublicKey));
1817 self::crypto_generichash_update($h, $clientPublicKey);
1818 self::crypto_generichash_update($h, $pk);
1819 $sessionKeys = self::crypto_generichash_final($h, self::CRYPTO_KX_SESSIONKEYBYTES * 2);
1820 return array(
1821 ParagonIE_Sodium_Core_Util::substr(
1822 $sessionKeys,
1823 self::CRYPTO_KX_SESSIONKEYBYTES,
1824 self::CRYPTO_KX_SESSIONKEYBYTES
1825 ),
1826 ParagonIE_Sodium_Core_Util::substr(
1827 $sessionKeys,
1828 0,
1829 self::CRYPTO_KX_SESSIONKEYBYTES
1830 )
1831 );
1832 }
1833
1834 /**
1835 * @param string $kp
1836 * @return string
1837 * @throws SodiumException
1838 */
1839 public static function crypto_kx_secretkey(
1840 #[SensitiveParameter]
1841 string $kp
1842 ): string {
1843 return ParagonIE_Sodium_Core_Util::substr(
1844 $kp,
1845 0,
1846 self::CRYPTO_KX_SECRETKEYBYTES
1847 );
1848 }
1849
1850 /**
1851 * @param string $kp
1852 * @return string
1853 * @throws SodiumException
1854 */
1855 public static function crypto_kx_publickey(
1856 string $kp
1857 ): string {
1858 return ParagonIE_Sodium_Core_Util::substr(
1859 $kp,
1860 self::CRYPTO_KX_SECRETKEYBYTES,
1861 self::CRYPTO_KX_PUBLICKEYBYTES
1862 );
1863 }
1864
1865 /**
1866 * @param int $outlen
1867 * @param string $passwd
1868 * @param string $salt
1869 * @param int $opslimit
1870 * @param int $memlimit
1871 * @param int|null $alg
1872 * @return string
1873 * @throws SodiumException
1874 * @throws TypeError
1875 */
1876 public static function crypto_pwhash(
1877 int $outlen,
1878 #[SensitiveParameter]
1879 string $passwd,
1880 #[SensitiveParameter]
1881 string $salt,
1882 int $opslimit,
1883 int $memlimit,
1884 ?int $alg = null
1885 ): string {
1886 if (self::useNewSodiumAPI()) {
1887 if (!is_null($alg)) {
1888 return sodium_crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit, $alg);
1889 }
1890 return sodium_crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit);
1891 }
1892 if (self::use_fallback('crypto_pwhash')) {
1893 return (string) call_user_func('\\Sodium\\crypto_pwhash', $outlen, $passwd, $salt, $opslimit, $memlimit);
1894 }
1895 // This is the best we can do.
1896 throw new SodiumException(
1897 'This is not implemented, as it is not possible to implement Argon2i with acceptable performance in pure-PHP'
1898 );
1899 }
1900
1901 /**
1902 * !Exclusive to sodium_compat!
1903 *
1904 * This returns TRUE if the native crypto_pwhash API is available by libsodium.
1905 * This returns FALSE if only sodium_compat is available.
1906 *
1907 * @return bool
1908 */
1909 public static function crypto_pwhash_is_available(): bool
1910 {
1911 if (self::useNewSodiumAPI()) {
1912 return true;
1913 }
1914 if (self::use_fallback('crypto_pwhash')) {
1915 return true;
1916 }
1917 return false;
1918 }
1919
1920 /**
1921 * @param string $passwd
1922 * @param int $opslimit
1923 * @param int $memlimit
1924 * @return string
1925 * @throws SodiumException
1926 * @throws TypeError
1927 */
1928 public static function crypto_pwhash_str(
1929 #[SensitiveParameter]
1930 string $passwd,
1931 int $opslimit,
1932 int $memlimit
1933 ): string {
1934 if (self::useNewSodiumAPI()) {
1935 return sodium_crypto_pwhash_str($passwd, $opslimit, $memlimit);
1936 }
1937 if (self::use_fallback('crypto_pwhash_str')) {
1938 return (string) call_user_func('\\Sodium\\crypto_pwhash_str', $passwd, $opslimit, $memlimit);
1939 }
1940 // This is the best we can do.
1941 throw new SodiumException(
1942 'This is not implemented, as it is not possible to implement Argon2i with acceptable performance in pure-PHP'
1943 );
1944 }
1945
1946 /**
1947 * Do we need to rehash this password?
1948 *
1949 * @param string $hash
1950 * @param int $opslimit
1951 * @param int $memlimit
1952 * @return bool
1953 * @throws SodiumException
1954 */
1955 public static function crypto_pwhash_str_needs_rehash(
1956 #[SensitiveParameter]
1957 string $hash,
1958 int $opslimit,
1959 int $memlimit
1960 ): bool {
1961 // Just grab the first 4 pieces.
1962 $pieces = explode('$', $hash);
1963 $prefix = implode('$', array_slice($pieces, 0, 4));
1964
1965 // Rebuild the expected header.
1966 $ops = $opslimit;
1967 $mem = $memlimit >> 10;
1968 $encoded = self::CRYPTO_PWHASH_STRPREFIX . 'v=19$m=' . $mem . ',t=' . $ops . ',p=1';
1969
1970 // Do they match? If so, we don't need to rehash, so return false.
1971 return !ParagonIE_Sodium_Core_Util::hashEquals($encoded, $prefix);
1972 }
1973
1974 /**
1975 * @param string $passwd
1976 * @param string $hash
1977 * @return bool
1978 * @throws SodiumException
1979 * @throws TypeError
1980 */
1981 public static function crypto_pwhash_str_verify(
1982 #[SensitiveParameter]
1983 string $passwd,
1984 #[SensitiveParameter]
1985 string $hash
1986 ): bool {
1987 if (self::useNewSodiumAPI()) {
1988 return sodium_crypto_pwhash_str_verify($passwd, $hash);
1989 }
1990 if (self::use_fallback('crypto_pwhash_str_verify')) {
1991 return (bool) call_user_func('\\Sodium\\crypto_pwhash_str_verify', $passwd, $hash);
1992 }
1993 // This is the best we can do.
1994 throw new SodiumException(
1995 'This is not implemented, as it is not possible to implement Argon2i with acceptable performance in pure-PHP'
1996 );
1997 }
1998
1999 /**
2000 * @param int $outlen
2001 * @param string $passwd
2002 * @param string $salt
2003 * @param int $opslimit
2004 * @param int $memlimit
2005 * @return string
2006 * @throws SodiumException
2007 * @throws TypeError
2008 */
2009 public static function crypto_pwhash_scryptsalsa208sha256(
2010 int $outlen,
2011 #[SensitiveParameter]
2012 string $passwd,
2013 #[SensitiveParameter]
2014 string $salt,
2015 int $opslimit,
2016 int $memlimit
2017 ): string {
2018 if (self::useNewSodiumAPI()) {
2019 return sodium_crypto_pwhash_scryptsalsa208sha256(
2020 $outlen,
2021 $passwd,
2022 $salt,
2023 $opslimit,
2024 $memlimit
2025 );
2026 }
2027 if (self::use_fallback('crypto_pwhash_scryptsalsa208sha256')) {
2028 return (string) call_user_func(
2029 '\\Sodium\\crypto_pwhash_scryptsalsa208sha256',
2030 $outlen,
2031 $passwd,
2032 $salt,
2033 $opslimit,
2034 $memlimit
2035 );
2036 }
2037 // This is the best we can do.
2038 throw new SodiumException(
2039 'This is not implemented, as it is not possible to implement Scrypt with acceptable performance in pure-PHP'
2040 );
2041 }
2042
2043 /**
2044 * !Exclusive to sodium_compat!
2045 *
2046 * This returns TRUE if the native crypto_pwhash API is available by libsodium.
2047 * This returns FALSE if only sodium_compat is available.
2048 *
2049 * @return bool
2050 */
2051 public static function crypto_pwhash_scryptsalsa208sha256_is_available(): bool
2052 {
2053 if (self::useNewSodiumAPI()) {
2054 return true;
2055 }
2056 if (self::use_fallback('crypto_pwhash_scryptsalsa208sha256')) {
2057 return true;
2058 }
2059 return false;
2060 }
2061
2062 /**
2063 * @param string $passwd
2064 * @param int $opslimit
2065 * @param int $memlimit
2066 * @return string
2067 * @throws SodiumException
2068 * @throws TypeError
2069 */
2070 public static function crypto_pwhash_scryptsalsa208sha256_str(
2071 #[SensitiveParameter]
2072 string $passwd,
2073 int $opslimit,
2074 int $memlimit
2075 ): string {
2076 if (self::useNewSodiumAPI()) {
2077 return sodium_crypto_pwhash_scryptsalsa208sha256_str(
2078 $passwd,
2079 $opslimit,
2080 $memlimit
2081 );
2082 }
2083 if (self::use_fallback('crypto_pwhash_scryptsalsa208sha256_str')) {
2084 return (string) call_user_func(
2085 '\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str',
2086 $passwd,
2087 $opslimit,
2088 $memlimit
2089 );
2090 }
2091 // This is the best we can do.
2092 throw new SodiumException(
2093 'This is not implemented, as it is not possible to implement Scrypt with acceptable performance in pure-PHP'
2094 );
2095 }
2096
2097 /**
2098 * @param string $passwd
2099 * @param string $hash
2100 * @return bool
2101 * @throws SodiumException
2102 * @throws TypeError
2103 */
2104 public static function crypto_pwhash_scryptsalsa208sha256_str_verify(
2105 #[SensitiveParameter]
2106 string $passwd,
2107 #[SensitiveParameter]
2108 string $hash
2109 ): bool {
2110 if (self::useNewSodiumAPI()) {
2111 return sodium_crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash);
2112 }
2113 if (self::use_fallback('crypto_pwhash_scryptsalsa208sha256_str_verify')) {
2114 return (bool) call_user_func(
2115 '\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str_verify',
2116 $passwd,
2117 $hash
2118 );
2119 }
2120 // This is the best we can do.
2121 throw new SodiumException(
2122 'This is not implemented, as it is not possible to implement Scrypt with acceptable performance in pure-PHP'
2123 );
2124 }
2125
2126 /**
2127 * Calculate the shared secret between your secret key and your
2128 * recipient's public key.
2129 *
2130 * Algorithm: X25519 (ECDH over Curve25519)
2131 *
2132 * @param string $secretKey
2133 * @param string $publicKey
2134 * @return string
2135 * @throws SodiumException
2136 * @throws TypeError
2137 */
2138 public static function crypto_scalarmult(
2139 #[SensitiveParameter]
2140 string $secretKey,
2141 string $publicKey
2142 ): string {
2143 /* Input validation: */
2144 if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !== self::CRYPTO_BOX_SECRETKEYBYTES) {
2145 throw new SodiumException('Argument 1 must be CRYPTO_BOX_SECRETKEYBYTES long.');
2146 }
2147 if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !== self::CRYPTO_BOX_PUBLICKEYBYTES) {
2148 throw new SodiumException('Argument 2 must be CRYPTO_BOX_PUBLICKEYBYTES long.');
2149 }
2150
2151 if (self::useNewSodiumAPI()) {
2152 return sodium_crypto_scalarmult($secretKey, $publicKey);
2153 }
2154 if (self::use_fallback('crypto_scalarmult')) {
2155 return (string) call_user_func('\\Sodium\\crypto_scalarmult', $secretKey, $publicKey);
2156 }
2157
2158 /* Output validation: Forbid all-zero keys */
2159 if (ParagonIE_Sodium_Core_Util::hashEquals($secretKey, str_repeat("\0", self::CRYPTO_BOX_SECRETKEYBYTES))) {
2160 throw new SodiumException('Zero secret key is not allowed');
2161 }
2162 if (ParagonIE_Sodium_Core_Util::hashEquals($publicKey, str_repeat("\0", self::CRYPTO_BOX_PUBLICKEYBYTES))) {
2163 throw new SodiumException('Zero public key is not allowed');
2164 }
2165 return ParagonIE_Sodium_Crypto::scalarmult($secretKey, $publicKey);
2166 }
2167
2168 /**
2169 * Calculate an X25519 public key from an X25519 secret key.
2170 *
2171 * @param string $secretKey
2172 * @return string
2173 * @throws SodiumException
2174 * @throws TypeError
2175 */
2176 public static function crypto_scalarmult_base(
2177 #[SensitiveParameter]
2178 string $secretKey
2179 ): string {
2180 /* Input validation: */
2181 if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !== self::CRYPTO_BOX_SECRETKEYBYTES) {
2182 throw new SodiumException('Argument 1 must be CRYPTO_BOX_SECRETKEYBYTES long.');
2183 }
2184
2185 if (self::useNewSodiumAPI()) {
2186 return sodium_crypto_scalarmult_base($secretKey);
2187 }
2188 if (self::use_fallback('crypto_scalarmult_base')) {
2189 return (string) call_user_func('\\Sodium\\crypto_scalarmult_base', $secretKey);
2190 }
2191 if (ParagonIE_Sodium_Core_Util::hashEquals($secretKey, str_repeat("\0", self::CRYPTO_BOX_SECRETKEYBYTES))) {
2192 throw new SodiumException('Zero secret key is not allowed');
2193 }
2194 return ParagonIE_Sodium_Crypto::scalarmult_base($secretKey);
2195 }
2196
2197 /**
2198 * Authenticated symmetric-key encryption.
2199 *
2200 * Algorithm: XSalsa20-Poly1305
2201 *
2202 * @param string $plaintext The message you're encrypting
2203 * @param string $nonce A Number to be used Once; must be 24 bytes
2204 * @param string $key Symmetric encryption key
2205 * @return string Ciphertext with Poly1305 MAC
2206 * @throws SodiumException
2207 * @throws TypeError
2208 */
2209 public static function crypto_secretbox(
2210 #[SensitiveParameter]
2211 string $plaintext,
2212 string $nonce,
2213 #[SensitiveParameter]
2214 string $key
2215 ): string {
2216 /* Input validation: */
2217 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_SECRETBOX_NONCEBYTES) {
2218 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_NONCEBYTES long.');
2219 }
2220 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_SECRETBOX_KEYBYTES) {
2221 throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_KEYBYTES long.');
2222 }
2223
2224 if (self::useNewSodiumAPI()) {
2225 return sodium_crypto_secretbox($plaintext, $nonce, $key);
2226 }
2227 if (self::use_fallback('crypto_secretbox')) {
2228 return (string) call_user_func('\\Sodium\\crypto_secretbox', $plaintext, $nonce, $key);
2229 }
2230 return ParagonIE_Sodium_Crypto::secretbox($plaintext, $nonce, $key);
2231 }
2232
2233 /**
2234 * Decrypts a message previously encrypted with crypto_secretbox().
2235 *
2236 * @param string $ciphertext Ciphertext with Poly1305 MAC
2237 * @param string $nonce A Number to be used Once; must be 24 bytes
2238 * @param string $key Symmetric encryption key
2239 * @return string|bool Original plaintext message
2240 * @throws SodiumException
2241 * @throws TypeError
2242 */
2243 public static function crypto_secretbox_open(
2244 string $ciphertext,
2245 string $nonce,
2246 #[SensitiveParameter]
2247 string $key
2248 ): string|bool {
2249 /* Input validation: */
2250 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_SECRETBOX_NONCEBYTES) {
2251 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_NONCEBYTES long.');
2252 }
2253 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_SECRETBOX_KEYBYTES) {
2254 throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_KEYBYTES long.');
2255 }
2256 if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) < self::CRYPTO_SECRETBOX_MACBYTES) {
2257 throw new SodiumException("Ciphertext must be at least CRYPTO_SECRETBOX_MACBYTES long");
2258 }
2259
2260 if (self::useNewSodiumAPI()) {
2261 return sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
2262 }
2263 if (self::use_fallback('crypto_secretbox_open')) {
2264 return call_user_func('\\Sodium\\crypto_secretbox_open', $ciphertext, $nonce, $key);
2265 }
2266 return ParagonIE_Sodium_Crypto::secretbox_open($ciphertext, $nonce, $key);
2267 }
2268
2269 /**
2270 * Return a secure random key for use with crypto_secretbox
2271 *
2272 * @return string
2273 * @throws Exception
2274 * @throws Error
2275 */
2276 public static function crypto_secretbox_keygen(): string
2277 {
2278 return random_bytes(self::CRYPTO_SECRETBOX_KEYBYTES);
2279 }
2280
2281 /**
2282 * Authenticated symmetric-key encryption.
2283 *
2284 * Algorithm: XChaCha20-Poly1305
2285 *
2286 * @param string $plaintext The message you're encrypting
2287 * @param string $nonce A Number to be used Once; must be 24 bytes
2288 * @param string $key Symmetric encryption key
2289 * @return string Ciphertext with Poly1305 MAC
2290 * @throws SodiumException
2291 * @throws TypeError
2292 */
2293 public static function crypto_secretbox_xchacha20poly1305(
2294 #[SensitiveParameter]
2295 string $plaintext,
2296 string $nonce,
2297 string $key
2298 ): string {
2299 /* Input validation: */
2300 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_SECRETBOX_NONCEBYTES) {
2301 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_NONCEBYTES long.');
2302 }
2303 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_SECRETBOX_KEYBYTES) {
2304 throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_KEYBYTES long.');
2305 }
2306 return ParagonIE_Sodium_Crypto::secretbox_xchacha20poly1305($plaintext, $nonce, $key);
2307 }
2308
2309 /**
2310 * Decrypts a message previously encrypted with crypto_secretbox_xchacha20poly1305().
2311 *
2312 * @param string $ciphertext Ciphertext with Poly1305 MAC
2313 * @param string $nonce A Number to be used Once; must be 24 bytes
2314 * @param string $key Symmetric encryption key
2315 * @return string Original plaintext message
2316 * @throws SodiumException
2317 * @throws TypeError
2318 */
2319 public static function crypto_secretbox_xchacha20poly1305_open(
2320 string $ciphertext,
2321 string $nonce,
2322 #[SensitiveParameter]
2323 string $key
2324 ): string {
2325 /* Input validation: */
2326 if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) < self::CRYPTO_SECRETBOX_MACBYTES) {
2327 throw new SodiumException('Argument 1 must be at least CRYPTO_SECRETBOX_MACBYTES long.');
2328 }
2329 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_SECRETBOX_NONCEBYTES) {
2330 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_NONCEBYTES long.');
2331 }
2332 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_SECRETBOX_KEYBYTES) {
2333 throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_KEYBYTES long.');
2334 }
2335
2336 return ParagonIE_Sodium_Crypto::secretbox_xchacha20poly1305_open($ciphertext, $nonce, $key);
2337 }
2338
2339 /**
2340 * @param string $key
2341 * @return array<int, string> Returns a state and a header.
2342 * @throws Exception
2343 * @throws SodiumException
2344 */
2345 public static function crypto_secretstream_xchacha20poly1305_init_push(
2346 #[SensitiveParameter]
2347 string $key
2348 ): array {
2349 return ParagonIE_Sodium_Crypto::secretstream_xchacha20poly1305_init_push($key);
2350 }
2351
2352 /**
2353 * @param string $header
2354 * @param string $key
2355 * @return string Returns a state.
2356 * @throws Exception
2357 */
2358 public static function crypto_secretstream_xchacha20poly1305_init_pull(
2359 string $header,
2360 #[SensitiveParameter]
2361 string $key
2362 ): string {
2363 if (ParagonIE_Sodium_Core_Util::strlen($header) < self::CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES) {
2364 throw new SodiumException(
2365 'header size should be SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES bytes'
2366 );
2367 }
2368 return ParagonIE_Sodium_Crypto::secretstream_xchacha20poly1305_init_pull($key, $header);
2369 }
2370
2371 /**
2372 * @param string $state
2373 * @param string $msg
2374 * @param string $aad
2375 * @param int $tag
2376 * @return string
2377 * @throws SodiumException
2378 */
2379 public static function crypto_secretstream_xchacha20poly1305_push(
2380 #[SensitiveParameter]
2381 string &$state,
2382 #[SensitiveParameter]
2383 string $msg,
2384 string $aad = '',
2385 int $tag = 0
2386 ): string {
2387 return ParagonIE_Sodium_Crypto::secretstream_xchacha20poly1305_push(
2388 $state,
2389 $msg,
2390 $aad,
2391 $tag
2392 );
2393 }
2394
2395 /**
2396 * @param string $state
2397 * @param string $msg
2398 * @param string $aad
2399 * @return bool|array{0: string, 1: int}
2400 * @throws SodiumException
2401 */
2402 public static function crypto_secretstream_xchacha20poly1305_pull(
2403 #[SensitiveParameter]
2404 string &$state,
2405 string $msg,
2406 string $aad = ''
2407 ): bool|array {
2408 return ParagonIE_Sodium_Crypto::secretstream_xchacha20poly1305_pull(
2409 $state,
2410 $msg,
2411 $aad
2412 );
2413 }
2414
2415 /**
2416 * @return string
2417 * @throws Exception
2418 */
2419 public static function crypto_secretstream_xchacha20poly1305_keygen(): string
2420 {
2421 return random_bytes(self::CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES);
2422 }
2423
2424 /**
2425 * @param string $state
2426 * @return void
2427 * @throws SodiumException
2428 */
2429 public static function crypto_secretstream_xchacha20poly1305_rekey(
2430 #[SensitiveParameter]
2431 string &$state
2432 ): void {
2433 ParagonIE_Sodium_Crypto::secretstream_xchacha20poly1305_rekey($state);
2434 }
2435
2436 /**
2437 * Calculates a SipHash-2-4 hash of a message for a given key.
2438 *
2439 * @param string $message Input message
2440 * @param string $key SipHash-2-4 key
2441 * @return string Hash
2442 * @throws SodiumException
2443 * @throws TypeError
2444 */
2445 public static function crypto_shorthash(
2446 string $message,
2447 #[SensitiveParameter]
2448 string $key
2449 ): string {
2450 /* Input validation: */
2451 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_SHORTHASH_KEYBYTES) {
2452 throw new SodiumException('Argument 2 must be CRYPTO_SHORTHASH_KEYBYTES long.');
2453 }
2454
2455 if (self::useNewSodiumAPI()) {
2456 return sodium_crypto_shorthash($message, $key);
2457 }
2458 if (self::use_fallback('crypto_shorthash')) {
2459 return (string) call_user_func('\\Sodium\\crypto_shorthash', $message, $key);
2460 }
2461 return ParagonIE_Sodium_Core_SipHash::sipHash24($message, $key);
2462 }
2463
2464 /**
2465 * Return a secure random key for use with crypto_shorthash
2466 *
2467 * @return string
2468 * @throws Exception
2469 * @throws Error
2470 */
2471 public static function crypto_shorthash_keygen(): string
2472 {
2473 return random_bytes(self::CRYPTO_SHORTHASH_KEYBYTES);
2474 }
2475
2476 /**
2477 * Returns a signed message. You probably want crypto_sign_detached()
2478 * instead, which only returns the signature.
2479 *
2480 * Algorithm: Ed25519 (EdDSA over Curve25519)
2481 *
2482 * @param string $message Message to be signed.
2483 * @param string $secretKey Secret signing key.
2484 * @return string Signed message (signature is prefixed).
2485 * @throws SodiumException
2486 * @throws TypeError
2487 */
2488 public static function crypto_sign(
2489 string $message,
2490 #[SensitiveParameter]
2491 string $secretKey
2492 ): string {
2493 /* Input validation: */
2494 if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !== self::CRYPTO_SIGN_SECRETKEYBYTES) {
2495 throw new SodiumException('Argument 2 must be CRYPTO_SIGN_SECRETKEYBYTES long.');
2496 }
2497 if (self::useNewSodiumAPI()) {
2498 return sodium_crypto_sign($message, $secretKey);
2499 }
2500 if (self::use_fallback('crypto_sign')) {
2501 return (string) call_user_func('\\Sodium\\crypto_sign', $message, $secretKey);
2502 }
2503 return ParagonIE_Sodium_Crypto::sign($message, $secretKey);
2504 }
2505
2506 /**
2507 * Validates a signed message then returns the message.
2508 *
2509 * @param string $signedMessage A signed message
2510 * @param string $publicKey A public key
2511 * @return string|bool The original message (if the signature is
2512 * valid for this public key)
2513 * @throws SodiumException
2514 * @throws TypeError
2515 */
2516 public static function crypto_sign_open(string $signedMessage, string $publicKey): string|bool
2517 {
2518 /* Input validation: */
2519 if (ParagonIE_Sodium_Core_Util::strlen($signedMessage) < self::CRYPTO_SIGN_BYTES) {
2520 throw new SodiumException('Argument 1 must be at least CRYPTO_SIGN_BYTES long.');
2521 }
2522 if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !== self::CRYPTO_SIGN_PUBLICKEYBYTES) {
2523 throw new SodiumException('Argument 2 must be CRYPTO_SIGN_PUBLICKEYBYTES long.');
2524 }
2525
2526 if (self::useNewSodiumAPI()) {
2527 return sodium_crypto_sign_open($signedMessage, $publicKey);
2528 }
2529 if (self::use_fallback('crypto_sign_open')) {
2530 return call_user_func('\\Sodium\\crypto_sign_open', $signedMessage, $publicKey);
2531 }
2532 return ParagonIE_Sodium_Crypto::sign_open($signedMessage, $publicKey);
2533 }
2534
2535 /**
2536 * Generate a new random Ed25519 keypair.
2537 *
2538 * @return string
2539 * @throws SodiumException
2540 * @throws TypeError
2541 */
2542 public static function crypto_sign_keypair(): string
2543 {
2544 if (self::useNewSodiumAPI()) {
2545 return sodium_crypto_sign_keypair();
2546 }
2547 if (self::use_fallback('crypto_sign_keypair')) {
2548 return (string) call_user_func('\\Sodium\\crypto_sign_keypair');
2549 }
2550 return ParagonIE_Sodium_Core_Ed25519::keypair();
2551 }
2552
2553 /**
2554 * @param string $sk
2555 * @param string $pk
2556 * @return string
2557 * @throws SodiumException
2558 */
2559 public static function crypto_sign_keypair_from_secretkey_and_publickey(
2560 #[SensitiveParameter]
2561 string $sk,
2562 string $pk
2563 ): string {
2564 if (ParagonIE_Sodium_Core_Util::strlen($sk) !== self::CRYPTO_SIGN_SECRETKEYBYTES) {
2565 throw new SodiumException('secretkey should be SODIUM_CRYPTO_SIGN_SECRETKEYBYTES bytes');
2566 }
2567 if (ParagonIE_Sodium_Core_Util::strlen($pk) !== self::CRYPTO_SIGN_PUBLICKEYBYTES) {
2568 throw new SodiumException('publickey should be SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES bytes');
2569 }
2570
2571 if (self::useNewSodiumAPI()) {
2572 return sodium_crypto_sign_keypair_from_secretkey_and_publickey($sk, $pk);
2573 }
2574 return $sk . $pk;
2575 }
2576
2577 /**
2578 * Generate an Ed25519 keypair from a seed.
2579 *
2580 * @param string $seed Input seed
2581 * @return string Keypair
2582 * @throws SodiumException
2583 * @throws TypeError
2584 */
2585 public static function crypto_sign_seed_keypair(
2586 #[SensitiveParameter]
2587 string $seed
2588 ): string {
2589 if (self::useNewSodiumAPI()) {
2590 return sodium_crypto_sign_seed_keypair($seed);
2591 }
2592 if (self::use_fallback('crypto_sign_keypair')) {
2593 return (string) call_user_func('\\Sodium\\crypto_sign_seed_keypair', $seed);
2594 }
2595 $publicKey = '';
2596 $secretKey = '';
2597 ParagonIE_Sodium_Core_Ed25519::seed_keypair($publicKey, $secretKey, $seed);
2598 return $secretKey . $publicKey;
2599 }
2600
2601 /**
2602 * Extract an Ed25519 public key from an Ed25519 keypair.
2603 *
2604 * @param string $keypair Keypair
2605 * @return string Public key
2606 * @throws SodiumException
2607 * @throws TypeError
2608 */
2609 public static function crypto_sign_publickey(
2610 #[SensitiveParameter]
2611 string $keypair
2612 ): string {
2613 /* Input validation: */
2614 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_SIGN_KEYPAIRBYTES) {
2615 throw new SodiumException('Argument 1 must be CRYPTO_SIGN_KEYPAIRBYTES long.');
2616 }
2617
2618 if (self::useNewSodiumAPI()) {
2619 return sodium_crypto_sign_publickey($keypair);
2620 }
2621 if (self::use_fallback('crypto_sign_publickey')) {
2622 return (string) call_user_func('\\Sodium\\crypto_sign_publickey', $keypair);
2623 }
2624 return ParagonIE_Sodium_Core_Ed25519::publickey($keypair);
2625 }
2626
2627 /**
2628 * Calculate an Ed25519 public key from an Ed25519 secret key.
2629 *
2630 * @param string $secretKey Your Ed25519 secret key
2631 * @return string The corresponding Ed25519 public key
2632 * @throws SodiumException
2633 * @throws TypeError
2634 */
2635 public static function crypto_sign_publickey_from_secretkey(
2636 #[SensitiveParameter]
2637 string $secretKey
2638 ): string {
2639
2640 /* Input validation: */
2641 if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !== self::CRYPTO_SIGN_SECRETKEYBYTES) {
2642 throw new SodiumException('Argument 1 must be CRYPTO_SIGN_SECRETKEYBYTES long.');
2643 }
2644
2645 if (self::useNewSodiumAPI()) {
2646 return sodium_crypto_sign_publickey_from_secretkey($secretKey);
2647 }
2648 if (self::use_fallback('crypto_sign_publickey_from_secretkey')) {
2649 return (string) call_user_func('\\Sodium\\crypto_sign_publickey_from_secretkey', $secretKey);
2650 }
2651 return ParagonIE_Sodium_Core_Ed25519::publickey_from_secretkey($secretKey);
2652 }
2653
2654 /**
2655 * Extract an Ed25519 secret key from an Ed25519 keypair.
2656 *
2657 * @param string $keypair Keypair
2658 * @return string Secret key
2659 * @throws SodiumException
2660 * @throws TypeError
2661 */
2662 public static function crypto_sign_secretkey(
2663 #[SensitiveParameter]
2664 string $keypair
2665 ): string {
2666 /* Input validation: */
2667 if (ParagonIE_Sodium_Core_Util::strlen($keypair) !== self::CRYPTO_SIGN_KEYPAIRBYTES) {
2668 throw new SodiumException('Argument 1 must be CRYPTO_SIGN_KEYPAIRBYTES long.');
2669 }
2670
2671 if (self::useNewSodiumAPI()) {
2672 return sodium_crypto_sign_secretkey($keypair);
2673 }
2674 if (self::use_fallback('crypto_sign_secretkey')) {
2675 return (string) call_user_func('\\Sodium\\crypto_sign_secretkey', $keypair);
2676 }
2677 return ParagonIE_Sodium_Core_Ed25519::secretkey($keypair);
2678 }
2679
2680 /**
2681 * Calculate the Ed25519 signature of a message and return ONLY the signature.
2682 *
2683 * Algorithm: Ed25519 (EdDSA over Curve25519)
2684 *
2685 * @param string $message Message to be signed
2686 * @param string $secretKey Secret signing key
2687 * @return string Digital signature
2688 * @throws SodiumException
2689 * @throws TypeError
2690 */
2691 public static function crypto_sign_detached(
2692 string $message,
2693 #[SensitiveParameter]
2694 string $secretKey
2695 ): string {
2696 /* Input validation: */
2697 if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !== self::CRYPTO_SIGN_SECRETKEYBYTES) {
2698 throw new SodiumException('Argument 2 must be CRYPTO_SIGN_SECRETKEYBYTES long.');
2699 }
2700
2701 if (self::useNewSodiumAPI()) {
2702 return sodium_crypto_sign_detached($message, $secretKey);
2703 }
2704 if (self::use_fallback('crypto_sign_detached')) {
2705 return (string) call_user_func('\\Sodium\\crypto_sign_detached', $message, $secretKey);
2706 }
2707 return ParagonIE_Sodium_Crypto::sign_detached($message, $secretKey);
2708 }
2709
2710 /**
2711 * Verify the Ed25519 signature of a message.
2712 *
2713 * @param string $signature Digital sginature
2714 * @param string $message Message to be verified
2715 * @param string $publicKey Public key
2716 * @return bool TRUE if this signature is good for this public key;
2717 * FALSE otherwise
2718 * @throws SodiumException
2719 * @throws TypeError
2720 */
2721 public static function crypto_sign_verify_detached(
2722 string $signature,
2723 string $message,
2724 string $publicKey
2725 ): bool {
2726 /* Input validation: */
2727 if (ParagonIE_Sodium_Core_Util::strlen($signature) !== self::CRYPTO_SIGN_BYTES) {
2728 throw new SodiumException('Argument 1 must be CRYPTO_SIGN_BYTES long.');
2729 }
2730 if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !== self::CRYPTO_SIGN_PUBLICKEYBYTES) {
2731 throw new SodiumException('Argument 3 must be CRYPTO_SIGN_PUBLICKEYBYTES long.');
2732 }
2733
2734 if (self::useNewSodiumAPI()) {
2735 return sodium_crypto_sign_verify_detached($signature, $message, $publicKey);
2736 }
2737 if (self::use_fallback('crypto_sign_verify_detached')) {
2738 return (bool) call_user_func(
2739 '\\Sodium\\crypto_sign_verify_detached',
2740 $signature,
2741 $message,
2742 $publicKey
2743 );
2744 }
2745 return ParagonIE_Sodium_Crypto::sign_verify_detached($signature, $message, $publicKey);
2746 }
2747
2748 /**
2749 * Convert an Ed25519 public key to a Curve25519 public key
2750 *
2751 * @param string $pk
2752 * @return string
2753 * @throws SodiumException
2754 * @throws TypeError
2755 */
2756 public static function crypto_sign_ed25519_pk_to_curve25519(string $pk): string
2757 {
2758 /* Input validation: */
2759 if (ParagonIE_Sodium_Core_Util::strlen($pk) < self::CRYPTO_SIGN_PUBLICKEYBYTES) {
2760 throw new SodiumException('Argument 1 must be at least CRYPTO_SIGN_PUBLICKEYBYTES long.');
2761 }
2762 if (self::useNewSodiumAPI()) {
2763 if (is_callable('crypto_sign_ed25519_pk_to_curve25519')) {
2764 return sodium_crypto_sign_ed25519_pk_to_curve25519($pk);
2765 }
2766 }
2767 if (self::use_fallback('crypto_sign_ed25519_pk_to_curve25519')) {
2768 return (string) call_user_func('\\Sodium\\crypto_sign_ed25519_pk_to_curve25519', $pk);
2769 }
2770 return ParagonIE_Sodium_Core_Ed25519::pk_to_curve25519($pk);
2771 }
2772
2773 /**
2774 * Convert an Ed25519 secret key to a Curve25519 secret key
2775 *
2776 * @param string $sk
2777 * @return string
2778 * @throws SodiumException
2779 * @throws TypeError
2780 */
2781 public static function crypto_sign_ed25519_sk_to_curve25519(
2782 #[SensitiveParameter]
2783 string $sk
2784 ): string {
2785 /* Input validation: */
2786 if (ParagonIE_Sodium_Core_Util::strlen($sk) < self::CRYPTO_SIGN_SEEDBYTES) {
2787 throw new SodiumException('Argument 1 must be at least CRYPTO_SIGN_SEEDBYTES long.');
2788 }
2789 if (self::useNewSodiumAPI()) {
2790 if (is_callable('crypto_sign_ed25519_sk_to_curve25519')) {
2791 return sodium_crypto_sign_ed25519_sk_to_curve25519($sk);
2792 }
2793 }
2794 if (self::use_fallback('crypto_sign_ed25519_sk_to_curve25519')) {
2795 return (string) call_user_func('\\Sodium\\crypto_sign_ed25519_sk_to_curve25519', $sk);
2796 }
2797
2798 $h = hash('sha512', ParagonIE_Sodium_Core_Util::substr($sk, 0, 32), true);
2799 $h[0] = ParagonIE_Sodium_Core_Util::intToChr(
2800 ParagonIE_Sodium_Core_Util::chrToInt($h[0]) & 248
2801 );
2802 $h[31] = ParagonIE_Sodium_Core_Util::intToChr(
2803 (ParagonIE_Sodium_Core_Util::chrToInt($h[31]) & 127) | 64
2804 );
2805 return ParagonIE_Sodium_Core_Util::substr($h, 0, 32);
2806 }
2807
2808 /**
2809 * Expand a key and nonce into a keystream of pseudorandom bytes.
2810 *
2811 * @param int $len Number of bytes desired
2812 * @param string $nonce Number to be used Once; must be 24 bytes
2813 * @param string $key XSalsa20 key
2814 * @return string Pseudorandom stream that can be XORed with messages
2815 * to provide encryption (but not authentication; see
2816 * Poly1305 or crypto_auth() for that, which is not
2817 * optional for security)
2818 * @throws SodiumException
2819 * @throws TypeError
2820 */
2821 public static function crypto_stream(
2822 int $len,
2823 string $nonce,
2824 #[SensitiveParameter]
2825 string $key
2826 ): string {
2827 /* Input validation: */
2828 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_STREAM_NONCEBYTES) {
2829 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_NONCEBYTES long.');
2830 }
2831 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_STREAM_KEYBYTES) {
2832 throw new SodiumException('Argument 3 must be CRYPTO_STREAM_KEYBYTES long.');
2833 }
2834
2835 if (self::useNewSodiumAPI()) {
2836 return sodium_crypto_stream($len, $nonce, $key);
2837 }
2838 if (self::use_fallback('crypto_stream')) {
2839 return (string) call_user_func('\\Sodium\\crypto_stream', $len, $nonce, $key);
2840 }
2841 return ParagonIE_Sodium_Core_XSalsa20::xsalsa20($len, $nonce, $key);
2842 }
2843
2844 /**
2845 * DANGER! UNAUTHENTICATED ENCRYPTION!
2846 *
2847 * Unless you are following expert advice, do not use this feature.
2848 *
2849 * Algorithm: XSalsa20
2850 *
2851 * This DOES NOT provide ciphertext integrity.
2852 *
2853 * @param string $message Plaintext message
2854 * @param string $nonce Number to be used Once; must be 24 bytes
2855 * @param string $key Encryption key
2856 * @return string Encrypted text which is vulnerable to chosen-
2857 * ciphertext attacks unless you implement some
2858 * other mitigation to the ciphertext (i.e.
2859 * Encrypt then MAC)
2860 * @throws SodiumException
2861 * @throws TypeError
2862 */
2863 public static function crypto_stream_xor(
2864 #[SensitiveParameter]
2865 string $message,
2866 string $nonce,
2867 #[SensitiveParameter]
2868 string $key
2869 ): string {
2870 /* Input validation: */
2871 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_STREAM_NONCEBYTES) {
2872 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_NONCEBYTES long.');
2873 }
2874 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_STREAM_KEYBYTES) {
2875 throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_KEYBYTES long.');
2876 }
2877
2878 if (self::useNewSodiumAPI()) {
2879 return sodium_crypto_stream_xor($message, $nonce, $key);
2880 }
2881 if (self::use_fallback('crypto_stream_xor')) {
2882 return (string) call_user_func('\\Sodium\\crypto_stream_xor', $message, $nonce, $key);
2883 }
2884 return ParagonIE_Sodium_Core_XSalsa20::xsalsa20_xor($message, $nonce, $key);
2885 }
2886
2887 /**
2888 * Return a secure random key for use with crypto_stream
2889 *
2890 * @return string
2891 * @throws Exception
2892 * @throws Error
2893 */
2894 public static function crypto_stream_keygen(): string
2895 {
2896 return random_bytes(self::CRYPTO_STREAM_KEYBYTES);
2897 }
2898
2899 /**
2900 * Expand a key and nonce into a keystream of pseudorandom bytes.
2901 *
2902 * @param int $len Number of bytes desired
2903 * @param string $nonce Number to be used Once; must be 24 bytes
2904 * @param string $key XChaCha20 key
2905 * @param bool $dontFallback
2906 * @return string Pseudorandom stream that can be XORed with messages
2907 * to provide encryption (but not authentication; see
2908 * Poly1305 or crypto_auth() for that, which is not
2909 * optional for security)
2910 * @throws SodiumException
2911 * @throws TypeError
2912 */
2913 public static function crypto_stream_xchacha20(
2914 int $len,
2915 string $nonce,
2916 #[SensitiveParameter]
2917 string $key,
2918 bool $dontFallback = false
2919 ): string {
2920 /* Input validation: */
2921 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_STREAM_XCHACHA20_NONCEBYTES) {
2922 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_XCHACHA20_NONCEBYTES long.');
2923 }
2924 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_STREAM_XCHACHA20_KEYBYTES) {
2925 throw new SodiumException('Argument 3 must be CRYPTO_STREAM_XCHACHA20_KEYBYTES long.');
2926 }
2927
2928 if (self::useNewSodiumAPI() && !$dontFallback) {
2929 return sodium_crypto_stream_xchacha20($len, $nonce, $key);
2930 }
2931 return ParagonIE_Sodium_Core_XChaCha20::stream($len, $nonce, $key);
2932 }
2933
2934 /**
2935 * DANGER! UNAUTHENTICATED ENCRYPTION!
2936 *
2937 * Unless you are following expert advice, do not use this feature.
2938 *
2939 * Algorithm: XChaCha20
2940 *
2941 * This DOES NOT provide ciphertext integrity.
2942 *
2943 * @param string $message Plaintext message
2944 * @param string $nonce Number to be used Once; must be 24 bytes
2945 * @param string $key Encryption key
2946 * @return string Encrypted text which is vulnerable to chosen-
2947 * ciphertext attacks unless you implement some
2948 * other mitigation to the ciphertext (i.e.
2949 * Encrypt then MAC)
2950 * @param bool $dontFallback
2951 * @throws SodiumException
2952 * @throws TypeError
2953 */
2954 public static function crypto_stream_xchacha20_xor(
2955 #[SensitiveParameter]
2956 string $message,
2957 string $nonce,
2958 #[SensitiveParameter]
2959 string $key,
2960 bool $dontFallback = false
2961 ): string {
2962 /* Input validation: */
2963 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_STREAM_XCHACHA20_NONCEBYTES) {
2964 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_XCHACHA20_NONCEBYTES long.');
2965 }
2966 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_STREAM_XCHACHA20_KEYBYTES) {
2967 throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_XCHACHA20_KEYBYTES long.');
2968 }
2969
2970 if (self::useNewSodiumAPI() && !$dontFallback) {
2971 return sodium_crypto_stream_xchacha20_xor($message, $nonce, $key);
2972 }
2973 return ParagonIE_Sodium_Core_XChaCha20::streamXorIc($message, $nonce, $key);
2974 }
2975
2976 /**
2977 * DANGER! UNAUTHENTICATED ENCRYPTION!
2978 *
2979 * Unless you are following expert advice, do not use this feature.
2980 *
2981 * Algorithm: XChaCha20
2982 *
2983 * This DOES NOT provide ciphertext integrity.
2984 *
2985 * @param string $message Plaintext message
2986 * @param string $nonce Number to be used Once; must be 24 bytes
2987 * @param int $counter
2988 * @param string $key Encryption key
2989 * @return string Encrypted text which is vulnerable to chosen-
2990 * ciphertext attacks unless you implement some
2991 * other mitigation to the ciphertext (i.e.
2992 * Encrypt then MAC)
2993 * @param bool $dontFallback
2994 * @throws SodiumException
2995 * @throws TypeError
2996 */
2997 public static function crypto_stream_xchacha20_xor_ic(
2998 #[SensitiveParameter]
2999 string $message,
3000 string $nonce,
3001 int $counter,
3002 #[SensitiveParameter]
3003 string $key,
3004 bool $dontFallback = false
3005 ): string {
3006 /* Input validation: */
3007 if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_STREAM_XCHACHA20_NONCEBYTES) {
3008 throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_XCHACHA20_NONCEBYTES long.');
3009 }
3010 if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_STREAM_XCHACHA20_KEYBYTES) {
3011 throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_XCHACHA20_KEYBYTES long.');
3012 }
3013
3014 if (is_callable('sodium_crypto_stream_xchacha20_xor_ic') && !$dontFallback) {
3015 return sodium_crypto_stream_xchacha20_xor_ic($message, $nonce, $counter, $key);
3016 }
3017
3018 $ic = ParagonIE_Sodium_Core_Util::store64_le($counter);
3019 return ParagonIE_Sodium_Core_XChaCha20::streamXorIc($message, $nonce, $key, $ic);
3020 }
3021
3022 /**
3023 * Return a secure random key for use with crypto_stream_xchacha20
3024 *
3025 * @return string
3026 * @throws Exception
3027 * @throws Error
3028 */
3029 public static function crypto_stream_xchacha20_keygen(): string
3030 {
3031 return random_bytes(self::CRYPTO_STREAM_XCHACHA20_KEYBYTES);
3032 }
3033
3034 /**
3035 * Cache-timing-safe implementation of hex2bin().
3036 *
3037 * @param string $string Hexadecimal string
3038 * @param string $ignore List of characters to ignore; useful for whitespace
3039 * @return string Raw binary string
3040 * @throws SodiumException
3041 * @throws TypeError
3042 */
3043 public static function hex2bin(
3044 #[SensitiveParameter]
3045 string $string,
3046 string $ignore = ''
3047 ): string {
3048 if (self::useNewSodiumAPI()) {
3049 if (is_callable('sodium_hex2bin')) {
3050 return sodium_hex2bin($string, $ignore);
3051 }
3052 }
3053 if (self::use_fallback('hex2bin')) {
3054 return (string) call_user_func('\\Sodium\\hex2bin', $string, $ignore);
3055 }
3056 return ParagonIE_Sodium_Core_Util::hex2bin($string, $ignore, true);
3057 }
3058
3059 /**
3060 * Increase a string (little endian)
3061 *
3062 * @param string $var
3063 *
3064 * @return void
3065 * @throws SodiumException
3066 * @throws TypeError
3067 */
3068 public static function increment(
3069 #[SensitiveParameter]
3070 string &$var
3071 ): void {
3072 if (self::useNewSodiumAPI()) {
3073 sodium_increment($var);
3074 return;
3075 }
3076 if (self::use_fallback('increment')) {
3077 $func = '\\Sodium\\increment';
3078 $func($var);
3079 return;
3080 }
3081
3082 $len = ParagonIE_Sodium_Core_Util::strlen($var);
3083 if ($len < 1) {
3084 throw new SodiumException('Argument 1 cannot be empty');
3085 }
3086 $c = 1;
3087 $copy = '';
3088 for ($i = 0; $i < $len; ++$i) {
3089 $c += ParagonIE_Sodium_Core_Util::chrToInt(
3090 ParagonIE_Sodium_Core_Util::substr($var, $i, 1)
3091 );
3092 $copy .= ParagonIE_Sodium_Core_Util::intToChr($c);
3093 $c >>= 8;
3094 }
3095 $var = $copy;
3096 }
3097
3098 /**
3099 * @param string $str
3100 * @return bool
3101 *
3102 * @throws SodiumException
3103 */
3104 public static function is_zero(
3105 #[SensitiveParameter]
3106 string $str
3107 ): bool {
3108 $d = 0;
3109 for ($i = 0; $i < 32; ++$i) {
3110 $d |= ParagonIE_Sodium_Core_Util::chrToInt($str[$i]);
3111 }
3112 return ((($d - 1) >> 31) & 1) === 1;
3113 }
3114
3115 /**
3116 * The equivalent to the libsodium minor version we aim to be compatible
3117 * with (sans pwhash and memzero).
3118 *
3119 * @return int
3120 */
3121 public static function library_version_major(): int
3122 {
3123 if (self::useNewSodiumAPI() && defined('SODIUM_LIBRARY_MAJOR_VERSION')) {
3124 return SODIUM_LIBRARY_MAJOR_VERSION;
3125 }
3126 if (self::use_fallback('library_version_major')) {
3127 /** @psalm-suppress UndefinedFunction */
3128 return (int) call_user_func('\\Sodium\\library_version_major');
3129 }
3130 return self::LIBRARY_VERSION_MAJOR;
3131 }
3132
3133 /**
3134 * The equivalent to the libsodium minor version we aim to be compatible
3135 * with (sans pwhash and memzero).
3136 *
3137 * @return int
3138 */
3139 public static function library_version_minor(): int
3140 {
3141 if (self::useNewSodiumAPI() && defined('SODIUM_LIBRARY_MINOR_VERSION')) {
3142 return SODIUM_LIBRARY_MINOR_VERSION;
3143 }
3144 if (self::use_fallback('library_version_minor')) {
3145 /** @psalm-suppress UndefinedFunction */
3146 return (int) call_user_func('\\Sodium\\library_version_minor');
3147 }
3148 return self::LIBRARY_VERSION_MINOR;
3149 }
3150
3151 /**
3152 * Compare two strings.
3153 *
3154 * @param string $left
3155 * @param string $right
3156 * @return int
3157 * @throws SodiumException
3158 * @throws TypeError
3159 */
3160 public static function memcmp(
3161 #[SensitiveParameter]
3162 string $left,
3163 #[SensitiveParameter]
3164 string $right
3165 ): int {
3166 if (self::useNewSodiumAPI()) {
3167 return sodium_memcmp($left, $right);
3168 }
3169 if (self::use_fallback('memcmp')) {
3170 return (int) call_user_func('\\Sodium\\memcmp', $left, $right);
3171 }
3172 return ParagonIE_Sodium_Core_Util::memcmp($left, $right);
3173 }
3174
3175 /**
3176 * It's actually not possible to zero memory buffers in PHP. You need the
3177 * native library for that.
3178 *
3179 * @param ?string $var
3180 * @param-out string|null $var
3181 *
3182 * @return void
3183 * @throws SodiumException (Unless libsodium is installed)
3184 * @throws TypeError
3185 * @psalm-suppress TooFewArguments
3186 */
3187 public static function memzero(
3188 #[SensitiveParameter]
3189 ?string &$var
3190 ): void {
3191 if (is_null($var)) {
3192 return;
3193 }
3194 if (self::useNewSodiumAPI()) {
3195 /** @psalm-suppress MixedArgument */
3196 sodium_memzero($var);
3197 return;
3198 }
3199 if (self::use_fallback('memzero')) {
3200 $func = '\\Sodium\\memzero';
3201 $func($var);
3202 return;
3203 }
3204 // This is the best we can do.
3205 throw new SodiumException(
3206 'This is not implemented in sodium_compat, as it is not possible to securely wipe memory from PHP. ' .
3207 'To fix this error, make sure libsodium is installed and the PHP extension is enabled.'
3208 );
3209 }
3210
3211 /**
3212 * @param string $unpadded
3213 * @param int $blockSize
3214 * @param bool $dontFallback
3215 * @return string
3216 * @throws SodiumException
3217 */
3218 public static function pad(
3219 #[SensitiveParameter]
3220 string $unpadded,
3221 int $blockSize,
3222 bool $dontFallback = false
3223 ): string {
3224 if (self::useNewSodiumAPI() && !$dontFallback) {
3225 return sodium_pad($unpadded, $blockSize);
3226 }
3227
3228 if ($blockSize <= 0) {
3229 throw new SodiumException(
3230 'block size cannot be less than 1'
3231 );
3232 }
3233 $unpadded_len = ParagonIE_Sodium_Core_Util::strlen($unpadded);
3234 $xpadlen = ($blockSize - 1);
3235 if (($blockSize & ($blockSize - 1)) === 0) {
3236 $xpadlen -= $unpadded_len & ($blockSize - 1);
3237 } else {
3238 $xpadlen -= $unpadded_len % $blockSize;
3239 }
3240
3241 $xpadded_len = $unpadded_len + $xpadlen;
3242 $padded = str_repeat("\0", $xpadded_len - 1);
3243 if ($unpadded_len > 0) {
3244 $st = 1;
3245 $i = 0;
3246 $k = $unpadded_len;
3247 for ($j = 0; $j <= $xpadded_len; ++$j) {
3248 $i = (int) $i;
3249 /** @psalm-suppress RedundantCast */
3250 $k = (int) $k;
3251 if ($j >= $unpadded_len) {
3252 $padded[$j] = "\0";
3253 } else {
3254 $padded[$j] = $unpadded[$j];
3255 }
3256 $k -= $st;
3257 $st = (~(
3258 (
3259 (
3260 ($k >> 48)
3261 |
3262 ($k >> 32)
3263 |
3264 ($k >> 16)
3265 |
3266 $k
3267 ) - 1
3268 ) >> 16
3269 )
3270 ) & 1;
3271 $i += $st;
3272 }
3273 }
3274
3275 $mask = 0;
3276 $tail = $xpadded_len;
3277 for ($i = 0; $i < $blockSize; ++$i) {
3278 # barrier_mask = (unsigned char)
3279 # (((i ^ xpadlen) - 1U) >> ((sizeof(size_t) - 1U) * CHAR_BIT));
3280 $barrier_mask = (($i ^ $xpadlen) -1) >> ((PHP_INT_SIZE << 3) - 1);
3281 # tail[-i] = (tail[-i] & mask) | (0x80 & barrier_mask);
3282 $padded[$tail - $i] = ParagonIE_Sodium_Core_Util::intToChr(
3283 (ParagonIE_Sodium_Core_Util::chrToInt($padded[$tail - $i]) & $mask)
3284 |
3285 (0x80 & $barrier_mask)
3286 );
3287 # mask |= barrier_mask;
3288 $mask |= $barrier_mask;
3289 }
3290 return $padded;
3291 }
3292
3293 /**
3294 * @param string $padded
3295 * @param int $blockSize
3296 * @param bool $dontFallback
3297 * @return string
3298 * @throws SodiumException
3299 */
3300 public static function unpad(
3301 #[SensitiveParameter]
3302 string $padded,
3303 int $blockSize,
3304 bool $dontFallback = false
3305 ): string {
3306 if (self::useNewSodiumAPI() && !$dontFallback) {
3307 return sodium_unpad($padded, $blockSize);
3308 }
3309 if ($blockSize <= 0) {
3310 throw new SodiumException('block size cannot be less than 1');
3311 }
3312 $padded_len = ParagonIE_Sodium_Core_Util::strlen($padded);
3313 if ($padded_len < $blockSize) {
3314 throw new SodiumException('invalid padding');
3315 }
3316
3317 # tail = &padded[padded_len - 1U];
3318 $tail = $padded_len - 1;
3319
3320 $acc = 0;
3321 $valid = 0;
3322 $pad_len = 0;
3323
3324 $found = 0;
3325 for ($i = 0; $i < $blockSize; ++$i) {
3326 # c = tail[-i];
3327 $c = ParagonIE_Sodium_Core_Util::chrToInt($padded[$tail - $i]);
3328
3329 # is_barrier =
3330 # (( (acc - 1U) & (pad_len - 1U) & ((c ^ 0x80) - 1U) ) >> 8) & 1U;
3331 $is_barrier = (
3332 (
3333 ($acc - 1) & ($pad_len - 1) & (($c ^ 80) - 1)
3334 ) >> 7
3335 ) & 1;
3336 $is_barrier &= ~$found;
3337 $found |= $is_barrier;
3338
3339 # acc |= c;
3340 $acc |= $c;
3341
3342 # pad_len |= i & (1U + ~is_barrier);
3343 $pad_len |= $i & (1 + ~$is_barrier);
3344
3345 # valid |= (unsigned char) is_barrier;
3346 $valid |= ($is_barrier & 0xff);
3347 }
3348 # unpadded_len = padded_len - 1U - pad_len;
3349 $unpadded_len = $padded_len - 1 - $pad_len;
3350 if ($valid !== 1) {
3351 throw new SodiumException('invalid padding');
3352 }
3353 return ParagonIE_Sodium_Core_Util::substr($padded, 0, $unpadded_len);
3354 }
3355
3356 /**
3357 * Will sodium_compat run fast on the current hardware and PHP configuration?
3358 *
3359 * @return bool
3360 */
3361 public static function polyfill_is_fast(): bool
3362 {
3363 if (extension_loaded('sodium')) {
3364 return true;
3365 }
3366 if (extension_loaded('libsodium')) {
3367 return true;
3368 }
3369 return PHP_INT_SIZE === 8;
3370 }
3371
3372 /**
3373 * Generate a string of bytes from the kernel's CSPRNG.
3374 * Proudly uses /dev/urandom (if getrandom(2) is not available).
3375 *
3376 * @param int $numBytes
3377 * @return string
3378 * @throws Exception
3379 * @throws TypeError
3380 */
3381 public static function randombytes_buf(int $numBytes): string
3382 {
3383 /** @var positive-int $numBytes */
3384 if (self::use_fallback('randombytes_buf')) {
3385 return (string) call_user_func('\\Sodium\\randombytes_buf', $numBytes);
3386 }
3387 return random_bytes($numBytes);
3388 }
3389
3390 /**
3391 * Generate an integer between 0 and $range (non-inclusive).
3392 *
3393 * @param int $range
3394 * @return int
3395 * @throws Exception
3396 * @throws Error
3397 * @throws TypeError
3398 */
3399 public static function randombytes_uniform(int $range): int
3400 {
3401 if (self::use_fallback('randombytes_uniform')) {
3402 return (int) call_user_func('\\Sodium\\randombytes_uniform', $range);
3403 }
3404 return random_int(0, $range - 1);
3405 }
3406
3407 /**
3408 * Generate a random 16-bit integer.
3409 *
3410 * @return int
3411 * @throws Exception
3412 * @throws Error
3413 * @throws TypeError
3414 */
3415 public static function randombytes_random16(): int
3416 {
3417 if (self::use_fallback('randombytes_random16')) {
3418 return (int) call_user_func('\\Sodium\\randombytes_random16');
3419 }
3420 return random_int(0, 65535);
3421 }
3422
3423 /**
3424 * @param string $p
3425 * @param bool $dontFallback
3426 * @return bool
3427 * @throws SodiumException
3428 */
3429 public static function ristretto255_is_valid_point(
3430 string $p,
3431 bool $dontFallback = false
3432 ): bool {
3433 if (self::useNewSodiumAPI() && !$dontFallback) {
3434 return sodium_crypto_core_ristretto255_is_valid_point($p);
3435 }
3436 try {
3437 $r = ParagonIE_Sodium_Core_Ristretto255::ristretto255_frombytes($p);
3438 return $r['res'] === 0 &&
3439 ParagonIE_Sodium_Core_Ristretto255::ristretto255_point_is_canonical($p) === 1;
3440 } catch (SodiumException $ex) {
3441 if ($ex->getMessage() === 'S is not canonical') {
3442 return false;
3443 }
3444 throw $ex;
3445 }
3446 }
3447
3448 /**
3449 * @param string $p
3450 * @param string $q
3451 * @param bool $dontFallback
3452 * @return string
3453 * @throws SodiumException
3454 */
3455 public static function ristretto255_add(
3456 #[SensitiveParameter]
3457 string $p,
3458 #[SensitiveParameter]
3459 string $q,
3460 bool $dontFallback = false
3461 ): string {
3462 if (self::useNewSodiumAPI() && !$dontFallback) {
3463 return sodium_crypto_core_ristretto255_add($p, $q);
3464 }
3465 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_add($p, $q);
3466 }
3467
3468 /**
3469 * @param string $p
3470 * @param string $q
3471 * @param bool $dontFallback
3472 * @return string
3473 * @throws SodiumException
3474 */
3475 public static function ristretto255_sub(
3476 #[SensitiveParameter]
3477 string $p,
3478 #[SensitiveParameter]
3479 string $q,
3480 bool $dontFallback = false
3481 ): string{
3482 if (self::useNewSodiumAPI() && !$dontFallback) {
3483 return sodium_crypto_core_ristretto255_sub($p, $q);
3484 }
3485 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_sub($p, $q);
3486 }
3487
3488 /**
3489 * @param string $r
3490 * @param bool $dontFallback
3491 * @return string
3492 *
3493 * @throws SodiumException
3494 */
3495 public static function ristretto255_from_hash(
3496 #[SensitiveParameter]
3497 string $r,
3498 bool $dontFallback = false
3499 ): string {
3500 if (self::useNewSodiumAPI() && !$dontFallback) {
3501 return sodium_crypto_core_ristretto255_from_hash($r);
3502 }
3503 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_from_hash($r);
3504 }
3505
3506 /**
3507 * @param bool $dontFallback
3508 * @return string
3509 *
3510 * @throws SodiumException
3511 */
3512 public static function ristretto255_random(bool $dontFallback = false): string
3513 {
3514 if (self::useNewSodiumAPI() && !$dontFallback) {
3515 return sodium_crypto_core_ristretto255_random();
3516 }
3517 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_random();
3518 }
3519
3520 /**
3521 * @param bool $dontFallback
3522 * @return string
3523 *
3524 * @throws SodiumException
3525 */
3526 public static function ristretto255_scalar_random(bool $dontFallback = false): string
3527 {
3528 if (self::useNewSodiumAPI() && !$dontFallback) {
3529 return sodium_crypto_core_ristretto255_scalar_random();
3530 }
3531 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_scalar_random();
3532 }
3533
3534 /**
3535 * @param string $s
3536 * @param bool $dontFallback
3537 * @return string
3538 * @throws SodiumException
3539 */
3540 public static function ristretto255_scalar_invert(
3541 #[SensitiveParameter]
3542 string $s,
3543 bool $dontFallback = false
3544 ): string {
3545 if (self::useNewSodiumAPI() && !$dontFallback) {
3546 return sodium_crypto_core_ristretto255_scalar_invert($s);
3547 }
3548 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_scalar_invert($s);
3549 }
3550 /**
3551 * @param string $s
3552 * @param bool $dontFallback
3553 * @return string
3554 * @throws SodiumException
3555 */
3556 public static function ristretto255_scalar_negate(
3557 #[SensitiveParameter]
3558 string $s,
3559 bool $dontFallback = false
3560 ): string {
3561 if (self::useNewSodiumAPI() && !$dontFallback) {
3562 return sodium_crypto_core_ristretto255_scalar_negate($s);
3563 }
3564 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_scalar_negate($s);
3565 }
3566
3567 /**
3568 * @param string $s
3569 * @param bool $dontFallback
3570 * @return string
3571 * @throws SodiumException
3572 */
3573 public static function ristretto255_scalar_complement(
3574 #[SensitiveParameter]
3575 string $s,
3576 bool $dontFallback = false
3577 ): string {
3578 if (self::useNewSodiumAPI() && !$dontFallback) {
3579 return sodium_crypto_core_ristretto255_scalar_complement($s);
3580 }
3581 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_scalar_complement($s);
3582 }
3583
3584 /**
3585 * @param string $x
3586 * @param string $y
3587 * @param bool $dontFallback
3588 * @return string
3589 * @throws SodiumException
3590 */
3591 public static function ristretto255_scalar_add(
3592 #[SensitiveParameter]
3593 string $x,
3594 #[SensitiveParameter]
3595 string $y,
3596 bool $dontFallback = false
3597 ): string {
3598 if (self::useNewSodiumAPI() && !$dontFallback) {
3599 return sodium_crypto_core_ristretto255_scalar_add($x, $y);
3600 }
3601 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_scalar_add($x, $y);
3602 }
3603
3604 /**
3605 * @param string $x
3606 * @param string $y
3607 * @param bool $dontFallback
3608 * @return string
3609 * @throws SodiumException
3610 */
3611 public static function ristretto255_scalar_sub(
3612 #[SensitiveParameter]
3613 string $x,
3614 #[SensitiveParameter]
3615 string $y,
3616 bool $dontFallback = false
3617 ): string {
3618 if (self::useNewSodiumAPI() && !$dontFallback) {
3619 return sodium_crypto_core_ristretto255_scalar_sub($x, $y);
3620 }
3621 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_scalar_sub($x, $y);
3622 }
3623
3624 /**
3625 * @param string $x
3626 * @param string $y
3627 * @param bool $dontFallback
3628 * @return string
3629 * @throws SodiumException
3630 */
3631 public static function ristretto255_scalar_mul(
3632 #[SensitiveParameter]
3633 string $x,
3634 #[SensitiveParameter]
3635 string $y,
3636 bool $dontFallback = false
3637 ): string {
3638 if (self::useNewSodiumAPI() && !$dontFallback) {
3639 return sodium_crypto_core_ristretto255_scalar_mul($x, $y);
3640 }
3641 return ParagonIE_Sodium_Core_Ristretto255::ristretto255_scalar_mul($x, $y);
3642 }
3643
3644 /**
3645 * @param string $n
3646 * @param string $p
3647 * @param bool $dontFallback
3648 * @return string
3649 * @throws SodiumException
3650 */
3651 public static function scalarmult_ristretto255(
3652 #[SensitiveParameter]
3653 string $n,
3654 #[SensitiveParameter]
3655 string $p,
3656 bool $dontFallback = false
3657 ): string {
3658 if (self::useNewSodiumAPI() && !$dontFallback) {
3659 return sodium_crypto_scalarmult_ristretto255($n, $p);
3660 }
3661 return ParagonIE_Sodium_Core_Ristretto255::scalarmult_ristretto255($n, $p);
3662 }
3663
3664 /**
3665 * @param string $n
3666 * @param bool $dontFallback
3667 * @return string
3668 * @throws SodiumException
3669 */
3670 public static function scalarmult_ristretto255_base(
3671 #[SensitiveParameter]
3672 string $n,
3673 bool $dontFallback = false
3674 ): string {
3675 if (self::useNewSodiumAPI() && !$dontFallback) {
3676 return sodium_crypto_scalarmult_ristretto255_base($n);
3677 }
3678 return ParagonIE_Sodium_Core_Ristretto255::scalarmult_ristretto255_base($n);
3679 }
3680
3681 /**
3682 * @param string $s
3683 * @param bool $dontFallback
3684 * @return string
3685 * @throws SodiumException
3686 */
3687 public static function ristretto255_scalar_reduce(
3688 #[SensitiveParameter]
3689 string $s,
3690 bool $dontFallback = false
3691 ): string {
3692 if (self::useNewSodiumAPI() && !$dontFallback) {
3693 return sodium_crypto_core_ristretto255_scalar_reduce($s);
3694 }
3695 return ParagonIE_Sodium_Core_Ristretto255::sc_reduce($s);
3696 }
3697
3698 /**
3699 * Add two numbers (little-endian unsigned), storing the value in the first
3700 * parameter.
3701 *
3702 * This mutates $val.
3703 *
3704 * @param string $val
3705 * @param string $addv
3706 * @return void
3707 * @throws SodiumException
3708 */
3709 public static function sub(
3710 #[SensitiveParameter]
3711 string &$val,
3712 #[SensitiveParameter]
3713 string $addv
3714 ): void {
3715 $val_len = ParagonIE_Sodium_Core_Util::strlen($val);
3716 $addv_len = ParagonIE_Sodium_Core_Util::strlen($addv);
3717 if ($val_len !== $addv_len) {
3718 throw new SodiumException('values must have the same length');
3719 }
3720 $A = ParagonIE_Sodium_Core_Util::stringToIntArray($val);
3721 $B = ParagonIE_Sodium_Core_Util::stringToIntArray($addv);
3722
3723 $c = 0;
3724 for ($i = 0; $i < $val_len; $i++) {
3725 $c = ($A[$i] - $B[$i] - $c);
3726 $A[$i] = ($c & 0xff);
3727 $c = ($c >> 8) & 1;
3728 }
3729 $val = ParagonIE_Sodium_Core_Util::intArrayToString($A);
3730 }
3731
3732 /**
3733 * This emulates libsodium's version_string() function, except ours is
3734 * prefixed with 'polyfill-'.
3735 *
3736 * @return string
3737 * @psalm-suppress MixedInferredReturnType
3738 * @psalm-suppress UndefinedFunction
3739 */
3740 public static function version_string(): string
3741 {
3742 if (self::useNewSodiumAPI()) {
3743 return sodium_version_string();
3744 }
3745 if (self::use_fallback('version_string')) {
3746 return (string) call_user_func('\\Sodium\\version_string');
3747 }
3748 return self::VERSION_STRING;
3749 }
3750
3751 /**
3752 * Should we use the libsodium core function instead?
3753 * This is always a good idea, if it's available. (Unless we're in the
3754 * middle of running our unit test suite.)
3755 *
3756 * If ext/libsodium is available, use it. Return TRUE.
3757 * Otherwise, we have to use the code provided herein. Return FALSE.
3758 *
3759 * @param string $sodium_func_name
3760 *
3761 * @return bool
3762 */
3763 protected static function use_fallback(string $sodium_func_name = ''): bool
3764 {
3765 static $res = null;
3766 if ($res === null) {
3767 $res = extension_loaded('libsodium') && PHP_VERSION_ID >= 50300;
3768 }
3769 if ($res === false) {
3770 // No libsodium installed
3771 return false;
3772 }
3773 if (self::$disableFallbackForUnitTests) {
3774 // Don't fallback. Use the PHP implementation.
3775 return false;
3776 }
3777 if (!empty($sodium_func_name)) {
3778 return is_callable('\\Sodium\\' . $sodium_func_name);
3779 }
3780 return true;
3781 }
3782
3783 /**
3784 * Libsodium as implemented in PHP 7.2
3785 * and/or ext/sodium (via PECL)
3786 *
3787 * @ref https://wiki.php.net/rfc/libsodium
3788 * @return bool
3789 */
3790 protected static function useNewSodiumAPI(): bool
3791 {
3792 static $res = null;
3793 if ($res === null) {
3794 $res = PHP_VERSION_ID >= 70000 && extension_loaded('sodium');
3795 }
3796 if (self::$disableFallbackForUnitTests) {
3797 // Don't fallback. Use the PHP implementation.
3798 return false;
3799 }
3800 return (bool) $res;
3801 }
3802 }