KeyManager.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: stanley-king
  5. * Date: 2018/12/12
  6. * Time: 11:14 AM
  7. */
  8. namespace openapi;
  9. class KeyManager
  10. {
  11. static private $stInstance = null;
  12. private $mPaths = [];
  13. private $mKeys = [];
  14. const JYC_APPID = "JYC_CHANNEL";
  15. const DHKJ_APPID = "DHKJ_CHANNEL";
  16. private function __construct()
  17. {
  18. $this->mPaths = [];
  19. $this->mPaths[self::JYC_APPID] = BASE_ROOT_PATH . '/helper/openapi/keys/jyc_pub.pem';
  20. $this->mPaths[self::DHKJ_APPID] = BASE_ROOT_PATH . '/helper/openapi/keys/dhkj_pub.pem';
  21. }
  22. static public function instance()
  23. {
  24. if(self::$stInstance == null) {
  25. self::$stInstance = new KeyManager();
  26. }
  27. return self::$stInstance;
  28. }
  29. private function pub_key($appid)
  30. {
  31. if(empty($appid)) return false;
  32. if(!array_key_exists($appid,$this->mKeys))
  33. {
  34. if(!array_key_exists($appid,$this->mPaths))
  35. {
  36. return false;
  37. }
  38. else {
  39. $key = file_get_contents($this->mPaths[$appid]);
  40. $pub = openssl_get_publickey($key);
  41. if($pub === false) return false;
  42. $this->mKeys[$appid] = $pub;
  43. }
  44. }
  45. return $this->mKeys[$appid];
  46. }
  47. public function verify($appid,$body,$signed)
  48. {
  49. $pub = $this->pub_key($appid);
  50. if($pub === false) return false;
  51. return openssl_verify($body, $signed, $pub) === 1;
  52. }
  53. }