[英]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.