1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- <?php
- namespace Juju\Data;
- class Encryption {
- private static $methods = null;
- private static $instances = [];
- private $method = null;
- private function __construct(string $method){
- $this->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)){
- self::$methods = openssl_get_cipher_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){
- return openssl_encrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv);
- }
- public function decrypt(string $data, string $key, string $iv){
- return openssl_decrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv);
- }
- }
- ?>
|