encryption.class.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. $methods = openssl_get_cipher_methods(true);
  21. $methods = array_map('StrToLower', $methods);
  22. $methods = array_intersect_key(
  23. $methods,
  24. array_unique($methods)
  25. );
  26. $methods = array_diff($methods, [
  27. 'aes-128-ccm',
  28. 'aes-128-gcm',
  29. 'aes-128-xts',
  30. 'aes-192-ccm',
  31. 'aes-192-gcm',
  32. 'aes-256-ccm',
  33. 'aes-256-gcm',
  34. 'aes-256-xts',
  35. 'id-aes128-ccm',
  36. 'id-aes128-gcm',
  37. 'id-aes128-wrap',
  38. 'id-aes192-ccm',
  39. 'id-aes192-gcm',
  40. 'id-aes192-wrap',
  41. 'id-aes256-ccm',
  42. 'id-aes256-gcm',
  43. 'id-aes256-wrap',
  44. 'id-smime-alg-cms3deswrap'
  45. ]);
  46. self::$methods = array_values(array_unique($methods));
  47. }
  48. return self::$methods;
  49. }
  50. public static function from(string $method){
  51. if(!in_array($method, self::methods())){
  52. throw new \Exception("Unsupported OpenSSL method: {$method}");
  53. }
  54. if(!isset(Encryption::$instances[$method])){
  55. Encryption::$instances[$method] = new Encryption($method);
  56. }
  57. return Encryption::$instances[$method];
  58. }
  59. public function __toString(){
  60. return $this->method.'';
  61. }
  62. public function iv_len(){
  63. return openssl_cipher_iv_length($this->method);
  64. }
  65. public function encrypt(string $data, string $key, string $iv){
  66. $ret = openssl_encrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv);
  67. if($ret === false){
  68. throw new \Exception("Encryption ({$this->method}) failed: ".openssl_error_string());
  69. }
  70. return $ret;
  71. }
  72. public function decrypt(string $data, string $key, string $iv){
  73. $ret = openssl_decrypt($data, $this->method, $key, \OPENSSL_RAW_DATA, $iv);
  74. if($ret === false){
  75. throw new \Exception("Decryption ({$this->method}) failed: ".openssl_error_string());
  76. }
  77. return $ret;
  78. }
  79. }
  80. ?>