【问题标题】:Encrypting with GPG using PHP使用 PHP 使用 GPG 进行加密
【发布时间】:2011-10-13 08:43:32
【问题描述】:

我需要帮助使用 GPG 在 PHP 中加密文件。我做了一些研究,但我还没有找到解决方案。

在命令行中使用 GPG 效果很好,但是当我从 PHP 中尝试时,我得到一个返回值 2。 我还尝试过将“--yes --always-trust”作为额外的开关传递给命令,正如关于 SO 的答案之一所建议的那样,但没有任何乐趣。

我尝试过使用 PHP 中内置的 gnupg 函数——我发现的所有示例都显示了如何加密字符串而不是文件。将文件作为字符串读取对我来说不起作用,因为我正在处理大至 15MB 的大文件。

我需要帮助!

环境详情

OS: Windows 7
PHP installation: WAMP Server 2.1

代码

$path = "c:\wamp\www";
$recipient = "Test user";
$encrypted_file = "c:\wamp\www\test.txt.gpg";
$decrypted_file = "c:\wamp\www\decrypted_test.txt";
$plain_file = "c:\wamp\www\test.txt";

exec('gpg --homedir $path --recipient $recipient --output $encrypted_file --encrypt $plain_file --yes --always-trust', $answer, $rtn);

var_dump($answer);
var_dump($rtn);
echo "<br />ANSWER: ".$answer;
echo "<br />RTN: ".$rtn;

输出

array(0) { } int(2) 
ANSWER: Array
RTN: 2
PHP User: nt authority\system

【问题讨论】:

    标签: php windows exec gnupg


    【解决方案1】:

    尝试改变

    exec('gpg --homedir $path --recipient $recipient --output $encrypted_file --encrypt                     $plain_file --yes --always-trust', $answer, $rtn);
    

    exec("gpg --homedir $path --recipient $recipient --output $encrypted_file --encrypt                     $plain_file --yes --always-trust", $answer, $rtn);
    

    注意我把单引号改成了双引号

    http://php.net/manual/en/language.types.string.php

    【讨论】:

    • 我听从了你的建议,但输出还是一样
    • Raptor 和 Vascowhite 非常感谢 - 你让我走上了正确的道路。我能够让它工作。问题是开关值需要在双引号 ("") 内。 exec("gpg --homedir \"$path\" --recipient \"$recipient\" --output \"$encrypted_file\" --encrypt \"$plain_file\" --yes --always-trust", $answer, $rtn);
    【解决方案2】:

    你混淆了单引号和双引号的使用。

    $path = 'c:\wamp\www';
    $recipient = 'Test user';
    $encrypted_file = 'c:\wamp\www\test.txt.gpg';
    $decrypted_file = 'c:\wamp\www\decrypted_test.txt';
    $plain_file = 'c:\wamp\www\test.txt';
    

    在这一行:

    exec("C:\\Wamp\\WWW\\gpg --homedir $path --recipient $recipient --output $encrypted_file --encrypt                     $plain_file --yes --always-trust", $answer, $rtn);
    

    当字符串需要被PHP解析时使用双引号(注意转义字符);不需要解析字符串时使用单引号。

    【讨论】:

    • 我听从了你的建议,但输出还是一样
    • 复查执行权?另外,您应该为exec()函数提供GPG的完整路径。
    • 执行权限:PHP 用户是 nt authority\system - 我猜这个用户应该有执行权限。 GPG 的完整路径:我按照建议的步骤在 C:\Wamp\WWW 中运行了本地版本的 GPG (glump.net/howto/gpg_intro)
    • 不是真的。 NT_AUTHORITY\SYSTEM 不一定有权限。您应该仔细检查文件夹访问权限。例如,在某些情况下,PHP 用户对 C:\WINDOWS\Temp 没有权限
    猜你喜欢
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2015-08-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多