SodiumMarshaller.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Marshaller;
  11. use Symfony\Component\Cache\Exception\CacheException;
  12. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. /**
  14. * Encrypt/decrypt values using Libsodium.
  15. *
  16. * @author Ahmed TAILOULOUTE <ahmed.tailouloute@gmail.com>
  17. */
  18. class SodiumMarshaller implements MarshallerInterface
  19. {
  20. private MarshallerInterface $marshaller;
  21. /**
  22. * @param string[] $decryptionKeys The key at index "0" is required and is used to decrypt and encrypt values;
  23. * more rotating keys can be provided to decrypt values;
  24. * each key must be generated using sodium_crypto_box_keypair()
  25. */
  26. public function __construct(
  27. private array $decryptionKeys,
  28. ?MarshallerInterface $marshaller = null,
  29. ) {
  30. if (!self::isSupported()) {
  31. throw new CacheException('The "sodium" PHP extension is not loaded.');
  32. }
  33. if (!isset($decryptionKeys[0])) {
  34. throw new InvalidArgumentException('At least one decryption key must be provided at index "0".');
  35. }
  36. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  37. }
  38. public static function isSupported(): bool
  39. {
  40. return \function_exists('sodium_crypto_box_seal');
  41. }
  42. public function marshall(array $values, ?array &$failed): array
  43. {
  44. $encryptionKey = sodium_crypto_box_publickey($this->decryptionKeys[0]);
  45. $encryptedValues = [];
  46. foreach ($this->marshaller->marshall($values, $failed) as $k => $v) {
  47. $encryptedValues[$k] = sodium_crypto_box_seal($v, $encryptionKey);
  48. }
  49. return $encryptedValues;
  50. }
  51. public function unmarshall(string $value): mixed
  52. {
  53. foreach ($this->decryptionKeys as $k) {
  54. if (false !== $decryptedValue = @sodium_crypto_box_seal_open($value, $k)) {
  55. $value = $decryptedValue;
  56. break;
  57. }
  58. }
  59. return $this->marshaller->unmarshall($value);
  60. }
  61. }