如何通过php使用gpg加密文件

来自:互联网
时间:2021-07-06
阅读:

环境

  • macOS Sierra 10.12.1

  • php 7.0.8

安装gpg环境

macOS:
$ brew install gpg
CentOS
$ yum install gnupg
php

安装gnupg扩展,具体方法参考我的旧文:使用phpize安装php扩展

导入私钥,公钥随之导入

$ gpg --import /Users/xjnotxj/downloads/6e.pri

如何通过php使用gpg加密文件

测试密钥正确性[可跳过]

加密文件
$ 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

使用php加密文件

// 设置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();
}
返回顶部
顶部