php7.2+使用openssl替換mcrypt加解密微信消息

文檔: 微信消息加解密官方文檔

在文檔中的SDK所使用的mcrypt 擴展從PHP 7.2起它將被從核心代碼中移除並且移到PECL中。PHP手冊在7.1遷移頁面給出了替代方案,就是用OpenSSL取代MCrypt.

說明:二、抽離代碼,直接對微信消息進行解密”中只是抽離了對消息加解密的部分,抽離的代碼只是爲了研究微信消息的加密算法,實際場景還需加上簽名的驗證,實際簽名驗證的代碼請自行查看微信提供的SDK

一、快速替換

替換SDK中 pkcs7Encoder.php的內容如下:
替換完就可以繼續使用SDK了,下面的內容只是進一步的擴展,到這一步就完成對SDK的更改了。

<?php

include_once "errorCode.php";

/**
 * PKCS7Encoder class
 *
 * 提供基於PKCS7算法的加解密接口.
 */
class PKCS7Encoder
{
	public static $block_size = 32;

	/**
	 * 對需要加密的明文進行填充補位
	 * @param $text 需要進行填充補位操作的明文
	 * @return 補齊明文字符串
	 */
	function encode($text)
	{
		$block_size = PKCS7Encoder::$block_size;
		$text_length = strlen($text);
		//計算需要填充的位數
		$amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
		if ($amount_to_pad == 0) {
			$amount_to_pad = PKCS7Encoder::block_size;
		}
		//獲得補位所用的字符
		$pad_chr = chr($amount_to_pad);
		$tmp = "";
		for ($index = 0; $index < $amount_to_pad; $index++) {
			$tmp .= $pad_chr;
		}
		return $text . $tmp;
	}

	/**
	 * 對解密後的明文進行補位刪除
	 * @param decrypted 解密後的明文
	 * @return 刪除填充補位後的明文
	 */
	function decode($text)
	{

		$pad = ord(substr($text, -1));
		if ($pad < 1 || $pad > 32) {
			$pad = 0;
		}
		return substr($text, 0, (strlen($text) - $pad));
	}

}

/**
 * Prpcrypt class
 *
 * 提供接收和推送給公衆平臺消息的加解密接口.
 */
class Prpcrypt
{
	public $key;

	function __construct($k)
	{
		$this->key = base64_decode($k . "=");
	}

	/**
	 * 微信舊版本: 對明文進行加密
	 * @param string $text 需要加密的明文
	 * @return string 加密後的密文
	 */
//	public function encrypt($text, $appid)
//	{
//
//		try {
//			//獲得16位隨機字符串,填充到明文之前
//			$random = $this->getRandomStr();
//			$text = $random . pack("N", strlen($text)) . $text . $appid;
//			// 網絡字節序
//			$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
//			$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
//			$iv = substr($this->key, 0, 16);
//			//使用自定義的填充方式對明文進行補位填充
//			$pkc_encoder = new PKCS7Encoder;
//			$text = $pkc_encoder->encode($text);
//			mcrypt_generic_init($module, $this->key, $iv);
//			//加密
//			$encrypted = mcrypt_generic($module, $text);
//			mcrypt_generic_deinit($module);
//			mcrypt_module_close($module);
//
//			//print(base64_encode($encrypted));
//			//使用BASE64對加密後的字符串進行編碼
//			return array(ErrorCode::$OK, base64_encode($encrypted));
//		} catch (Exception $e) {
//			//print $e;
//			return array(ErrorCode::$EncryptAESError, null);
//		}
//
//	}

    public function encrypt($text, $appid)
    {

        try {
            $key = $this->key;
            $random = $this->getRandomStr();
            $text = $random.pack('N', strlen($text)).$text.$appid;
            $padAmount = 32 - (strlen($text) % 32);
            $padAmount = 0 !== $padAmount ? $padAmount : 32;
            $padChr = chr($padAmount);
            $tmp = '';
            for ($index = 0; $index < $padAmount; ++$index) {
                $tmp .= $padChr;
            }
            $text = $text.$tmp;
            $iv = substr($key, 0, 16);
            $encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
            return array(ErrorCode::$OK, base64_encode($encrypted));
        } catch (Exception $e) {
            return array(ErrorCode::$EncryptAESError, null);
        }

    }


	/**
	 * 對密文進行解密
	 * @param string $encrypted 需要解密的密文
	 * @return string 解密得到的明文
	 */
	public function decrypt($encrypted, $appid)
	{
//
//		try {
//			//使用BASE64對需要解密的字符串進行解碼
//			$ciphertext_dec = base64_decode($encrypted);
//			$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
//			$iv = substr($this->key, 0, 16);
//			mcrypt_generic_init($module, $this->key, $iv);
//
//			//解密
//			$decrypted = mdecrypt_generic($module, $ciphertext_dec);
//			mcrypt_generic_deinit($module);
//			mcrypt_module_close($module);
//		} catch (Exception $e) {
//			return array(ErrorCode::$DecryptAESError, null);
//		}

        try {
            $key = $this->key;
            $ciphertext = base64_decode($encrypted, true);
            $iv = substr($key, 0, 16);

            $decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
        } catch (Exception $e) {
            return array(ErrorCode::$DecryptAESError, null);
        }
		try {
			//去除補位字符
			$pkc_encoder = new PKCS7Encoder;
			$result = $pkc_encoder->decode($decrypted);
			//去除16位隨機字符串,網絡字節序和AppId
			if (strlen($result) < 16)
				return "";
			$content = substr($result, 16, strlen($result));
			$len_list = unpack("N", substr($content, 0, 4));
			$xml_len = $len_list[1];
			$xml_content = substr($content, 4, $xml_len);
			$from_appid = substr($content, $xml_len + 4);
		} catch (Exception $e) {
			//print $e;
			return array(ErrorCode::$IllegalBuffer, null);
		}
		if ($from_appid != $appid)
			return array(ErrorCode::$ValidateAppidError, null);
        return array(0, $xml_content);

	}


	/**
	 * 隨機生成16位字符串
	 * @return string 生成的字符串
	 */
	function getRandomStr()
	{

		$str = "";
		$str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
		$max = strlen($str_pol) - 1;
		for ($i = 0; $i < 16; $i++) {
			$str .= $str_pol[mt_rand(0, $max)];
		}
		return $str;
	}



}

?>

二、抽離代碼,直接對微信消息進行解密(只需要引入這個類文件即可完成解密)



class WxEncode{

    //微信解密的密鑰(AesKey)
    private $key = 'MzVkc2N2ZmRHeDlzZktHRU11RWdmZEd4OXNmS0dFTXVFZw==';
    //一個塊有多少位
    private $blockSize = 32;

    function __construct()
    {
        $this->key = base64_decode($this->key . "=");
    }
    function encrypt($text,$appid)
    {
        try {
            $key = $this->key;
            $random = $this->getRandomStr();
            $text = $random . pack('N', strlen($text)) . $text . $appid;
            $text = $this->encode($text);
            $iv = substr($key, 0, 16);
            $encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
            return base64_encode($encrypted);
        } catch (Exception $e) {
            return array(ErrorCode::$EncryptAESError, null);
        }
    }

    /**
     * 隨機生成16位字符串
     * @return string 生成的字符串
     */
    function getRandomStr()
    {

        $str = "";
        $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($str_pol) - 1;
        for ($i = 0; $i < 16; $i++) {
            $str .= $str_pol[mt_rand(0, $max)];
        }
        return $str;
    }

    function decrypt($encrypted,$appid)
    {
        try {
            $key = $this->key;
            $ciphertext = base64_decode($encrypted, true);
            $iv = substr($key, 0, 16);

            $decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
        } catch (Exception $e) {
            return array(ErrorCode::$DecryptAESError, null);
        }
        try {
            //去除補位字符
            $result = $this->decode($decrypted);
            //去除16位隨機字符串,網絡字節序和AppId
            if (strlen($result) < 16)
                return "";
            $content = substr($result, 16, strlen($result));
            $len_list = unpack("N", substr($content, 0, 4));
            $xml_len = $len_list[1];
            $xml_content = substr($content, 4, $xml_len);
            $from_appid = substr($content, $xml_len + 4);
        } catch (Exception $e) {
            //print $e;
            exit( $e->getMessage());
        }
        if ($from_appid != $appid)
            exit( 'appid錯誤');
        return $xml_content;

    }



    /**
     * 對需要加密的明文進行填充補位
     * @param $text  /需要進行填充補位操作的明文
     * @return
     */
    function encode($text)
    {
        $blockSize = $this->blockSize;
        $text_length = strlen($text);
        //計算需要填充的位數
        $amount_to_pad = $blockSize - ($text_length % $blockSize);
        if ($amount_to_pad == 0) {
            $amount_to_pad = $blockSize;
        }
        //獲得補位所用的字符
        $pad_chr = chr($amount_to_pad);
        $tmp = "";
        for ($index = 0; $index < $amount_to_pad; $index++) {
            $tmp .= $pad_chr;
        }
        return $text . $tmp;
    }

    /**
     * 對解密後的明文進行補位刪除
     * @param /decrypted 解密後的明文
     * @return /刪除填充補位後的明文
     */
    function decode($text)
    {

        $pad = ord(substr($text, -1));
        if ($pad < 1 || $pad > $this->blockSize;) {
            $pad = 0;
        }
        return substr($text, 0, (strlen($text) - $pad));
    }
}


/**
 *  抽離成功,進行測試
 */


//appId
$appid = 'wxf1dea3322522114329';
$wxEncode = new WxEncode();


//步驟1:模擬微信的加密數據
    //假設這是微信推送到服務器的消息,但此時還是明文模式(我微信小程序後臺設置的是json格式)
$baseData = '{"ToUserName":"gh_2fcc195deca8","FromUserName":"oYBz64smtrDVSB0Zc-Ci3cCGoI","CreateTime":"1570781174","MsgType":"text","Content":"我是用戶發送的消息","MsgId":"22488181173754573"}';
    //模擬微信對要發送數據進行加密
$encodeData = $wxEncode->encrypt($baseData,$appid);
echo  '模擬完成,加密數據如下:';
echo  $encodeData;
echo '<hr/>';


//步驟2:模擬微信發送的數據
$wxSendMsg = json_encode(['ToUserName'=>'gh_2fcc195deca8','Encrypt'=>$encodeData],true);


//步驟3:解密微信推送的加密數據(需要實現的實際業務模塊)
$sendData = json_decode($wxSendMsg,true);

 //解密加密的數據
$decodeData = $wxEncode->decrypt($sendData['Encrypt'],$appid);
echo  '這是解密後的數據:'.$decodeData;

三、微信消息加解密的實現細節

對明文msg加密的過程如下:
msg_encrypt = Base64_Encode( AES_Encrypt[random(16B) + msg_len(4B) + msg + $CorpID] )
AES加密的buf由16個字節的隨機字符串、4個字節的msg長度、明文msg和CorpID組成。其中msg_len爲msg的字節數,網絡字節序;CorpID爲企業號的CorpID。經AESKey加密後,再進行Base64編碼,即獲得密文msg_encrypt。

對應於加密方案,解密方案如下:
1.對密文BASE64解碼:aes_msg=Base64_Decode(msg_encrypt)
2.使用AESKey做AES解密:rand_msg=AES_Decrypt(aes_msg)
3.驗證解密後CorpID、msg_len
4.去掉rand_msg頭部的16個隨機字節,4個字節的msg_len,和尾部的CorpID即爲最終的消息體原文msg

四、加密前的補位要小心

encode補位的代碼要格外注意

   /**
     * 對需要加密的明文進行填充補位
     * @param $text  /需要進行填充補位操作的明文
     * @return
     */
    function encode($text)
    {
        $blockSize = $this->blockSize;
        $text_length = strlen($text);
        //計算需要填充的位數
        $amount_to_pad = $blockSize - ($text_length % $blockSize);
        if ($amount_to_pad == 0) {
            $amount_to_pad = $blockSize;
        }
        //獲得補位所用的字符
        $pad_chr = chr($amount_to_pad);
        $tmp = "";
        for ($index = 0; $index < $amount_to_pad; $index++) {
            $tmp .= $pad_chr;
        }
        return $text . $tmp;
    }

如果字符不能被一開始設置的塊(定義的$blockSize屬性)分隔完就需要對原文進行補位,補滿 $blockSize對應的數量,就是代碼中的

$amount_to_pad = $blockSize - ($text_length % $blockSize);
        if ($amount_to_pad == 0) {
            $amount_to_pad = $blockSize;
        }

如何填充呢?這裏有個妙用:$pad_chr = chr($amount_to_pad); chr返回一個ASCII對應的字符,然後使用返回的字符去填充,注意,現在這裏chr的參數是傳入的需要填充的數量,一個數字,然後刪除補位的時候(decode函數),通過ord函數獲取解密後的最後一個字符對應的ASCII表中的位置,而這個位置是chr一開始傳入的需要填充的數量,最後得到這個數量,去掉末尾對應的填充字符;
這樣的填充我們注意這段代碼

  if ($amount_to_pad == 0) {
            $amount_to_pad = $blockSize;
        }

如果剛好可以分隔完,我們也是填充了一個完整的$blockSize對應的長度,意味這最後解密出來的原文不管是否能被分隔完都必須取出最後一位字節對應的ASCII表中的位置,然後去除掉相應數量的補位符;問題也是在這裏,如果其他開發這不知道這一情況,他看到解密長度是正確的就不會再去刪除填充字節,就會導致當加密的數據剛好可以分隔完進行對稱加密時,不知情的其他開發者就會忽略最後一段的填充字符,導致原文最後多了一段填充字符。不過如果全是自己開發的就沒問題了,我們自己清楚原文結尾是100%拼入了填充字符的。如果是給其他開發者解密記得提醒別人原文結尾一定要去掉填位字節哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章