微信小程序加密數據(encryptedData)解密中的PHP代碼,php7.1報錯


問題描述

最近在開發微信小程序涉及到加密數據(encryptedData)的解密,用的是PHP代碼,在運行后報錯mcrypt_module_ xxx is deprecated,提示方法已過時了


經研究得知,是php7.1版本引起的,可以使用openssl方法代替解密.

首先要知道微信方使用的是AES-128-CBC加密的:

​​圖片描述

所以我們采用openssl也應該對應:

/**
     * 對密文進行解密
     * @param string $aesCipher 需要解密的密文
     * @param string $aesIV 解密的初始向量
     * @return string 解密得到的明文
     */
    public function decrypt( $aesCipher, $aesIV )
    {
 
        try {
            
//             $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
            
//             mcrypt_generic_init($module, $this->key, $aesIV);
 
//             //解密
//             $decrypted = mdecrypt_generic($module, $aesCipher);
//             mcrypt_generic_deinit($module);
//             mcrypt_module_close($module);
            
            $decrypted = openssl_decrypt($aesCipher, "aes-128-cbc", $this->key, OPENSSL_RAW_DATA ,$aesIV);
            
        } catch (Exception $e) {
            return array(ErrorCode::$IllegalBuffer, null);
        }
 
 
        try {
            //去除補位字符
            $pkc_encoder = new PKCS7Encoder;
            $result = $pkc_encoder->decode($decrypted);
 
        } catch (Exception $e) {
            //print $e;
            return array(ErrorCode::$IllegalBuffer, null);
        }
        return array(0, $result);
    }
    
    

特別注意

很多解密失敗是因為在使用openssl_decrypt解密的時候又使用了一次base_decode,實際上微信demo在調用這個方法之前就已經把所有參數都base_decode了一次:

圖片描述

by KingFer


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM