Decrypt.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Http\Controllers\Miniprogram;
  3. class Decrypt
  4. {
  5. private $appid;
  6. private $sessionKey;
  7. public function __construct($appid, $sessionKey)
  8. {
  9. $this->appid = $appid;
  10. $this->sessionKey = $sessionKey;
  11. }
  12. /**
  13. * 对解密后的明文进行补位删除
  14. * @param text decrypted 解密后的明文
  15. * @return void 删除填充补位后的明文
  16. */
  17. public function decode($text)
  18. {
  19. $pad = ord(substr($text, -1));
  20. if ($pad < 1 || $pad > 32) {
  21. $pad = 0;
  22. }
  23. return substr($text, 0, (strlen($text) - $pad));
  24. }
  25. /**
  26. * 对密文进行解密
  27. * @param $aesKey
  28. * @param string $aesCipher 需要解密的密文
  29. * @param string $aesIV 解密的初始向量
  30. * @return array 解密得到的明文
  31. */
  32. public function decrypt($aesKey, $aesCipher, $aesIV)
  33. {
  34. try {
  35. //解密
  36. $decrypted = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, OPENSSL_RAW_DATA, $aesIV);
  37. } catch (\Exception $e) {
  38. return array($this->IllegalBuffer, null);
  39. }
  40. try {
  41. //去除补位字符
  42. $result = $this->decode($decrypted);
  43. } catch (Exception $e) {
  44. return array(41003, null);
  45. }
  46. return array(0, $result);
  47. }
  48. /**
  49. * 检验数据的真实性,并且获取解密后的明文.
  50. * @param string $encryptedData
  51. * @param $iv string 与用户数据一同返回的初始向量
  52. * @param $data string 解密后的原文
  53. * @return void 成功0,失败返回对应的错误码
  54. */
  55. public function decryptData(string $encryptedData, string $iv, &$data)
  56. {
  57. if (strlen($this->sessionKey) != 24) {
  58. return 41001;
  59. }
  60. $aesKey = base64_decode($this->sessionKey);
  61. if (strlen($iv) != 24) {
  62. return 41002;
  63. }
  64. $aesIV = base64_decode($iv);
  65. $aesCipher = base64_decode($encryptedData);
  66. $result = $this->decrypt($aesKey, $aesCipher, $aesIV);
  67. if ($result[0] != 0) {
  68. return $result[0];
  69. }
  70. $dataObj = json_decode($result[1]);
  71. if ($dataObj == null) {
  72. return 41004;
  73. }
  74. if ($dataObj->watermark->appid != $this->appid) {
  75. return 41003;
  76. }
  77. $data = $result[1];
  78. return 0;
  79. }
  80. }