SignUtil.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace app\extra\douyin;
  3. class SignUtil
  4. {
  5. /*
  6. * appid/client_key对应的client_secret TODO 这里换成服务商的appsecret
  7. */
  8. private static $secret = "12345678901234566543210987654321";
  9. private static $key;
  10. private static $iv;
  11. public static function init($secret) {
  12. self::$secret = $secret;
  13. self::$key = self::parseSecret(self::$secret);
  14. self::$iv = substr(self::$key, 16);
  15. }
  16. /**
  17. * AES解密
  18. * @param string $data base64后的密文
  19. * @return string 明文
  20. */
  21. public static function decryptAES($data) {
  22. try {
  23. $encrypted = self::decode($data); // 先用base64解密
  24. $decrypted = openssl_decrypt(
  25. $encrypted,
  26. 'AES-256-CBC',
  27. self::$key,
  28. OPENSSL_RAW_DATA,
  29. self::$iv
  30. );
  31. return $decrypted;
  32. } catch (\Exception $e) {
  33. error_log($e->getMessage());
  34. return null;
  35. }
  36. }
  37. /**
  38. * base64编码
  39. */
  40. public static function encode($data) {
  41. return base64_encode($data);
  42. }
  43. /**
  44. * base64解码
  45. */
  46. public static function decode($data) {
  47. return base64_decode($data);
  48. }
  49. private static function parseSecret($secret) {
  50. $secret = self::fillSecret($secret);
  51. $secret = self::cutSecret($secret);
  52. return $secret;
  53. }
  54. private static function cutSecret($secret) {
  55. if (strlen($secret) <= 32) {
  56. return $secret;
  57. }
  58. $rightCnt = (int)((strlen($secret) - 32) / 2);
  59. $leftCnt = strlen($secret) - 32 - $rightCnt;
  60. return substr($secret, $leftCnt, 32);
  61. }
  62. private static function fillSecret($secret) {
  63. if (strlen($secret) >= 32) {
  64. return $secret;
  65. }
  66. $rightCnt = (int)((32 - strlen($secret)) / 2);
  67. $leftCnt = 32 - strlen($secret) - $rightCnt;
  68. $sb = str_repeat('#', $leftCnt);
  69. $sb .= $secret;
  70. $sb .= str_repeat('#', $rightCnt);
  71. return $sb;
  72. }
  73. }