key = base64_decode($k . "="); } public function encrypt($text, $appid) { try { $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); return array(ErrorCode::$OK, base64_encode($encrypted)); } catch (\Exception $e) { return array(ErrorCode::$EncryptAESError, null); } } public function decrypt($encrypted, $appid) { try { $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 { $pkc_encoder = new PKCS7Encoder; $result = $pkc_encoder->decode($decrypted); 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) { return array(ErrorCode::$IllegalBuffer, null); } if ($from_appid != $appid) return array(ErrorCode::$ValidateAppidError, null); return array(0, $xml_content); } 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; } }