php使用openssl來實現非對稱加密

使用非對稱加密主要是藉助openssl的公鑰和私鑰,用公鑰加密私鑰解密,或者私鑰加密公鑰解密。php

安裝openssl和php的openssl擴展

生成私鑰:openssl genrsa 用於生成rsa私鑰文件,生成是能夠指定私鑰長度和密碼保護

openssl genrsa -out rsa_private_key.pem 1024

生成公鑰:rsa命令用於處理RSA密鑰、格式轉換和打印信息

openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

這裏咱們使用公鑰加密,私鑰解密

class Openssl
{

   /**
     * [$instance description]
     * @var null
     */
    protected static $instance = null;

   /**
     * [$error description]
     * @var null
     */
	public $error = null;

      /**
	 * [$rsa_private_key 移鑰]
	 * @var string
	 */
	public $rsa_private_key = '';

       /**
	 * [$rsa_public_key 公鑰]
	 * @var string
	 */
	public $rsa_public_key = '';

   /**
     * [__construct description]
     * @author: edge
     * @time: 2017/10/22
     */
    public function __construct()
    {
    	$this->rsa_private_key_path = __DIR__ . '/key/rsa_private_key.pem';
    	$this->rsa_public_key_path = __DIR__ . '/key/rsa_public_key.pem';
    	if (!file_exists($this->rsa_private_key_path)) {
    		throw new \Exception('私鑰不存在');
    	}
    	if (!file_exists($this->rsa_public_key_path)) {
    		throw new \Exception('公鑰不存在');
    	}
    	if(!extension_loaded('openssl')){
    		throw new \Exception('缺乏openssl擴展');
    	}
    	$this->rsa_private_key = openssl_pkey_get_private(file_get_contents($this->rsa_private_key_path));
    	$this->rsa_public_key = openssl_pkey_get_public(file_get_contents($this->rsa_public_key_path));
    	if (!$this->rsa_private_key) {
    		throw new \Exception('私鑰不可用');
    	}
    	if (!$this->rsa_public_key) {
    		throw new \Exception('公鑰不可用');
    	}
    }

   /**
     * 單例
     * @author: edge
     * @time: 2017/10/22
     * @return class
     */
    public static function getInstance()
    {
        if(empty(static::$instance)){
            static::$instance = new static();
        }
        return static::$instance;
    }

    /**
     * [Base64Encrypt 公鑰加密]
     * @author: edge
     * @time: 2017/10/22
     * @param string $str [description]
     */
    public function Base64Encrypt($str = '')
    {
    	if (!empty($str)) {
    		$str = json_encode($str);
    		if(openssl_public_encrypt($str,$sign,$this->rsa_public_key)){
    			return base64_encode($sign);
    		} else {
    			throw new \Exception('加密數據出錯');
    		}
    	} else {
    		throw new \Exception('要加密的原始數據爲空');
    	}
    }

   /**
     * [Base64Decrypt 私鑰解密]
     * @author: edge
     * @time: 2017/10/22
     * @param string $str [description]
     */
    public function Base64Decrypt($str = '')
    {
    	if (!empty($str)) {
    		$str = base64_decode($str);
    		if(openssl_private_decrypt($str,$design,$this->rsa_private_key)){
    			$design = json_decode($design);
    			return $design;
    		} else {
    			throw new \Exception('解密數據出錯');
    		}
    	} else {
    		throw new \Exception('要解密的數據爲空');
    	}
    }

}
相關文章
相關標籤/搜索