SodiumChachaIetf.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Framework\Encryption\Adapter;
  8. /**
  9. * Sodium adapter for encrypting and decrypting strings
  10. */
  11. class SodiumChachaIetf implements EncryptionAdapterInterface
  12. {
  13. /**
  14. * @var string
  15. */
  16. private $key;
  17. /**
  18. * Sodium constructor.
  19. * @param string $key
  20. */
  21. public function __construct(
  22. string $key
  23. ) {
  24. $this->key = $key;
  25. }
  26. /**
  27. * Encrypt a string
  28. *
  29. * @param string $data
  30. * @return string string
  31. */
  32. public function encrypt(string $data): string
  33. {
  34. $nonce = random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES);
  35. $cipherText = sodium_crypto_aead_chacha20poly1305_ietf_encrypt(
  36. (string)$data,
  37. $nonce,
  38. $nonce,
  39. $this->key
  40. );
  41. return $nonce . $cipherText;
  42. }
  43. /**
  44. * Decrypt a string
  45. *
  46. * @param string $data
  47. * @return string
  48. */
  49. public function decrypt(string $data): string
  50. {
  51. $nonce = mb_substr($data, 0, SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES, '8bit');
  52. $payload = mb_substr($data, SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES, null, '8bit');
  53. $plainText = sodium_crypto_aead_chacha20poly1305_ietf_decrypt(
  54. $payload,
  55. $nonce,
  56. $nonce,
  57. $this->key
  58. );
  59. return $plainText;
  60. }
  61. }