Encryptor.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Common\Library;
  3. class Encryptor
  4. {
  5. /**
  6. * Holds the Encryptor instance
  7. * @var Encryptor
  8. */
  9. private static $instance;
  10. /**
  11. * @var string
  12. */
  13. private $method;
  14. /**
  15. * @var string
  16. */
  17. private $key;
  18. /**
  19. * @var string
  20. */
  21. private $separator;
  22. /**
  23. * Encryptor constructor.
  24. */
  25. public function __construct($key, $method = 'aes-256-cfb')
  26. {
  27. $this->method = $method;
  28. $this->key = $key;
  29. $this->separator = ':';
  30. }
  31. private function __clone()
  32. {
  33. }
  34. /**
  35. * Returns an instance of the Encryptor class or creates the new instance if the instance is not created yet.
  36. * @return Encryptor
  37. */
  38. public static function getInstance()
  39. {
  40. if (self::$instance === null) {
  41. self::$instance = new Encryptor();
  42. }
  43. return self::$instance;
  44. }
  45. /**
  46. * Generates the initialization vector
  47. * @return string
  48. */
  49. private function getIv()
  50. {
  51. return openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->method));
  52. }
  53. /**
  54. * @param string $data
  55. * @return string
  56. */
  57. public function encrypt($data)
  58. {
  59. $iv = $this->getIv();
  60. return base64_encode(openssl_encrypt($data, $this->method, $this->key, 0, $iv) . $this->separator . base64_encode($iv));
  61. }
  62. /**
  63. * @param string $dataAndVector
  64. * @return string
  65. */
  66. public function decrypt($dataAndVector)
  67. {
  68. $parts = explode($this->separator, base64_decode($dataAndVector));
  69. // $parts[0] = encrypted data
  70. // $parts[1] = initialization vector
  71. return openssl_decrypt($parts[0], $this->method, $this->key, 0, base64_decode($parts[1]));
  72. }
  73. }