【发布时间】:2019-11-15 20:18:48
【问题描述】:
我需要对无法存储为纯文本的非敏感数据进行简单的加密/解密。我把这个类放在一起,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"])
);
}
}
【问题讨论】:
-
你有什么错误或输出吗?
-
使用更现代的built-in functions 几乎肯定会更好。
标签: php openssl php-openssl