Мне нужно простое шифрование/дешифрование для неконфиденциальных данных, которые я не могу хранить в виде обычного текста. Я собрал этот класс, и openssl_decrypt возвращает false, но я не могу понять, почему.
$ssl=new ssl();
$x="this was encrpyted";
echo "<br />1".$x;
$json=$ssl->encrypt($x);
echo "<br />2".$json;
echo "<br />3".$ssl->decrypt($json);
class ssl {
private $cipher = "aes-128-gcm";
private $options=0;
public function encrypt($plaintext) {
$key=openssl_random_pseudo_bytes(16);
$ivlen=openssl_cipher_iv_length($this->cipher);
$iv=openssl_random_pseudo_bytes($ivlen);
$ciphertext=openssl_encrypt(
$plaintext,
$this->cipher,
$key,
$this->options,
$iv,
$tag
);
$a=[];
$a["key"]=bin2hex($key);
$a["iv"]=bin2hex($iv);
$a["ciphertext"]=$ciphertext;
return json_encode($a);
}
public function decrypt($json) {
$a=json_decode($json,true);
return openssl_decrypt(
$a["ciphertext"],
$this->cipher,
hex2bin($a["key"]),
$this->options,
hex2bin($a["iv"])
);
}
}