[英]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 的操作系统,这就是我处理这种情况的方式:安装依赖项。
创建简单测试脚本的步骤。
执行上面的步骤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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.