Files
kiri-wchat/common/Decode.php
T

118 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2019-11-11 18:14:47 +08:00
<?php
2020-03-05 12:41:49 +08:00
namespace wchat\common;
2019-11-11 18:14:47 +08:00
class Decode
{
2022-09-09 16:42:55 +08:00
private string $sessionKey;
private string $iv;
private string $encryptedData;
private string $appId;
2019-11-11 18:14:47 +08:00
2022-09-09 16:42:55 +08:00
private int $OK = 0;
private int $IllegalAesKey = -41001;
private int $IllegalIv = -41002;
private int $IllegalBuffer = -41003;
private int $DecodeBase64Error = -41004;
2019-11-11 18:14:47 +08:00
/**
2022-09-09 16:42:55 +08:00
* @return string
2019-11-11 18:14:47 +08:00
*/
2022-09-09 16:42:55 +08:00
public function getSessionKey(): string
{
return $this->sessionKey;
}
/**
* @param string $sessionKey
*/
public function setSessionKey(string $sessionKey): void
2019-11-11 18:14:47 +08:00
{
$this->sessionKey = $sessionKey;
}
/**
2022-09-09 16:42:55 +08:00
* @return string
*/
public function getIv(): string
{
return $this->iv;
}
/**
* @param string $iv
2019-11-11 18:14:47 +08:00
*/
2022-09-09 16:42:55 +08:00
public function setIv(string $iv): void
2019-11-11 18:14:47 +08:00
{
$this->iv = $iv;
}
/**
2022-09-09 16:42:55 +08:00
* @return string
*/
public function getEncryptedData(): string
{
return $this->encryptedData;
}
/**
* @param string $encryptedData
2019-11-11 18:14:47 +08:00
*/
2022-09-09 16:42:55 +08:00
public function setEncryptedData(string $encryptedData): void
2019-11-11 18:14:47 +08:00
{
$this->encryptedData = $encryptedData;
}
/**
2022-09-09 16:42:55 +08:00
* @return string
*/
public function getAppId(): string
{
return $this->appId;
}
/**
* @param string $appId
2019-11-11 18:14:47 +08:00
*/
2022-09-09 16:42:55 +08:00
public function setAppId(string $appId): void
2019-11-11 18:14:47 +08:00
{
$this->appId = $appId;
}
/**
* @param $asArray
* @return array|mixed
* @throws \Exception
*/
2022-09-09 16:42:55 +08:00
public function decode($asArray): object|array
2019-11-11 18:14:47 +08:00
{
if (strlen($this->sessionKey) != 24) {
throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey);
}
$aesKey = base64_decode($this->sessionKey);
if (strlen($this->iv) != 24) {
throw new \Exception('base64解密失败', $this->IllegalIv);
}
$aesIV = base64_decode($this->iv);
$aesCipher = base64_decode($this->encryptedData);
$result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, OPENSSL_RAW_DATA, $aesIV);
if ($result === false) {
throw new \Exception('aes 解密失败', $this->IllegalBuffer);
}
$dataObj = json_decode($result);
if ($dataObj->watermark->appid != $this->appId) {
throw new \Exception('aes 解密失败', $this->IllegalBuffer);
}
2022-09-09 16:42:55 +08:00
return $asArray ? get_object_vars($dataObj) : $dataObj;
2019-11-11 18:14:47 +08:00
}
}