securestring.class.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. try{
  15. $this->encryption = Encryption::from($method);
  16. $ivlen = $this->encryption->iv_len();
  17. $this->password = openssl_random_pseudo_bytes($ivlen);
  18. $this->iv = openssl_random_pseudo_bytes($ivlen);
  19. $this->data = $this->encryption->encrypt($data, $this->password, $this->iv);
  20. }catch(\Exception $e){}
  21. if(++$tries == count($methods)){
  22. throw new \Exception("Too many failed attempts to encrypt data");
  23. }
  24. // If for some reason the data we encrypted will not decrypt, try again until it will
  25. }while($data != (string)$this);
  26. }
  27. public function __toString(){
  28. return ''.$this->encryption->decrypt($this->data, $this->password, $this->iv);
  29. }
  30. public function jsonSerialize(){
  31. return "{$this}";
  32. }
  33. public static function from(string $data){
  34. return new self($data);
  35. }
  36. }
  37. ?>