GPG在PHP中的使用

GPG加密使用

 

 

官网:https://www.gnupg.org/download/index.en.html

 

安装软件

1Libgpg-error

2Libassuan

3GPGME

 

PHP扩展安装

来源站点:https://pecl.php.net/package/gnupg

安装方法:

Phpize

./configure

Make & make install

生成私钥与公钥:

gpg –gen-key

接下来跟随一步一步选择与执行,其中一步需要填写密码,可以选填,当填写密码后解密需要键入密码才能解密。

 

查看公钥:

gpg --list-keys

查看私钥:

gpg --list-secret-keys

 

MASTERKEYID KEY_ID如上面查看公钥,MASTERKEYID 94A2DECE

导出公钥:

gpg -o pubkey.txt -a --export MASTERKEYID 

Pubkey.txt为导出的目标文件,会把公钥保存在pubkey.txt

导出私钥:

gpg -o prikey.txt -a --export-secret-keys MASTERKEYID 

Pubkey.txt为导出的目标文件,会把公钥保存在prikey.txt

 

生成和使用撤销证书

生成二进制证书:

gpg --output revocation-gmail.cert --gen-revoke MASTERKEYID 

导出证书:

gpg -a -o revocation-gmail.txt --gen-revoke MASTERKEYID 

php扩展的使用

基于gnupg开发加密操作类

<?php
namespace tools;
/**
 * Created by PhpStorm.
 * User: ShaunXu
 * Date: 2019/4/15
 * Time: 13:56
 */
class gpg{
    public $publicKeyFile = ROOT."gpg_keys/public-key-gmail.gpg";       //公钥地址
    public $privateKeyFile = ROOT."gpg_keys/secret-key-gmail.gpg";      //私钥地址
    public $publicKey = null;                                   //公钥KEY
    public $privateKey = null;                                  //私钥KEY
    public $gpg = null;                                         //gpg对象
    private $startTime = 0;
    /**
     * 状态码
     * @Variable code_msg
     * @author ShaunXu
     * @var array
     */
    public $code_msg = array(
        0 => "成功",
        1 => "公钥文件不存在",
        2 => "需要加密的文件不存在",
        3 => "私钥文件不存在",
        4 => "需要解密的文件不存在",
        5 => "签名验证失败",
        500 => "错误"
    );

    /**
     * gpg constructor.
     */
    function __construct()
    {
        $this->startTime = $this->msectime();
        putenv("GNUPGHOME=".GNUPGHOME);

        if($this->gpg == null){
            try{
                $this->gpg = new \gnupg();
                $this->gpg->seterrormode(\gnupg::ERROR_EXCEPTION);
            }catch (\Exception $e){
                return false;
            }
        }
        return true;
    }

    /**
     * 获取加密KEY
     * getKey
     * @author ShaunXu
     * @date 2019/4/15
     * @param string $type
     * @return bool|string
     */
    private function getKey($type = "public"){
        if($this->publicKey != null && $type == "public") return $this->publicKey;
        if($this->privateKey != null && $type == "private") return $this->privateKey;
        $file = $type == "public" ? $this->publicKeyFile : $this->privateKeyFile;
        $key = $this->readFile($file);
        return $key;
    }

    /**
     * 设置公钥
     * setPublicKey
     * @author ShaunXu
     * @date 2019/4/17
     * @param $key
     */
     function setPublicKey($key){
        $this->publicKey = $key;
     }

    /**
     * 设置私钥
     * setPrivateKey
     * @author ShaunXu
     * @date 2019/4/17
     * @param $key
     */
     function setPrivateKey($key){
         $this->privateKey = $key;
     }

    /**
     * 设置公钥文件存储地址
     * setPublicKeyFile
     * @author ShaunXu
     * @date 2019/4/17
     * @param $file
     */
     function setPublicKeyFile($file){
         $this->publicKeyFile = $file;
         $key = $this->readFile($file);
         if($key != false) $this->publicKey = $key;
     }

    /**
     * 设置私钥文件存储地址
     * setPrivateKeyFile
     * @author ShaunXu
     * @date 2019/4/17
     * @param $file
     */
     function setPrivateKeyFile($file){
         $this->privateKeyFile = $file;
         $key = $this->readFile($file);
         if($key != false) $this->privateKey = $key;
     }

    /**
     * 读取文件
     * readFile
     * @author ShaunXu
     * @date 2019/4/15
     * @param $file
     * @return bool|string
     */
    private function readFile($file){
        if(file_exists($file)){
            return file_get_contents($file);
        }
        return false;
    }

    /**
     * 加密文件
     * encrypt
     * @author ShaunXu
     * @date 2019/4/17
     * @param $content      //需要加密的内容
     * @return array
     */
    function encrypt($content) {
        $this->startTime = $this->msectime();
        try {
            $publicKey = $this->getKey();                       //获取公钥
            if(!$publicKey) return $this->result(1);
            $info = $this->gpg->import($publicKey);             //导入公钥
            $this->gpg->addencryptkey($info['fingerprint']);    //获取公钥指纹
            $enc = $this->gpg->encrypt($content);               //加密文件
        } catch (Exception $e) {
            return $this->result(500 , $e->getMessage());
        }
        return $this->result(0 , $enc);
    }

    /**
     * 解密文件
     * decrypt
     * @author ShaunXu
     * @date 2019/4/18
     * @param $content
     * @param string $pass
     * @return array
     */
    function decrypt($content , $pass = ""){
        $this->startTime = $this->msectime();
        try{
            $privateKeyData = $this->getKey("private");//导入私钥用于解密,导入后会自动找该私密解密
            if(!$privateKeyData) return $this->result(3);
            $privateInfo = $this->gpg->import($privateKeyData);
            $this->gpg->adddecryptkey($privateInfo['fingerprint'],$pass);//fingerprint为钥匙指纹
            $plaintext = $this->gpg->decrypt($content);
        }catch (\Exception $e){
            return $this->result(500 , $e->getMessage());
        }
        return $this->result(0 , $plaintext);
    }

    /**
     * 获取毫秒时间戳
     * msectime
     * @author ShaunXu
     * @date 2019/4/16
     * @return float
     */
    function msectime(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    /**
     * 结果输出
     * result
     * @author ShaunXu
     * @date 2019/4/15
     * @param int $code
     * @param string $data
     * @return array
     */
    function result($code = 0 , $data = ""){
        $endTime = $this->msectime();
        return array(
            "code" => $code,
            "duration" => $endTime - $this->startTime,
            "message" => $this->code_msg[$code],
            "data" => $data
        );
    }
}

 

使用示例:

//加密

$gpg=newgpg();

$content=file_get_contents($file);//需要加密的内容

$gpg->setPublicKey($pubkey);//设置公钥Key存储文件

$result=$gpg->encrypt($content);//普通加密

//解密

$pass="";                       //生成key时输入的密码

$gpg->setPrivateKey($priKey);

$result=$gpg->decrypt($content,$pass);//普通解密

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章