<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class CryptExtension extends AbstractExtension
{
private $encryptionKey = "2bfe6c40";
private $encryptionMethod = 'AES-128-CBC';
public function __construct()
{
}
public function getFilters(): array
{
return [
new TwigFilter('encrypt', [$this, 'encryptValue']),
new TwigFilter('decrypt', [$this, 'decryptValue']),
];
}
public function encryptValue(string $value): string
{
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->encryptionMethod));
$encrypted = openssl_encrypt($value, $this->encryptionMethod, $this->encryptionKey, 0, $iv);
return base64_encode($iv . $encrypted);
}
public function decryptValue(string $encryptedValue): string
{
$data = base64_decode($encryptedValue);
$ivLength = openssl_cipher_iv_length($this->encryptionMethod);
$iv = substr($data, 0, $ivLength);
$encryptedData = substr($data, $ivLength);
return openssl_decrypt($encryptedData, $this->encryptionMethod, $this->encryptionKey, 0, $iv);
}
}