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

Xeo*_*oss 12 php cryptography pgp php-openssl libsodium

我有一小段一些数据(小于1kb),我希望用户代理从我的网站发送到其他网站.为了让其他站点验证我是创建字符串的那个,我有两个选项.

  1. 服务器请回要我确认(如paypal,openid等..)
  2. 我使用公钥/私钥来证明我发送的消息(如PGP,DKIM等)

我不想设置HMAC,因为这意味着我必须为每个站点使用自定义键,这将是一个痛苦.

在这两个选择中,似乎#2会节省带宽,这使它看起来是更好的选择.

那么如何使用PHP设置公钥/私钥加密,是否有任何缺点?

Ebo*_*bob 20

使用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"];
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用私钥和公钥加密和解密,如下所示:

// 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";
Run Code Online (Sandbox Code Playgroud)

  • 您可以自己保留私钥,并给其他人公钥。 (2认同)

vy3*_*y32 11

我将使用OpenSSL创建S/MIME公钥/私钥对,然后使用OpenSSL命令进行加密和解密.我相信这优于使用PGP,因为openssl包含在大多数Linux操作系统中而PGP不包含在内.一旦你关闭了命令,OpenSSL也是基于标准的,通常更容易使用.

我建议不要使用"纯PHP"解决方案(纯PHP,我的意思是在PHP中使用加密,而不是使用PHP来调用现有的库或单独的可执行文件).你不想在PHP中进行批量加密.太慢了.并且您希望使用OpenSSL,因为它具有高性能并且可以很好地理解安全性.

这是魔术.

制作X.509密钥:

$subj="/C=US/ST=California/L=Remote/O=Country Govt./OU=My Dept/CN=Mr. Agent/emailAddress=agent@investiations.com"
openssl req -x509 -newkey rsa:1024 -keyout mycert.key -out mycert.pem -nodes -subj $subj
Run Code Online (Sandbox Code Playgroud)

这将私钥放在mycert.key中,而公钥放在mycert.pem中.私钥不受密码保护.

现在,使用S/MIME签名消息:

openssl smime -sign -signer mycert.pem -inkey mycert.key <input >output
Run Code Online (Sandbox Code Playgroud)

使用S/MIME加密消息:

openssl smime -encrypt -recip yourcert.pem <input >output
Run Code Online (Sandbox Code Playgroud)

要使用S/MIME解密消息:

openssl smime -decrypt -inkey mycert.key -certfile mycert.pem <input >output
Run Code Online (Sandbox Code Playgroud)

我还有一些演示使用来自C语言绑定的OpenSSL,但不是来自PHP.

  • 为什么PHP的[OpenSSL扩展](http://us2.php.net/manual/en/book.openssl.php)比调用OpenSSL本身要慢?无论哪种方式运行相同的代码.也就是说,还有另外一个原因就是不使用PHP本机:OpenSSL扩展无法在使用异国情调的密钥格式时执行任何外壳打开到openssl二进制文件. (5认同)
  • 我是查尔斯的第二个评论.PHP OpenSSL扩展可能会更快*,而不是更慢,因为它使用与openssl命令行应用程序相同的API,但没有进程创建开销. (2认同)