securestring.class.php 971 B

123456789101112131415161718192021222324252627282930
  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. if(is_null(self::$methods)){
  11. self::$methods = openssl_get_cipher_methods();
  12. }
  13. $this->method = self::$methods[random_int(0, count(self::$methods))];
  14. $ivlen = openssl_cipher_iv_length($this->method);
  15. $this->password = openssl_random_pseudo_bytes($ivlen);
  16. $this->iv = openssl_random_pseudo_bytes($ivlen);
  17. $this->data = openssl_encrypt($data, $this->method, $this->password, \OPENSSL_RAW_DATA, $this->iv);
  18. }
  19. public function __toString(){
  20. return openssl_decrypt($this->data, $this->method, $this->password, \OPENSSL_RAW_DATA, $this->iv);
  21. }
  22. public function jsonSerialize(){
  23. return "{$this}";
  24. }
  25. public static function from(string $data){
  26. return new self($data);
  27. }
  28. }
  29. }
  30. ?>