微信小程式與 PHP 7.1 的一點小坑

蝸牛發表於2017-05-25

前段時間寫小程式介面,涉及到需要獲取微信使用者的資料。微信小程式提供了加密資料解密的演算法。官方提供了多種程式語言。
file

只是天有不測風雲,我當時使用的環境是 PHP 7.1 。加密函式 mcrypt_module_open() 因為過時而被廢棄。

微信小程式官方提供的示例程式碼,PHP 資料夾中,pkcs7Encoder.php 的如下內容:

/**
 * 對密文進行解密
 * 
 * @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);
    } 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);
}

進行如下替換,即可解決。

/**
* 對密文進行解密
* 
* @param string $aesCipher 需要解密的密文
* @param string $aesIV 解密的初始向量
* @return string 解密得到的明文
*/
public function decrypt($aesCipher, $aesIV)
{
    try {
        //解密
        $decrypted = openssl_decrypt($aesCipher, 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $aesIV);
    } catch (\Exception $e) {
        return array($this->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);
}

簡單點說就是將第一段 try {} catch ($e) {} 中的 try {} 進行替換,換成可支援的 openssl_decrypt() 即可解決。

參考:PHP7.1 加密函式 mcrypt_module_open() 替換方案

Study hard and make progress every day. Study hard and make progress every day.

相關文章