securestring.class.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. try{
  29. return ''.$this->encryption->decrypt($this->data, $this->password, $this->iv);
  30. }catch(\Exception $e){
  31. return '';
  32. }
  33. }
  34. public function jsonSerialize(){
  35. return "{$this}";
  36. }
  37. public static function from(string $data){
  38. return new self($data);
  39. }
  40. }
  41. ?>