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);//普通解密

 

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