之前在接入微信公衆号相關的接口,對微信消息加解密操作時,下載下傳了官網上的php demo下來。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SM0ETM1MWNyM2N3I2NzMTNkdTN4kTOjFDM3gDZ2Q2N28CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
image.png
沒想到的是,官網的php代碼居然使用着php7廢棄的函數
Mcrypt,這就導緻了使用了php7.2及以上的版本程式上報錯。
image.png
然後就使用了open_ssl替代解決方案。以下是更新後的pkcs7Encoder.php檔案代碼
32) {
$pad = 0;
}
return substr($text, 0, (strlen($text) - $pad));
}
}
class Prpcrypt
{
public $key;
function __construct($k)
{
$this->key = base64_decode($k . "=");
}
public function encrypt($text, $appid)
{
try {
//獲得16位随機字元串,填充到明文之前
$random = $this->getRandomStr();
$text = $random . pack("N", strlen($text)) . $text . $appid;
$iv = substr($this->key, 0, 16);
//使用自定義的填充方式對明文進行補位填充
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
$encrypted = openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $iv);
return array(ErrorCode::$OK, base64_encode($encrypted));
} catch (Exception $e) {
//print $e;
return array(ErrorCode::$EncryptAESError, null);
}
}
public function decrypt($encrypted, $appid)
{
try {
$iv = substr($this->key, 0, 16);
//使用BASE64對需要解密的字元串進行解碼
$decrypted = openssl_decrypt(base64_decode($encrypted), 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $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);
}
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;
}
}
?>
方法步驟
1、居然是php的加密擴充,自然是先安裝openssl擴充,不過一般都有安裝(指令php -m可檢視)
image.png
2、檢視php官網開發文檔openssl,看看各個參數的含義與使用方法。當然上面是已經寫好的且驗證通過的代碼,可拿來即用。
image.png