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

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

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

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

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

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

出錯的iv例子:$iv = "shNiHyqyaVamI Fe\/YHUjw=="

WXBizDataCrypt類

<?php
namespace App\Libs\WeChat;

use App\Libs\WeChat\errorCode;

/**
 * 對微信小程序用戶加密數(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 用戶在小程序登錄后獲取的會話密鑰
     * @param $appid string 小程序的appid
     */
    public function WXBizDataCrypt( $appid, $sessionKey)
    {
        $this->sessionKey = $sessionKey;
        $this->appid = $appid;

    }


    /**
     * 檢驗數(shù)據(jù)的真實性,并且獲取解密后的明文.
     * @param $encryptedData string 加密的用戶數(shù)據(jù)
     * @param $iv string 與用戶數(shù)據(jù)一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0,失敗返回對應(yīng)的錯誤碼
     */
    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小程序端請求的時候用encodeURIComponent函數(shù)進行urlencode就好了(空格其實是符號:+ ?)

2017年4月9日 18:03