| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace App\Common\Library;
- class Encryptor
- {
- /**
- * Holds the Encryptor instance
- * @var Encryptor
- */
- private static $instance;
- /**
- * @var string
- */
- private $method;
- /**
- * @var string
- */
- private $key;
- /**
- * @var string
- */
- private $separator;
- /**
- * Encryptor constructor.
- */
- public function __construct($key, $method = 'aes-256-cfb')
- {
- $this->method = $method;
- $this->key = $key;
- $this->separator = ':';
- }
- private function __clone()
- {
- }
- /**
- * Returns an instance of the Encryptor class or creates the new instance if the instance is not created yet.
- * @return Encryptor
- */
- public static function getInstance()
- {
- if (self::$instance === null) {
- self::$instance = new Encryptor();
- }
- return self::$instance;
- }
- /**
- * Generates the initialization vector
- * @return string
- */
- private function getIv()
- {
- return openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->method));
- }
- /**
- * @param string $data
- * @return string
- */
- public function encrypt($data)
- {
- $iv = $this->getIv();
- return base64_encode(openssl_encrypt($data, $this->method, $this->key, 0, $iv) . $this->separator . base64_encode($iv));
- }
- /**
- * @param string $dataAndVector
- * @return string
- */
- public function decrypt($dataAndVector)
- {
- $parts = explode($this->separator, base64_decode($dataAndVector));
- // $parts[0] = encrypted data
- // $parts[1] = initialization vector
- return openssl_decrypt($parts[0], $this->method, $this->key, 0, base64_decode($parts[1]));
- }
- }
|