# PHP7.2使用openssl替换mcrypt

[http://blog.wpjam.com/m/php-7-1-openssl/](http://blog.wpjam.com/m/php-7-1-openssl/)

PHP7.2已经废弃了mcrypt扩展（ [http://php.net/manual/en/intro.mcrypt.php](http://php.net/manual/en/intro.mcrypt.php) ），但是微信的加解密函数使用的是mcrypt（Prpcrypt class），需要使用openssl进行替换。

```
/**
 * 对明文进行加密
 * @param string $text 需要加密的明文
 * @return string 加密后的密文
 */
public function encrypt($text, $corpid)
{
    try {
        $iv = substr($this->key, 0, 16);
        $encrypted = openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_ZERO_PADDING, $iv);
        return array(ErrorCode::$OK, $encrypted);
    } catch (Exception $e) {
        print $e;
        return array(ErrorCode::$EncryptAESError, null);
    }
}

/**
 * 对密文进行解密
 * @param string $encrypted 需要解密的密文
 * @return string 解密得到的明文
 */
public function decrypt($encrypted, $corpid)
{
    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 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_corpid = substr($content, $xml_len + 4);
    } catch (Exception $e) {
        print $e;
        return array(ErrorCode::$IllegalBuffer, null);
    }
    if ($from_corpid != $corpid){
        return array(ErrorCode::$ValidateCorpidError, null);
    }
    return array(0, $xml_content);
}
```
