123456789101112131415161718192021222324252627282930313233 |
- <?php
- namespace Juju\Data;
- class SecureString implements \JsonSerializable {
- private $data;
- private $password;
- private $iv;
- private $method;
- private static $methods = null;
- private function __construct(string $data){
- do{
- if(is_null(self::$methods)){
- self::$methods = openssl_get_cipher_methods();
- }
- $this->method = self::$methods[random_int(0, count(self::$methods) - 1)];
- $ivlen = openssl_cipher_iv_length($this->method);
- $this->password = openssl_random_pseudo_bytes($ivlen);
- $this->iv = openssl_random_pseudo_bytes($ivlen);
- $this->data = openssl_encrypt($data, $this->method, $this->password, \OPENSSL_RAW_DATA, $this->iv);
- // If for some reason the data we encrypted will not decrypt, try again until it will
- }while($data != (string)$this);
- }
- public function __toString(){
- return ''.openssl_decrypt($this->data, $this->method, $this->password, \OPENSSL_RAW_DATA, $this->iv);
- }
- public function jsonSerialize(){
- return "{$this}";
- }
- public static function from(string $data){
- return new self($data);
- }
- }
- ?>
|