securestring.class.php 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace Juju\Data;
  3. class SecureString implements \JsonSerializable {
  4. private $data;
  5. private $password;
  6. private $iv;
  7. private $method;
  8. private static $methods = null;
  9. private function __construct(string $data){
  10. do{
  11. if(is_null(self::$methods)){
  12. self::$methods = openssl_get_cipher_methods();
  13. }
  14. $this->method = self::$methods[random_int(0, count(self::$methods) - 1)];
  15. $ivlen = openssl_cipher_iv_length($this->method);
  16. $this->password = openssl_random_pseudo_bytes($ivlen);
  17. $this->iv = openssl_random_pseudo_bytes($ivlen);
  18. $this->data = openssl_encrypt($data, $this->method, $this->password, \OPENSSL_RAW_DATA, $this->iv);
  19. // If for some reason the data we encrypted will not decrypt, try again until it will
  20. }while($data != (string)$this);
  21. }
  22. public function __toString(){
  23. return ''.openssl_decrypt($this->data, $this->method, $this->password, \OPENSSL_RAW_DATA, $this->iv);
  24. }
  25. public function jsonSerialize(){
  26. return "{$this}";
  27. }
  28. public static function from(string $data){
  29. return new self($data);
  30. }
  31. }
  32. ?>