我有一小串数据(小于 1kb),我希望用户代理在从我的网站发送这些数据时将其传递到其他网站。为了让其他网站验证我是否是创建该字符串的网站,我考虑了两个选项。
- 服务器向我发送 ping 消息以进行确认(例如 paypal、openid 等)
- 我使用公钥/私钥来证明我发送了消息(例如 PGP、DKIM 等)
我不想设置 HMAC,因为这意味着我必须为每个站点使用自定义 key ,这会很痛苦。
在这两个选择中,#2 似乎可以节省带宽,这使得它看起来是一个更好的选择。
那么如何使用 PHP 设置公钥/私钥加密技术,有什么缺点吗?
最佳答案
使用 PHP Openssl 函数创建私钥和公钥对:
// Configuration settings for the key
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
// Create the private and public key
$res = openssl_pkey_new($config);
// Extract the private key into $private_key
openssl_pkey_export($res, $private_key);
// Extract the public key into $public_key
$public_key = openssl_pkey_get_details($res);
$public_key = $public_key["key"];
然后您可以使用私钥和公钥进行加密和解密,如下所示:
// Something to encrypt
$text = 'This is the text to encrypt';
echo "This is the original text: $text\n\n";
// Encrypt using the public key
openssl_public_encrypt($text, $encrypted, $public_key);
$encrypted_hex = bin2hex($encrypted);
echo "This is the encrypted text: $encrypted_hex\n\n";
// Decrypt the data using the private key
openssl_private_decrypt($encrypted, $decrypted, $private_key);
echo "This is the decrypted text: $decrypted\n\n";
关于php - 如何使用公钥/私钥加密 PHP 中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4629537/