【问题标题】:How to import pgp private key in PHP with gnupg?如何使用 gnupg 在 PHP 中导入 pgp 私钥?
【发布时间】:2017-05-08 16:00:03
【问题描述】:

我需要使用先前生成的私钥 (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 脚本从同一目录中的文件中读取密钥,但出现了相同的错误。请帮忙。

谢谢。

【问题讨论】:

标签: php linux apache gnupg


【解决方案1】:

假设您使用的是基于 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 密钥 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.asc 和 public_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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      相关资源
      最近更新 更多