鍍金池/ 問(wèn)答/PHP  C  網(wǎng)絡(luò)營(yíng)銷(xiāo)  HTML/ 微信小程序登錄,服務(wù)端解密有幾率-41003

微信小程序登錄,服務(wù)端解密有幾率-41003

服務(wù)器是將unionId作為唯一id的,需要使用WXBizDataCrypt.decryptData將encryptedData解密出來(lái)。不過(guò)在調(diào)用WXBizDataCrypt.decryptData的時(shí)候總是又會(huì)30%的幾率解密失敗,返回errorCode -41003

服務(wù)器端語(yǔ)言:PHP (Laravel框架)

報(bào)錯(cuò)為:openssl_decrypt(): IV passed is only 15 bytes long…ects an IV of precisely 16 bytes, padding with 0

補(bǔ)充:每次小程序獲取到iv的值中間有空格的,就會(huì)出錯(cuò)
成功的iv例子:$iv = "MLbq\/WIGb1YHk8f0GWmzLA=="

出錯(cuò)的iv例子:$iv = "shNiHyqyaVamI Fe\/YHUjw=="

WXBizDataCrypt類(lèi)

<?php
namespace App\Libs\WeChat;

use App\Libs\WeChat\errorCode;

/**
 * 對(duì)微信小程序用戶加密數(shù)據(jù)的解密示例代碼.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

class WXBizDataCrypt
{
    private $appid;
    private $sessionKey;

    public function __construct( $appid, $sessionKey) {
        $this->sessionKey = $sessionKey;
        $this->appid = $appid;
    }

    /**
     * 構(gòu)造函數(shù)
     * @param $sessionKey string 用戶在小程序登錄后獲取的會(huì)話密鑰
     * @param $appid string 小程序的appid
     */
    public function WXBizDataCrypt( $appid, $sessionKey)
    {
        $this->sessionKey = $sessionKey;
        $this->appid = $appid;

    }


    /**
     * 檢驗(yàn)數(shù)據(jù)的真實(shí)性,并且獲取解密后的明文.
     * @param $encryptedData string 加密的用戶數(shù)據(jù)
     * @param $iv string 與用戶數(shù)據(jù)一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0,失敗返回對(duì)應(yīng)的錯(cuò)誤碼
     */
    public function decryptData( $encryptedData, $iv, &$data )
    {
        if (strlen($this->sessionKey) != 24) {
            return ErrorCode::$IllegalAesKey;
        }
        $aesKey=base64_decode($this->sessionKey);

        
        if (strlen($iv) != 24) {
            return ErrorCode::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return ErrorCode::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return ErrorCode::$IllegalBuffer;
        }
        $data = $result;
        return ErrorCode::$OK;
    }

}

回答
編輯回答
互擼娃

【結(jié)貼】iv小程序端請(qǐng)求的時(shí)候用encodeURIComponent函數(shù)進(jìn)行urlencode就好了(空格其實(shí)是符號(hào):+ ?)

2017年4月9日 18:03