PHP 中使用 GnuPG 实现 PGP 加密与解密的完整实践指南

PHP 中使用 GnuPG 实现 PGP 加密与解密的完整实践指南 本文详解如何在 PHP 中借助 GnuPG 扩展正确实现基于 RSA 的 PGP 加密与解密重点纠正常见误区如解密时未设置私钥密码和未调用 adddecryptkey并提供可直接运行的健壮示例代码。 本文详解如何在 php 中借助 gnupg 扩展正确实现基于 rsa 的 pgp 加密与解密重点纠正常见误区如解密时未设置私钥密码和未调用 adddecryptkey并提供可直接运行的健壮示例代码。在 PHP 中实现符合 OpenPGP 标准的加密/解密推荐使用官方 gnupg 扩展底层调用 GnuPG 命令行工具而非手动实现 RSA 运算——这不仅确保协议兼容性支持签名、压缩、对称加密层等 PGP 特性也规避了密钥管理、填充模式、会话密钥派生等高危细节。但实践中开发者常因忽略关键配置导致解密失败例如仅导入私钥却未通过 adddecryptkey() 显式声明解密凭据或遗漏私钥密码passphrase参数。以下是一个经过验证、生产就绪的完整实现?php// 1. 配置 GnuPG 环境务必指定独立、可写的 GNUPGHOMEputenv(GNUPGHOME/tmp/gnupg-.uniqid()); // 避免多请求冲突mkdir(getenv(GNUPGHOME), 0700, true);// 2. 初始化 GnuPG 实例并启用异常模式便于调试$gpg new gnupg();$gpg-seterrormode(gnupg::ERROR_EXCEPTION);// 3. 加载密钥文件确保权限安全.asc 文件应仅 PHP 可读$publicKeyData file_get_contents(/path/to/public.asc);$privateKeyData file_get_contents(/path/to/private.asc);// 4. 导入密钥并获取指纹关键必须检查导入结果$publicImport $gpg-import($publicKeyData);$privateImport $gpg-import($privateKeyData);if (empty($publicImport[fingerprint]) || empty($privateImport[fingerprint])) { throw new RuntimeException(密钥导入失败请检查 ASC 文件格式及完整性);}$fingerprint $publicImport[fingerprint];$secretFingerprint $privateImport[fingerprint];// 5. 设置加密与解密密钥?? 核心修正点$gpg-addencryptkey($fingerprint); // 指定公钥用于加密$gpg-adddecryptkey($secretFingerprint, your_passphrase_here); // 必须提供私钥密码// 6. 执行加密与解密$plaintext Hello, this is a PGP-encrypted message.;$encrypted $gpg-encrypt($plaintext);echo Encrypted: . wordwrap($encrypted, 64, , true) . ;$decrypted $gpg-decrypt($encrypted);echo Decrypted: . $decrypted . ;echo Integrity check: . ($plaintext $decrypted ? ? PASS : ? FAIL) . ;关键注意事项 蝉妈妈AI 电商人专属的AI营销助手