/** * @param string/array $data [待加密的字符串或者是數組] * @uses rsa公鑰加密 */ private function rsaPublicEncrypt($data = '') { if (is_array($data)) { $formatData = json_encode($data, JSON_UNESCAPED_UNICODE); } else { $formatData = $data; } //三方rsa公鑰文件路徑 $publicKeyPath = $this->config['rsaKey'] . 'tongchengjieqian.pub.key'; $keyContent = @file_get_contents($publicKeyPath); $formatKey = $this->rsaPubKey($keyContent); $publicKey = openssl_pkey_get_public($formatKey); $publicLength = openssl_pkey_get_details($publicKey)['bits']; $encrypted = ''; $part_len = $publicLength / 8 - 11; $parts = str_split($formatData, $part_len); foreach ($parts as $part) { $encrypted_temp = ''; openssl_public_encrypt($part, $encrypted_temp, $publicKey); $encrypted .= $encrypted_temp; } return $this->dataBase64Encode($encrypted); }
/** * @param $rsaPubKeyStr * @return string * @uses rsa公鑰處理 */ private function rsaPubKey($rsaPubKeyStr) { $base64 = str_replace(array('-', '_'), array('+', '/'), $rsaPubKeyStr); $strKey = (wordwrap($base64, 64, PHP_EOL, true)) . PHP_EOL; return "-----BEGIN PUBLIC KEY-----" . PHP_EOL . $strKey . "-----END PUBLIC KEY-----" . PHP_EOL; }
/** * @param $data * @return string|string[] * @uses urlBase64加碼處理 */ private function dataBase64Encode($data) { return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($data)); }
/** * @param json $data [轉換爲json後的待簽名數據] * @uses 數據加簽 */ private function rsaSign($data) { //己方rsa私鑰文件路徑 $privateKeyPath = $this->config['rsaKey'] . 'ryt.pri.key'; $privateContent = @file_get_contents($privateKeyPath); $privateKey = openssl_pkey_get_private($privateContent); openssl_sign($data, $sign, $privateKey, self::RSA_ALGORITHM_SIGN_TYPE); return $this->dataBase64Encode($sign); }
/** * @param json $decryptData [同步返回解密後的json數據] * @param string $signature [同步返回的簽名] * @return int 0 || 1 [1:驗籤成功 0:驗籤失敗] * @uses 數據驗籤 */ private function verifySign($decryptData, $signature) { //三方rsa公鑰文件路徑 $publicKeyPath = $this->config['rsaKey'] . 'tongchengjieqian.pub.key'; $keyContent = @file_get_contents($publicKeyPath); $formatKey = $this->rsaPubKey($keyContent); $publicKey = openssl_pkey_get_public($formatKey); $sign = $this->dataBase64Decode($signature); $result = openssl_verify($decryptData, $sign, $publicKey, self::RSA_ALGORITHM_SIGN_TYPE); return $result; }
/** * @param $data * @return false|string * @uses urlBase64解碼處理 */ private function dataBase64Decode($data) { $base_64 = str_replace(array('-', '_'), array('+', '/'), $data); return base64_decode($base_64); }
目錄
/** * @return string $uniqid [唯一流水號] * @uses 生成請求流水號 */ private function generateNumber() { $uniqid = substr(uniqid(), 5, 8) . '-' . rand(1000, 9999) . '-' . substr(uniqid(), 9, 4) . '-' . rand(1000, 9999) . '-' . $this->getRandKey(2); return $uniqid; }