| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace addons\QiDingDong\common\helper;
- use addons\QiDingDong\common\service\SettingService;
- class RsaHelper
- {
- protected static $public_key = ''; //公钥
- /**
- * 根据公钥路径获取公钥信息
- *
- * @param string $path
- */
- public static function publicKey(string $path = '')
- {
- self::$public_key = openssl_pkey_get_public(file_get_contents($path));
- }
- /**
- * 公钥加密
- *
- * @param string|array $data
- * @return boolean|string
- */
- public static function publicEncrypt($data)
- {
- if (empty($data)) {
- return $data;
- }
- if (empty(self::$public_key)) {
- return false;
- }
- $encryptData = '';
- if (openssl_public_encrypt($data, $encryptData, self::$public_key)) {
- return base64_encode($encryptData);
- } else {
- return false;
- }
- }
- /**
- * 公钥解密
- *
- * @param string $data
- * @return boolean|string
- */
- public static function publicDecrypt(string $data)
- {
- if (empty($data)) {
- return $data;
- }
- if (empty(self::$public_key)) {
- return false;
- }
- $data = base64_decode($data);
- $decryptData = '';
- if (openssl_public_decrypt($data, $decryptData, self::$public_key)) {
- return $decryptData;
- } else {
- return false;
- }
- }
- public static function setPublicKey(int $mall_id)
- {
- $mall_id = SettingService::getMasterMall();
- $public_key = dirname(\Yii::$app->basePath) .'/'. ((new SettingService())->get($mall_id)['public_key'] ?? '');
- if (empty($public_key)) throw new \Exception("请上传Public Key");
- RsaHelper::publicKey($public_key);
- }
- }
|