PHP7怎么加解密AES
微信小程序开发过程中,开启了消息推送,并且消息是完全模式,需要自己加解密,服务器语言使用PHP,但是问题来了,官方给的代码中的消息加解密方法在PHP7中并不能使用,mcrypt_module_open
等相关方法不支持了,请问在PHP7中如何加解密消息内容。下面是微信官方给的PHP5的加密方法,在php7中出现问题,求大佬解答
微信小程序开发过程中,开启了消息推送,并且消息是完全模式,需要自己加解密,服务器语言使用PHP,但是问题来了,官方给的代码中的消息加解密方法在PHP7中并不能使用,mcrypt_module_open
等相关方法不支持了,请问在PHP7中如何加解密消息内容。下面是微信官方给的PHP5的加密方法,在php7中出现问题,求大佬解答
请问官方提供的demo在哪儿下载? 我在这里下载的没有php语言的,只有c++的demohttps://developers.weixin.qq.com/miniprogram/dev/api/signature.html#wxchecksessionobject
折腾半天,终于解决,将微信官方提供的pkcs7Encoder.php中的两个方法修改如下即可
/** * 对明文进行加密 * [@param](/user/param) string $text 需要加密的明文 * [@return](/user/return) string 加密后的密文 */ public function encrypt($text, $appid) { try { //获得16位随机字符串,填充到明文之前 $random = $this->getRandomStr();//"aaaabbbbccccdddd"; $text = $random . pack("N", strlen($text)) . $text . $appid; $iv = substr($this->key, 0, 16); $pkc_encoder = new Pkcsencoder(); $text = $pkc_encoder->encode($text); $encrypted = openssl_encrypt($text,'AES-256-CBC',substr($this->key, 0, 32),OPENSSL_ZERO_PADDING,$iv); return array(ErrorCode::$OK, $encrypted); } catch (Exception $e) { //print $e; return array(Errorcode::$EncryptAESError, null); } } /** * 对密文进行解密 * [@param](/user/param) string $encrypted 需要解密的密文 * [@return](/user/return) string 解密得到的明文 */ public function decrypt($encrypted, $appid) { try { $iv = substr($this->key, 0, 16); $decrypted = openssl_decrypt($encrypted,'AES-256-CBC',substr($this->key, 0, 32),OPENSSL_ZERO_PADDING,$iv); } catch (Exception $e) { return array(Errorcode::$DecryptAESError, null); } try { //去除补位字符 $pkc_encoder = new Pkcsencoder(); $result = $pkc_encoder->decode($decrypted); //去除16位随机字符串,网络字节序和AppId if (strlen($result) < 16) return array('出错啦'); $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, $from_appid); } |