审查视图

simplewind/vendor/baidu/Utility.php 2.3 KB
董瑞恩 authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
<?php
/**
 * Utility, provide RSA public encrypt method and gzdecode function
 */
class RsaPublicEncrypt {
    /**
     * @var string
     */
    private $publicKey;
    
    /**
     * @var string
     */
    private $path;

    /**
     * construct
     * @param string $path
     */
    public function __construct($path)
    {
        if(empty($path) || !is_dir($path))
        {
            echo "[error] error public key path: {$path}" . PHP_EOL;
        }
        $this->path = $path;
    }

    /**
     * setup public key
     * @return boolean
     */
    public function setupPublicKey()
    {
        if(is_resource($this->publicKey))
        {
            return true;
        }
        $file = $this->path . DIRECTORY_SEPARATOR .  'api_pub.key';

        $puk = file_get_contents($file);

        $this->publicKey = openssl_pkey_get_public($puk);
        return true;
    }

    /**
     * pub encrypt
     * @param string $data
     * @return string
     */
    public function pubEncrypt($data)
    {
        if(!is_string($data))
        {
            return null;
        }
        $this->setupPublicKey();
        $ret = openssl_public_encrypt($data, $encrypted, $this->publicKey);
        if($ret)
        {
            return $encrypted;
        }
        else
        {
            return null;
        }
    }
    
    /**
     * destruct
     */
    public function __destruct()
    {
        @fclose($this->publicKey);
    }
}

if (!function_exists('gzdecode')) {
    /**
     * gzdecode
     * @param string $data
     * @return string
     */
    function gzdecode($data) { 
        $flags = ord(substr($data, 3, 1)); 
        $headerlen = 10; 
        $extralen = 0; 
        $filenamelen = 0; 
        if ($flags & 4) {
            $extralen = unpack('v' ,substr($data, 10, 2)); 
            $extralen = $extralen[1]; 
            $headerlen += 2 + $extralen; 
        }       
        if ($flags & 8) {
            $headerlen = strpos($data, chr(0), $headerlen) + 1; 
        }
        if ($flags & 16) {
            $headerlen = strpos($data, chr(0), $headerlen) + 1; 
        }
        if ($flags & 2) {
            $headerlen += 2; 
        }
        $unpacked = @gzinflate(substr($data, $headerlen)); 
        if ($unpacked === false) {
            $unpacked = $data;
        }
        return $unpacked; 
    } 
}