所以假设问题如下:
- 您需要在存储数据之前对其进行加密。
- 你不应该有解密它的密钥,只加密它。
这实际上有一个工具:它被称为密封 API,它可以通过 OpenSSL 或 Libsodium 来完成。
使用 Libsodium 在 PHP 中密封/解封数据
$store_me = \Sodium\crypto_box_seal(
$plaintext,
$recipient_public_key
);
$visible = \Sodium\crypto_box_seal_open(
$store_me,
$recipient_keypair
);
使用 OpenSSL 在 PHP 中密封/解封数据
/**
* A human-usable variant of openssl_seal()
*
* @param string $plaintext Your message
* @param string $publickey_string PEM-encoded RSA public key
* @param boolean $encode Hex-encode the output?
*
* @return string
*/
function easy_seal($plaintext, $publickey_string, $encode = false)
{
$pubkey = openssl_get_publickey($publickey_string);
if ($pubkey === false) {
throw new Exception('Could not load public key');
}
$sealed = '';
$ekeys = [];
$result = openssl_seal($plaintext, $sealed, $ekeys, [$pubkey]);
if ($result === false) {
throw new Exception('openssl_seal failed!');
}
if ($encode) {
return json_encode([
bin2hex($sealed),
bin2hex($ekeys[0])
]);
}
return json_encode([$sealed, $ekeys[0]]);
}
/**
* Inverse operation of easy_seal()
*
* @param string $ciphertext (the output of easy_seal())
* @param string $privatekey_string PEM-encoded RSA private key
* @param boolean $encoded Do we need to decode from hex?
*
* @return string
*/
function easy_unseal($ciphertext, $privatekey_string, $encoded = false)
{
list($sealed, $ekey) = json_decode($ciphertext, true);
if ($encoded) {
$sealed = hex2bin($sealed);
$ekey = hex2bin($ekey);
}
$open_data = '';
$privkey = openssl_get_privatekey($privatekey_string);
if ($privkey === false) {
throw new Exception('Could not load public key');
}
$result = openssl_open($sealed, $open_data, $ekey, $privkey);
if ($result === false) {
throw new Exception('openssl_open failed!');
}
return $open_data;
}
使用示例
$public_key = file_get_contents('/path/to/publickey.pem');
$plaintext = 'Something something dark side';
$store_me = easy_seal($plaintext, $public_key);
// Elsewhere:
$secret_key = file_get_contents('/path/to/secretkey.pem');
$visible = easy_unseal($store_me, $secret_key);
演示:https ://3v4l.org/BNavp