encryption.class.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace Juju\Data;
  3. class Encryption {
  4. private static $methods = null;
  5. private static $instances = [];
  6. private $method = null;
  7. private function __construct(string $method){
  8. $this->method = $method;
  9. }
  10. public function __get(string $name){
  11. switch($name){
  12. case 'method':
  13. return $this->method;
  14. default:
  15. throw new \Exception("Property {$name} does not exist");
  16. }
  17. }
  18. public static function methods(){
  19. if(is_null(self::$methods)){
  20. self::$methods = openssl_get_cipher_methods();
  21. }
  22. return self::$methods;
  23. }
  24. public static function from(string $method){
  25. if(!in_array($method, self::methods())){
  26. throw new Exception("Unsupported OpenSSL method: {$method}");
  27. }
  28. if(!isset(Encryption::$instances[$method])){
  29. Encryption::$instances[$method] = new Encryption($method);
  30. }
  31. return Encryption::$instances[$method];
  32. }
  33. public function __toString(){
  34. return $this->method.'';
  35. }
  36. public function iv_len(){
  37. return openssl_cipher_iv_length($this->method);
  38. }
  39. public function encrypt(string $data, string $key, string $iv){
  40. return openssl_encrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv);
  41. }
  42. public function decrypt(string $data, string $key, string $iv){
  43. return openssl_decrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv);
  44. }
  45. }
  46. ?>