method = $method; } public function __get(string $name){ switch($name){ case 'method': return $this->method; default: throw new \Exception("Property {$name} does not exist"); } } public static function methods(){ if(is_null(self::$methods)){ $methods = openssl_get_cipher_methods(true); $methods = array_map('StrToLower', $methods); $methods = array_intersect_key( $methods, array_unique($methods) ); $methods = array_diff($methods, [ 'aes-128-ccm', 'aes-128-gcm', 'aes-128-xts', 'aes-192-ccm', 'aes-192-gcm', 'aes-256-ccm', 'aes-256-gcm', 'id-aes128-ccm', 'id-aes128-gcm', 'id-aes128-wrap', 'id-aes192-ccm', 'id-aes192-gcm', 'id-aes192-wrap', 'id-aes256-ccm', 'id-aes256-gcm', 'id-aes256-wrap', 'id-smime-alg-cms3deswrap' ]); self::$methods = array_values(array_unique($methods)); } return self::$methods; } public static function from(string $method){ if(!in_array($method, self::methods())){ throw new \Exception("Unsupported OpenSSL method: {$method}"); } if(!isset(Encryption::$instances[$method])){ Encryption::$instances[$method] = new Encryption($method); } return Encryption::$instances[$method]; } public function __toString(){ return $this->method.''; } public function iv_len(){ return openssl_cipher_iv_length($this->method); } public function encrypt(string $data, string $key, string $iv){ $ret = openssl_encrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv); if($ret === false){ throw new \Exception("Encryption ({$this->method}) failed: ".openssl_error_string()); } return $ret; } public function decrypt(string $data, string $key, string $iv){ $ret = openssl_decrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv); if($ret === false){ throw new \Exception("Decryption ({$this->method}) failed: ".openssl_error_string()); } return $ret; } } ?>