*/ class OpenSSL { protected ?\OpenSSLAsymmetricKey $publicKey; protected ?\OpenSSLAsymmetricKey $privateKey; public function __construct(string $publicKeyPath, string $privateKeyPath, Filesystem $filesystem) { if ($filesystem->exists($publicKeyPath)) { $this->publicKey = openssl_pkey_get_public(file_get_contents($publicKeyPath)); } if ($filesystem->exists($privateKeyPath)) { $this->privateKey = openssl_pkey_get_private(file_get_contents($privateKeyPath)); } } /** * Encrypts data by using the public key. */ public function encrypt($data): ?string { if (empty($this->publicKey)) { throw new \RuntimeException('Public key needed.'); } openssl_public_encrypt($data, $result, $this->publicKey); return $result; } /** * Decrypts data by using the private key. */ public function decrypt($data): ?string { if (empty($this->privateKey)) { throw new \RuntimeException('Private key needed.'); } openssl_private_decrypt($data, $result, $this->privateKey); return $result; } public function decryptEntity(EncryptedEntityInterface $entity): EncryptedEntityInterface { foreach ($entity->getEncryptedProperties() as $property) { $getter = 'get'.$property; $setter = 'set'.$property; $encryptedValue = $entity->{$getter}(); if (!is_resource($encryptedValue)) { continue; } $encryptedValue = stream_get_contents($encryptedValue, -1, 0); $entity->{$setter}($this->decrypt($encryptedValue)); } return $entity; } public function encryptEntity(EncryptedEntityInterface $entity): EncryptedEntityInterface { foreach ($entity->getEncryptedProperties() as $property) { $getter = 'get'.$property; $setter = 'set'.$property; $value = (string) $entity->{$getter}(); $entity->{$setter}($this->encrypt($value)); } return $entity; } }