1
0

encryption.class.php 2.2 KB

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