SodiumMarshaller.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 $marshaller;
  21. private $decryptionKeys;
  22. /**
  23. * @param string[] $decryptionKeys The key at index "0" is required and is used to decrypt and encrypt values;
  24. * more rotating keys can be provided to decrypt values;
  25. * each key must be generated using sodium_crypto_box_keypair()
  26. */
  27. public function __construct(array $decryptionKeys, ?MarshallerInterface $marshaller = null)
  28. {
  29. if (!self::isSupported()) {
  30. throw new CacheException('The "sodium" PHP extension is not loaded.');
  31. }
  32. if (!isset($decryptionKeys[0])) {
  33. throw new InvalidArgumentException('At least one decryption key must be provided at index "0".');
  34. }
  35. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  36. $this->decryptionKeys = $decryptionKeys;
  37. }
  38. public static function isSupported(): bool
  39. {
  40. return \function_exists('sodium_crypto_box_seal');
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function marshall(array $values, ?array &$failed): array
  46. {
  47. $encryptionKey = sodium_crypto_box_publickey($this->decryptionKeys[0]);
  48. $encryptedValues = [];
  49. foreach ($this->marshaller->marshall($values, $failed) as $k => $v) {
  50. $encryptedValues[$k] = sodium_crypto_box_seal($v, $encryptionKey);
  51. }
  52. return $encryptedValues;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function unmarshall(string $value)
  58. {
  59. foreach ($this->decryptionKeys as $k) {
  60. if (false !== $decryptedValue = @sodium_crypto_box_seal_open($value, $k)) {
  61. $value = $decryptedValue;
  62. break;
  63. }
  64. }
  65. return $this->marshaller->unmarshall($value);
  66. }
  67. }