key = $key; } /** * @param string $method * * @throws Exception */ public function setMethod(string $method): void { if (!in_array($method, $this->getAvailableMethods(), true)) { throw new Exception('Method unknowed'); } $this->method = $method; } /** * @return array */ public function getAvailableMethods(): array { $ciphers = openssl_get_cipher_methods(); $ciphersAndAliases = openssl_get_cipher_methods(true); $cipherAliases = array_diff($ciphersAndAliases, $ciphers); $ciphers = array_filter($ciphers, function ($n) { return mb_stripos($n, 'ecb') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, 'des') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, 'rc2') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, 'rc4') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, 'md5') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, '-ocb') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, '-ccm') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, '-gcm') === false; }); $ciphers = array_filter($ciphers, function ($c) { return mb_stripos($c, '-wrap') === false; }); $cipherAliases = array_filter($cipherAliases, function ($c) { return mb_stripos($c, 'des') === false; }); $cipherAliases = array_filter($cipherAliases, function ($c) { return mb_stripos($c, 'rc2') === false; }); $cipherAliases = array_filter($cipherAliases, function ($c) { return mb_stripos($c, '-wrap') === false; }); $methods = array_merge($ciphers, $cipherAliases); $methods = array_filter($methods, function ($c) { return !in_array($c, ['AES-128-CBC-HMAC-SHA1', 'AES-256-CBC-HMAC-SHA1'], true); }); return $methods; } /** * @param $data * * @throws \Exception * * @return string|bool */ public function decrypt(string $data) { $this->throwExceptionIfKeyEmpty(); if (mb_strlen($data) === 0) { return ''; } list($encrypted_data, $iv) = explode('::', base64_decode($data, true), 2); return openssl_decrypt($encrypted_data, $this->method, $this->key, 0, $iv); } /** * @param $data * * @throws \Exception * * @return mixed */ public function encrypt(string $data): string { $this->throwExceptionIfKeyEmpty(); $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->method)); $encrypted = openssl_encrypt($data, $this->method, $this->key, 0, $iv); $data = base64_encode($encrypted . '::' . $iv); return $data; } /** * @throws \Exception */ protected function throwExceptionIfKeyEmpty() { if (null === $this->key || mb_strlen($this->key) === 0) { throw new Exception('Key is empty'); } } }