<?php
namespace ModulesAbstract\ElectronicInvoice\Encryption; class OpenSSL extends EncryptionAbstract { protected $cipher_algo = null; protected $passphrase = null; protected $iv = null; public function destroy() { $this->cipher_algo = null; $this->passphrase = null; $this->iv = null; return parent::destroy(); } public function setCipherAlgo($cipher_algo) { $this->cipher_algo = $cipher_algo; return $this; } public function setPassphrase($passphrase) { $this->passphrase = $passphrase; return $this; } public function setIV($iv) { $this->iv = $iv; return $this; } public function encrypt($data) { $cipher_algo = ($this->cipher_algo!==null?$this->cipher_algo:reset(openssl_get_cipher_methods())); $ivlen = openssl_cipher_iv_length($cipher_algo); $passphrase = ($this->passphrase!==null?$this->passphrase:openssl_random_pseudo_bytes($ivlen)); $iv = ($this->iv!==null?$this->iv:openssl_random_pseudo_bytes($ivlen)); $encryptedData = openssl_encrypt($data, $this->cipher_algo, $passphrase, OPENSSL_RAW_DATA, $iv); return [$encryptedData, [ 'cipher_algo' => $cipher_algo, 'passphrase' => $passphrase, 'iv' => $iv, ]]; } public function decrypt($encryptedData, $params = []) { if (!$encryptedData) { throw new \RuntimeException(sprintf("Cannot decrypt provided data. No data provided")); } $data = openssl_decrypt($encryptedData, ($params['cipher_algo']!==null?$params['cipher_algo']:$this->cipher_algo), ($params['passphrase']!==null?$params['passphrase']:$this->passphrase), OPENSSL_RAW_DATA, ($params['iv']!==null?$params['iv']:$this->iv) ); if ($data===false) { throw new \RuntimeException(sprintf("Cannot decrypt provided data. Data length: %d. Please also check provided cipher_algo,passphrase,iv", strlen($encryptedData))); } return $data; } } 