时间:2021-07-01 10:21:17 帮助过:19人阅读

背景:客户提供私钥,并要求我方通过php把加密后的文件传输给他们。
macOS Sierra 10.12.1
php 7.0.8
$ brew install gpg
$ yum install gnupg
安装gnupg扩展,具体方法参考我的旧文:使用phpize安装php扩展
$ gpg --import /Users/xjnotxj/downloads/6e.pri

$ gpg --recipient 0D39xxxx --output test_file.xls.gpg --encrypt test_file.xls
0D39xxxx => 上图的#1
$ gpg -o test_file_new.xls -d test_file.xls.gpg
$ gpg -o pubkey.txt -a --export e6e6xxxx
e6e6xxxx => 上图的#2
// 设置gnupg在你本机的路径
putenv('GNUPGHOME=/root/.gnupg');
try {
//获取公钥
$publicKey = file_get_contents('application/report/pubkey.txt');
//初始化gpg
$gpg = new gnupg();
//开启调试
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);
//导入公钥
$info = $gpg->import($publicKey);
//获取公钥指纹
$gpg->addencryptkey($info['fingerprint']);
//获取需要加密的文件
$uploadFileContent = file_get_contents($filename);
//加密文件
$enc = $gpg->encrypt($uploadFileContent);
//保存文件到本地
$filename = 'application/report/'.'file_xls' . '.gpg';
file_put_contents($filename, $enc);
} catch (Exception $e) {
//log something
return $e->getMessage();
}推荐学习:php视频教程
以上就是如何通过php使用gpg加密文件的详细内容,更多请关注gxlcms其它相关文章!