php - 如何使用公钥/私钥加密 PHP 中的数据?

标签 php cryptography pgp php-openssl libsodium

我有一小串数据(小于 1kb),我希望用户代理在从我的网站发送这些数据时将其传递到其他网站。为了让其他网站验证我是否是创建该字符串的网站,我考虑了两个选项。

  1. 服务器向我发送 ping 消息以进行确认(例如 paypal、openid 等)
  2. 我使用公钥/私钥来证明我发送了消息(例如 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/

相关文章:

php - windows 10 中的文件 ini_set 在哪里 我为什么这个脚本有错误

php - 需要使用 array_key_exists 从 mysql 获取数据值

php - Docker 进程分离和源代码控制

c# - 在 C# 中生成 HMAC-SHA1

linux - libtasn1 未找到,但我已经安装了

java - 从共享路径读取文件,身份验证为 Java.io.File

ruby - 如何使用 Ruby gpgme 解密 PGP 加密文件

php - Magento 哪个文件有导航菜单栏的代码?

go - 为什么一些 golang.org 包以 `x` 为前缀

c# - Bouncy CaSTLe C# PGP 解密示例