当前位置: 首页 > 后端技术 > PHP

使用gpg加密文件-通过shell或php

时间:2023-03-30 03:30:30 PHP

背景:客户提供私钥,让我们通过php把加密后的文件传给他们。环境macOSSierra10.12.1php7.0.8安装gpg环境macOS:$brewinstallgpgCentOS$yuminstallgnupgphpinstallgnupgextension具体方法参考我的旧文章:使用phpize安装php扩展导入私钥,再导入公钥到$gpg--import/Users/xjnotxj/downloads/6e.pri测试密钥正确性[可跳过]加密文件$gpg--recipient0D39xxxx--outputtest_file.xls.gpg--encrypttest_file.xls0D39xxxx=>以上#1解密file$gpg-otest_file_new.xls-dtest_file.xls.gpgexportpublickey$gpg-opubkey.txt-a--exporte6e6xxxxe6e6xxxx=>#2上图使用php加密文件//setgnupginYourlocalpathputenv('GNUPGHOME=/root/.gnupg');try{//获取公钥$publicKey=file_get_contents('application/report/pubkey.txt');//初始化gpg$gpg=newgnupg();//启用调试$gpg->seterrormode(gnupg::ERROR_EXCEPTION);//导入公钥$info=$gpg->import($publicKey);//获取公钥指纹$gpg->addencryptkey($info['fingerprint']);//获取待加密文件$uploadFileContent=file_get_contents($filename);//加密文件$enc=$gpg->encrypt($uploadFileContent);//保存文件到本地$filename='applicationn/报告/'.'file_xls'。'.gpg';file_put_contents($filename,$enc);}catch(Exception$e){//logsomethingreturn$e->getMessage();}参考PHP官方API