RsaHelper.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace addons\QiDingDong\common\helper;
  3. use addons\QiDingDong\common\service\SettingService;
  4. class RsaHelper
  5. {
  6. protected static $public_key = ''; //公钥
  7. /**
  8. * 根据公钥路径获取公钥信息
  9. *
  10. * @param string $path
  11. */
  12. public static function publicKey(string $path = '')
  13. {
  14. self::$public_key = openssl_pkey_get_public(file_get_contents($path));
  15. }
  16. /**
  17. * 公钥加密
  18. *
  19. * @param string|array $data
  20. * @return boolean|string
  21. */
  22. public static function publicEncrypt($data)
  23. {
  24. if (empty($data)) {
  25. return $data;
  26. }
  27. if (empty(self::$public_key)) {
  28. return false;
  29. }
  30. $encryptData = '';
  31. if (openssl_public_encrypt($data, $encryptData, self::$public_key)) {
  32. return base64_encode($encryptData);
  33. } else {
  34. return false;
  35. }
  36. }
  37. /**
  38. * 公钥解密
  39. *
  40. * @param string $data
  41. * @return boolean|string
  42. */
  43. public static function publicDecrypt(string $data)
  44. {
  45. if (empty($data)) {
  46. return $data;
  47. }
  48. if (empty(self::$public_key)) {
  49. return false;
  50. }
  51. $data = base64_decode($data);
  52. $decryptData = '';
  53. if (openssl_public_decrypt($data, $decryptData, self::$public_key)) {
  54. return $decryptData;
  55. } else {
  56. return false;
  57. }
  58. }
  59. public static function setPublicKey(int $mall_id)
  60. {
  61. $mall_id = SettingService::getMasterMall();
  62. $public_key = dirname(\Yii::$app->basePath) .'/'. ((new SettingService())->get($mall_id)['public_key'] ?? '');
  63. if (empty($public_key)) throw new \Exception("请上传Public Key");
  64. RsaHelper::publicKey($public_key);
  65. }
  66. }