[英]How to import pgp private key in PHP with gnupg?
I'm need to to sign MD5-hash with previosly generated private key (private.pgp) and passphrase.我需要使用以前生成的私钥(private.pgp)和密码来签署 MD5-hash。 (for example 123456abc) within php script that running on apache2.
(例如 123456abc)在 apache2 上运行的 php 脚本中。 I'm using gnupg also.
我也在使用 gnupg。
This is how i'm doing it now:这就是我现在的做法:
<?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
?>
So, gnupg_import() returns me false .所以, gnupg_import() 返回给我false 。 Why this is happening?
为什么会发生这种情况? I've also tried to read key from a file in the same dir with this php-script, but had the same error.
我还尝试使用此 php 脚本从同一目录中的文件中读取密钥,但遇到了相同的错误。 Please, help.
请帮忙。
Thank you.谢谢你。
The manual is your friend: php.net/manual/en/function.gnupg-import.php The second argument is supposed to be the data, not the filename.手册是您的朋友: php.net/manual/en/function.gnupg-import.php第二个参数应该是数据,而不是文件名。 – Sammitch
– 萨米奇
Assuming that you are on Ubuntu/Debian based operating system this is how I would approach the situation: Install dependencies.假设您使用的是基于 Ubuntu/Debian 的操作系统,这就是我处理这种情况的方式:安装依赖项。
Steps for creating a simple test script.创建简单测试脚本的步骤。
After executing steps 4 & 5 above you should have two files private_key.asc and public_key.asc Now create pgp_example.php file on the same folder and add the following lines of code:执行上面的步骤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());
}
To execute this code open terminal and run php pgp_example.php要执行此代码打开终端并运行php pgp_example.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.