gpt4 book ai didi

php - 如何使用 gnupg 在 PHP 中导入 pgp 私钥?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:22 24 4
gpt4 key购买 nike

我需要使用先前生成的私钥 (private.pgp) 和密码来签署 MD5 哈希。 (例如 123456abc)在 apache2 上运行的 php 脚本中。我也在使用 gnupg。

这就是我现在的做法:

<?php
$keyring = "/pubkeys/.gnupg"; //this direcrtory owned by www-data
putenv("GNUPGHOME=$keyring");

$res = gnupg_init();
var_dump($res); //for debug

$info = gnupg_import($res,'private.pgp');
var_dump($info); //for debug

?>

因此,gnupg_import() 返回给我 false。为什么会这样?我还尝试使用此 php 脚本从同一目录中的文件中读取 key ,但出现了相同的错误。请帮忙。

谢谢。

最佳答案

假设您使用的是基于 Ubuntu/Debian 的操作系统,这就是我处理这种情况的方式:安装依赖项。

  1. sudo apt-get 更新
  2. sudo apt-get install software-properties-common gnupg gnupg2
  3. sudo add-apt-repository -y ppa:ondrej/php
  4. sudo apt-get install php7.4-{gnupg,intl,mbstring,cli,xml}

创建简单测试脚本的步骤。

  1. 创建一个名为test_pgp的目录
  2. cd/test_pgp
  3. 生成 OpenPGP key gpg --full-generate-key(按照提示操作,但不要输入密码)。
  4. 导出公钥 gpg --armor --export your_email@example.com >public_key.asc
  5. 导出私钥gpg --armor --export-secret-keysyour_email@example.com >private_key.asc

执行上面的步骤4 和5 后,您应该有两个文件private_key.ascpublic_key.asc现在在同一文件夹中创建 pgp_example.php 文件并添加以下代码行:

<?php
$gpg = new gnupg();

$privateAsciiKey = file_get_contents('private_key.asc');
$publicAsciiKey = file_get_contents('public_key.asc');

/**
* import private and public keys
*/
$privateKey = $gpg->import($privateAsciiKey);
$publicKey = $gpg->import($publicAsciiKey);
$fingerprint = $publicKey['fingerprint'];
$passphrase = ''; // empty string because we didn't set a passphrase.
$plain_text = "Put Some text to encrypt here";

// catch errors
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

// encrypt plain text
try{
$gpg->addencryptKey($fingerprint);
$ciphertext = $gpg->encrypt($plain_text);
echo "\n". $ciphertext ."\n";
}
catch(Exception $e){
die('Error '.$e->getMessage());
}

// decrypt text
try{
$gpg->adddecryptkey($fingerprint, $passphrase);
$plain_text = $gpg->decrypt($ciphertext);
echo "\n". $plain_text ."\n";
}
catch(Exception $e){
die('Error: '. $e->getMessage());
}

要执行此代码,请打开终端并运行 php pgp_example.php

关于php - 如何使用 gnupg 在 PHP 中导入 pgp 私钥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41293097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com