securestring.class.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. namespace Juju\Data;
  3. require_once('encryption.class.php');
  4. class SecureString implements \JsonSerializable {
  5. private $data;
  6. private $password;
  7. private $iv;
  8. private $encryption;
  9. private function __construct(string $data){
  10. $tries = 0;
  11. $methods = Encryption::methods();
  12. do{
  13. $method = $methods[random_int(0, count($methods) - 1)];
  14. $this->encryption = Encryption::from($method);
  15. $ivlen = $this->encryption->iv_len();
  16. $this->password = openssl_random_pseudo_bytes($ivlen);
  17. $this->iv = openssl_random_pseudo_bytes($ivlen);
  18. $this->data = $this->encryption->encrypt($data, $this->password, $this->iv);
  19. if(++$tries == count($methods)){
  20. throw new \Exception("Too many failed attempts to encrypt data");
  21. }
  22. // If for some reason the data we encrypted will not decrypt, try again until it will
  23. }while($data != (string)$this);
  24. }
  25. public function __toString(){
  26. return ''.$this->encryption->decrypt($this->data, $this->password, $this->iv);
  27. }
  28. public function jsonSerialize(){
  29. return "{$this}";
  30. }
  31. public static function from(string $data){
  32. return new self($data);
  33. }
  34. }
  35. ?>