繁体   English   中英

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

[英]How to import pgp private key in PHP with gnupg?

我需要使用以前生成的私钥(private.pgp)和密码来签署 MD5-hash。 (例如 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 脚本从同一目录中的文件中读取密钥,但遇到了相同的错误。 请帮忙。

谢谢你。

手册是您的朋友: php.net/manual/en/function.gnupg-import.php第二个参数应该是数据,而不是文件名。 – 萨米奇

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

  1. sudo apt-get 更新
  2. sudo apt-get install software-properties-common gnupg gnupg2
  3. 须藤添加-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 密钥gpg --full-generate-key (按照提示操作,但不要输入密码)。
  4. 导出公钥gpg --armor --export your_email@example.com > public_key.asc
  5. 导出私钥gpg --armor --export-secret-keys your_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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM