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

如何使用gnupg在PHP中导入pgp私钥?,php,linux,apache,gnupg,Php,Linux,Apache,Gnupg,我需要使用先前生成的私钥(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

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


谢谢。

手册是您的朋友:第二个参数应该是数据,而不是文件名。
–Sammitch

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

  • sudoapt获得更新
  • sudo apt获取安装软件属性通用gnupg gnupg2
  • sudo add apt repository-y ppa:ondrej/php
  • sudo apt get install php7.4-{gnupg,intl,mbstring,cli,xml}
  • 创建简单测试脚本的步骤。

  • 创建一个名为test\u pgp的目录
  • cd/test\U pgp
  • 生成OpenPGP密钥gpg——完全生成密钥(按照提示进行操作,但不要 输入密码短语)
  • 导出公钥gpg--armor--Export_email@example.com > 公钥.asc
  • 导出私钥gpg--armor--Export秘钥 你的_email@example.com > 私钥.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());
    }
    

    手册是你的朋友:第二个参数应该是数据,而不是文件名。@Sammitch谢谢你,兄弟!你的建议真的很有用,现在问题解决了!