src/Twig/CryptExtension.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\Twig;
  3. use Twig\Extension\AbstractExtension;
  4. use Twig\TwigFilter;
  5. class CryptExtension extends AbstractExtension
  6. {
  7. private $encryptionKey = "2bfe6c40";
  8. private $encryptionMethod = 'AES-128-CBC';
  9. public function __construct()
  10. {
  11. }
  12. public function getFilters(): array
  13. {
  14. return [
  15. new TwigFilter('encrypt', [$this, 'encryptValue']),
  16. new TwigFilter('decrypt', [$this, 'decryptValue']),
  17. ];
  18. }
  19. public function encryptValue(string $value): string
  20. {
  21. $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->encryptionMethod));
  22. $encrypted = openssl_encrypt($value, $this->encryptionMethod, $this->encryptionKey, 0, $iv);
  23. return base64_encode($iv . $encrypted);
  24. }
  25. public function decryptValue(string $encryptedValue): string
  26. {
  27. $data = base64_decode($encryptedValue);
  28. $ivLength = openssl_cipher_iv_length($this->encryptionMethod);
  29. $iv = substr($data, 0, $ivLength);
  30. $encryptedData = substr($data, $ivLength);
  31. return openssl_decrypt($encryptedData, $this->encryptionMethod, $this->encryptionKey, 0, $iv);
  32. }
  33. }