123456789101112131415161718192021222324252627282930313233343536373839404142 |
- <?php
- namespace Juju\Data;
- require_once('encryption.class.php');
- class SecureString implements \JsonSerializable {
- private $data = '';
- private $password;
- private $iv;
- private $encryption;
- private function __construct(string $data){
- $tries = 0;
- $methods = Encryption::methods();
- do{
- $method = $methods[random_int(0, count($methods) - 1)];
- try{
- $this->encryption = Encryption::from($method);
- $ivlen = $this->encryption->iv_len();
- $this->password = openssl_random_pseudo_bytes($ivlen);
- $this->iv = openssl_random_pseudo_bytes($ivlen);
- $this->data = $this->encryption->encrypt($data, $this->password, $this->iv);
- }catch(\Exception $e){}
- if(++$tries == count($methods)){
- throw new \Exception("Too many failed attempts to encrypt data");
- }
- // If for some reason the data we encrypted will not decrypt, try again until it will
- }while($data != (string)$this);
- }
- public function __toString(){
- try{
- return ''.$this->encryption->decrypt($this->data, $this->password, $this->iv);
- }catch(\Exception $e){
- return '';
- }
- }
- public function jsonSerialize(){
- return "{$this}";
- }
- public static function from(string $data){
- return new self($data);
- }
- }
- ?>
|