jiazx0107@163.com
2023-11-07 1ae45581a6024db5187c64621d01729e0d1dead5
提交网关功能
已修改11个文件
已添加5个文件
974 ■■■■ 文件已修改
src/main/java/com/fzzy/api/utils/RedisConst.java 10 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/GatewayRunner.java 4 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/GatewayTimerScheduled.java 67 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/api/GatewayRemoteService.java 19 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/entity/GatewayConf.java 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/hx2023/ScConstant.java 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/hx2023/data/CloudResp.java 44 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/hx2023/data/RespKey.java 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/hx2023/service/ApiInitService.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java 203 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/package-info.java 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/service/GatewayConfService.java 45 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/util/GatewayHttpUtil.java 69 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/util/GatewayRSAUtils.java 370 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/view/GatewayConf.view.xml 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/push/gb2022/HttpClientUtil.java 95 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/api/utils/RedisConst.java
@@ -17,11 +17,6 @@
    /**
     * è®¾å¤‡ç¼“å­˜
     */
    public static String KYE_GATE_DEVICE = "G_DEVICE";
    /**
     * è®¾å¤‡ç¼“å­˜
     */
    public static String KYE_GATE_TOKEN = "G_TOKEN";
@@ -31,6 +26,11 @@
    public static String KYE_CONF = "CONF";
    /**
     * æŽ¥å£é…ç½®-单个数据单个KEY
     */
    public static String KYE_CONF_GATEWAY = "CONF_GATEWAY";
    /**
     * æŽ¥å£é…ç½®-TOKEN
     */
    public static String KYE_TOKEN = "TOKEN";
src/main/java/com/fzzy/gateway/GatewayRunner.java
@@ -22,7 +22,9 @@
    @Override
    public void run(String... args) throws Exception {
        log.info("网关接口随系统启动------------");
        //执行初始化方案
        apiInitService.init();
    }
}
src/main/java/com/fzzy/gateway/GatewayTimerScheduled.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,67 @@
package com.fzzy.gateway;
import com.fzzy.api.data.ApiParam;
import com.fzzy.api.entity.ApiConfs;
import com.fzzy.api.service.*;
import com.fzzy.api.utils.ContextUtil;
import com.fzzy.api.utils.RedisUtil;
import com.fzzy.gateway.api.GatewayRemoteManager;
import com.fzzy.gateway.entity.GatewayConf;
import com.fzzy.gateway.service.GatewayConfService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
 * ç½‘关相关的定时器
 */
@Slf4j
@Component(GatewayTimerScheduled.BEAN_ID)
public class GatewayTimerScheduled {
    public static final String BEAN_ID = "gateway.timerScheduled";
    @Resource
    private GatewayConfService confService;
    @Resource
    private GatewayRemoteManager gatewayRemoteManager;
    /**
     * <p>
     * å›ºå®šæ—¶é—´ï¼šæ¯é—´éš”10分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void scheduled() {
        //网关的心跳执行
        doHeartbeat();
    }
    /**
     * æ‰§è¡Œç½‘关心跳
     */
    private void doHeartbeat() {
        //获取缓存中的网关信息
        List<GatewayConf> list = confService.getCacheConfList();
        if (null == list || list.isEmpty()) {
            log.warn("------系统为获取到网关配置信息,不执行定时心跳-----");
            return;
        }
        for (GatewayConf conf : list) {
            gatewayRemoteManager.getRemoteService(conf.getPushProtocol()).heartbeat(conf);
        }
    }
}
src/main/java/com/fzzy/gateway/api/GatewayRemoteService.java
@@ -1,6 +1,5 @@
package com.fzzy.gateway.api;
import com.fzzy.gateway.data.GatewayResponse;
import com.fzzy.gateway.entity.GatewayConf;
@@ -15,11 +14,21 @@
    /**
     * æ•°æ®æŽ¨é€
     *
     * @param conf å‚æ•°
     * ç½‘关设备初始化
     * @param gatewayConf
     */
    public GatewayResponse authorize(GatewayConf conf);
    void init(GatewayConf gatewayConf);
    /**
     * ç½‘关设备心跳维持
     * @param gatewayConf
     */
    void heartbeat(GatewayConf gatewayConf);
    /**
     * ç½‘关设备信息上报
     * @param gatewayConf
     */
    void pushInfo(GatewayConf gatewayConf);
}
src/main/java/com/fzzy/gateway/entity/GatewayConf.java
@@ -72,6 +72,14 @@
    @Column(name = "publicKey", length = 200)
    private String publicKey;
    @PropertyDef(label = "省平台加密私钥")
    @Column(name = "privateKey", length = 200)
    private String privateKey;
    @PropertyDef(label = "省平台鉴权口令")
    @Column(name = "accessToken", length = 200)
    private String accessToken;
    @PropertyDef(label = "省平台接口地址")
    @Column(name = "apiUrl", length = 200)
    private String apiUrl;
src/main/java/com/fzzy/gateway/hx2023/ScConstant.java
@@ -16,4 +16,7 @@
    public static String getMessageId() {
        return System.currentTimeMillis() + RandomUtils.nextInt(1000) + "";
    }
    public static int CODE_200 = 200;
}
src/main/java/com/fzzy/gateway/hx2023/data/CloudResp.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,44 @@
package com.fzzy.gateway.hx2023.data;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import java.io.Serializable;
/**
 * çœå¹³å°æŽ¥å£è¿”回封装
 */
@Data
public class CloudResp implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = -6714158228489303453L;
    /**
     * 200 è¡¨ç¤ºæˆ
     */
    public int code;
    /**
     * è¯´æ˜Ž
     */
    public String message;
    /**
     * status
     */
    public int status;
    public int timestamp;
    public JSONObject data;
    public CloudResp() {
    }
    public CloudResp(int code, String message) {
        this.code = code;
        this.message = message;
    }
}
src/main/java/com/fzzy/gateway/hx2023/data/RespKey.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,18 @@
package com.fzzy.gateway.hx2023.data;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
@Data
public class RespKey {
    private int code;
    private String message;
    private JSONObject result;
    private int status;
    private String timestamp;
}
src/main/java/com/fzzy/gateway/hx2023/service/ApiInitService.java
@@ -34,7 +34,7 @@
        GatewayRemoteService gatewayRemoteService;
        for (GatewayConf gatewayConf : list) {
            gatewayRemoteService = gatewayRemoteManager.getRemoteService(gatewayConf.getPushProtocol());
            gatewayRemoteService.authorize(gatewayConf);
            gatewayRemoteService.init(gatewayConf);
        }
    }
src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java
@@ -1,21 +1,23 @@
package com.fzzy.gateway.hx2023.service;
import com.fzzy.api.data.AuthToken;
import com.alibaba.fastjson2.JSONObject;
import com.fzzy.api.data.PushProtocol;
import com.fzzy.api.entity.ApiLog;
import com.fzzy.api.utils.ContextUtil;
import com.fzzy.api.utils.MyMD5Util;
import com.fzzy.api.utils.RSAUtils;
import com.fzzy.api.utils.RedisConst;
import com.fzzy.api.utils.RedisUtil;
import com.fzzy.api.view.repository.ApiLogRep;
import com.fzzy.gateway.service.GatewayConfService;
import com.fzzy.gateway.util.GatewayHttpUtil;
import com.fzzy.gateway.api.GatewayRemoteService;
import com.fzzy.gateway.data.GatewayResponse;
import com.fzzy.gateway.entity.GatewayConf;
import com.fzzy.gateway.hx2023.ScConstant;
import com.fzzy.push.gb2022.HttpClientUtil;
import com.fzzy.gateway.hx2023.data.CloudResp;
import com.fzzy.gateway.util.GatewayRSAUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
@@ -30,8 +32,10 @@
    @Resource
    private ApiLogRep apiLogRep;
    @Resource
    private RedisUtil redisUtil;
    private GatewayConfService gatewayConfService;
    @Override
@@ -40,79 +44,158 @@
    }
    @Override
    public GatewayResponse authorize(GatewayConf conf) {
        //添加LOG
        ApiLog apiLog = new ApiLog();
        apiLog.setData("鉴权接口");
        apiLog.setId(ContextUtil.getUUID());
        apiLog.setKqdm(conf.getKqdm());
    public void init(GatewayConf gatewayConf) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("username", conf.getUserName());
            map.put("username", conf.getPassword());
            if (StringUtils.isEmpty(gatewayConf.getApiUrl())) {
                return;
            }
            log.debug("-----------------数据报文----------------{}", map);
            //获取公私钥接口
            Map<String, String> params = new HashMap<>();
            params.put("appId", gatewayConf.getGatewayId());
            String url = gatewayConf.getApiUrl() + "reserver/api/key/apply";
            String jsonStr = GatewayHttpUtil.doGet(url, params);
            log.info("---获取公私钥接口-返回---{}", jsonStr);
            CloudResp respKey = JSONObject.parseObject(jsonStr, CloudResp.class);
            if (ScConstant.CODE_200 == respKey.getCode()) {
                JSONObject object = respKey.getData();
                String pubKey = (String) object.get("pubKey");
                String priKey = (String) object.get("priKey");
                gatewayConf.setPublicKey(pubKey);
                gatewayConf.setPrivateKey(priKey);
            }
            String url = conf.getApiUrl() + ScConstant.API_URL_AUTH;
            //获取 AccessToken æŽ¥å£
            String sign = getSign(params, gatewayConf.getPrivateKey());
            params.put("sign", sign);
            url = gatewayConf.getApiUrl() + "reserver/api/token/apply";
            jsonStr = GatewayHttpUtil.doGet(url, params);
            log.info("---获取AccessToken接口-返回---{}", jsonStr);
            CloudResp respToken = JSONObject.parseObject(jsonStr, CloudResp.class);
            if (ScConstant.CODE_200 == respToken.getCode()) {
                JSONObject object = respKey.getData();
                if (null != object) {
                    String token = (String) object.get("token");
                    gatewayConf.setAccessToken(token);
                }
            }
            GatewayResponse responseDto = HttpClientUtil.pushGateway(url, map);
            apiLog.setStatus(responseDto.getStatus());
            apiLog.setResult(responseDto.getMessage());
            apiLogRep.save(apiLog);
            //更新缓存
            updateAuthToken(gatewayConf);
            updateAuthToken(responseDto, conf);
            return responseDto;
        } catch (Exception e) {
            apiLog.setStatus(99);
            apiLog.setResult("失败:" + e.getMessage());
            apiLogRep.save(apiLog);
            log.error(e.getMessage(), e);
            return new GatewayResponse(99, e.getMessage());
            log.error("------初始化失败-----{}", e);
        }
    }
    @Override
    public void heartbeat(GatewayConf gatewayConf) {
        try {
            if (StringUtils.isEmpty(gatewayConf.getApiUrl())) {
                return;
            }
            gatewayConf = getCacheConf(gatewayConf.getKqdm());
            //网关心跳接口
            Map<String, String> params = new HashMap<>();
            params.put("token", gatewayConf.getAccessToken());
            params.put("gatewayId", gatewayConf.getGatewayId());
            params.put("gatewayIp", gatewayConf.getGatewayIp());
            params.put("gatewayMac", gatewayConf.getGatewayMac());
            params.put("heartbeat", "1");
            params.put("timestamp", System.currentTimeMillis() + "");
            String sign = getSign(params, gatewayConf.getPrivateKey());
            params.put("sign", sign);
            String url = gatewayConf.getApiUrl() + "reserver/api/iot/equipment/heartbeat";
            String jsonStr = GatewayHttpUtil.doGet(url, params);
            log.info("---网关心跳接口-返回---{}", jsonStr);
        } catch (Exception e) {
            log.error("------网关心跳接口--执行失败-----{}", e);
        }
    }
    @Override
    public void pushInfo(GatewayConf gatewayConf) {
        try {
            if (StringUtils.isEmpty(gatewayConf.getApiUrl())) {
                return;
            }
            gatewayConf = getCacheConf(gatewayConf.getKqdm());
            //网关心跳接口
            Map<String, String> params = new HashMap<>();
            params.put("token", gatewayConf.getAccessToken());
            params.put("gatewayId", gatewayConf.getGatewayId());
            params.put("gatewayIp", gatewayConf.getGatewayIp());
            params.put("gatewayMac", gatewayConf.getGatewayMac());
            params.put("gatewayCPU", gatewayConf.getGatewayCPU());
            params.put("gatewayMem", gatewayConf.getGatewayMem());
            params.put("gatewayHardDisk", gatewayConf.getGatewayHardDisk());
            params.put("timestamp", System.currentTimeMillis() + "");
            String sign = getSign(params, gatewayConf.getPrivateKey());
            params.put("sign", sign);
            String url = gatewayConf.getApiUrl() + "reserver/api/iot/equipment/heartbeat";
            String jsonStr = GatewayHttpUtil.doGet(url, params);
            log.info("---推送网关信息-返回---{}", jsonStr);
        } catch (Exception e) {
            log.error("------推送网关信息--执行失败-----{}", e);
        }
    }
    public String getSign(Map<String, String> parames, String priKey) {
        //参数拼接
        String msg = "";
        for (Map.Entry<String, String> param : parames.entrySet()) {
            msg += param.getKey() + "=" + param.getValue() + "&";
        }
        msg = msg.substring(0, msg.length() - 1);
        log.debug("------待加密信息-----{}", msg);
        //MD5加密
        String md5sign = MyMD5Util.getMD5(msg);
        log.debug("------md5加密-----{}", md5sign);
        //RSA加密
        String result = GatewayRSAUtils.encryptByPrivate(md5sign, priKey);
        log.debug("------RSA加密-----{}", result);
        return result;
    }
    /**
     * @param kqdm
     * @return
     */
    public AuthToken getAuthToken(String kqdm) {
        try {
            String key = RedisConst.buildKey(RedisConst.KYE_TOKEN, kqdm);
            AuthToken token = (AuthToken) redisUtil.get(key);
            if (null == token) {
                log.error("------------------未获取到TOKEN---------------");
                return null;
            }
            return token;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    public GatewayConf getCacheConf(String kqdm) {
        return gatewayConfService.getCacheConf(kqdm);
    }
    private void updateAuthToken(GatewayResponse dto, GatewayConf conf) {
        String key = RedisConst.buildKey(RedisConst.KYE_TOKEN, conf.getKqdm());
        AuthToken token = getAuthToken(conf.getKqdm());
    private void updateAuthToken(GatewayConf conf) {
        if (null == token) {
            token = new AuthToken();
            token.setKqdm(conf.getKqdm());
        }
        gatewayConfService.updateCache(conf);
        if (null != dto.getResult()) {
            token.setToken(dto.getResult().getToken());
        }
        redisUtil.set(key, token);
    }
src/main/java/com/fzzy/gateway/package-info.java
@@ -1,12 +1,4 @@
/**
 * ç½‘关接口
 *
 *
 *
 * æµ‹è¯•提交
 *
 *
 *
 *
 */
package com.fzzy.gateway;
src/main/java/com/fzzy/gateway/service/GatewayConfService.java
@@ -3,19 +3,27 @@
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.fzzy.api.utils.RedisConst;
import com.fzzy.api.utils.RedisUtil;
import com.fzzy.gateway.entity.GatewayConf;
import com.fzzy.gateway.service.repository.GatewayConfRep;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Slf4j
@Component
public class GatewayConfService {
    @Resource
    private GatewayConfRep gatewayConfRep;
    @Resource
    private RedisUtil redisUtil;
    /**
@@ -57,18 +65,29 @@
        return null;
    }
    /**
     * gatewayConfService#delData
     *
     * @param data
     */
    @Expose
    public String flush(GatewayConf data) {
        GatewayConf data2 = new GatewayConf();
        BeanUtils.copyProperties(data, data2);
        gatewayConfRep.delete(data2);
        return null;
    public void updateCache(GatewayConf conf) {
        String key = RedisConst.buildKey(RedisConst.KYE_CONF_GATEWAY, conf.getKqdm());
        redisUtil.set(key, conf);
    }
    public GatewayConf getCacheConf(String kqdm) {
        try {
            String key = RedisConst.buildKey(RedisConst.KYE_CONF_GATEWAY, kqdm);
            return (GatewayConf) redisUtil.get(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
    public List<GatewayConf> getCacheConfList() {
        String tag = RedisConst.buildKey(RedisConst.KYE_CONF_GATEWAY);
        Set<String> keys = redisUtil.keys(tag);
        List<GatewayConf> result = new ArrayList<>();
        for (String key : keys) {
            result.add((GatewayConf) redisUtil.get(key));
        }
        return result;
    }
}
src/main/java/com/fzzy/gateway/util/GatewayHttpUtil.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,69 @@
package com.fzzy.gateway.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;
/**
 * ç½‘关专用HTTP请求工具类
 */
@Slf4j
public class GatewayHttpUtil {
    /**
     * æ‰§è¡ŒGET请求
     * @param url
     * @param paramsMap
     * @return
     * @throws Exception
     */
    public static String doGet(String url,Map<String, String> paramsMap) throws Exception{
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            String getUrl = url + "?";
            if (paramsMap != null) {
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                  //  getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8") + "&";
                    getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8") + "&";
                }
            }
            HttpGet method = new HttpGet(getUrl);
            method.setHeader("Accept", "application/json");
            method.setHeader("charset", "UTF-8");
            response = client.execute(method);
//            response.setHeader("Accept", "application/json");
//            response.setHeader("charset", "UTF-8");
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity,"UTF-8");
            }
        } catch (Exception e) {
            log.error("http request failed", e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return responseText;
    }
}
src/main/java/com/fzzy/gateway/util/GatewayRSAUtils.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,370 @@
package com.fzzy.gateway.util;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.xerces.impl.dv.util.Base64;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class GatewayRSAUtils {
    /**
     * RSA最大加密明文大小 2048/8-11
     */
    private static final int MAX_ENCRYPT_BLOCK = 245;
    /**
     * RSA最大解密密文大小 2048/8
     */
    private static final int MAX_DECRYPT_BLOCK = 256;
    private static final int KEYSIZE = 1024;// å¯†é’¥ä½æ•°
    /**
     * å®šä¹‰åŠ å¯†æ–¹å¼
     */
    public static final String KEY_RSA = "RSA";
    /**
     * å®šä¹‰å…¬é’¥å…³é”®è¯
     */
    public static final String KEY_RSA_PUBLICKEY = "RSAPublicKey";
    /**
     * å®šä¹‰ç§é’¥å…³é”®è¯
     */
    public static final String KEY_RSA_PRIVATEKEY = "RSAPrivateKey";
    /**
     * å®šä¹‰ç­¾åç®—法
     */
    private final static String KEY_RSA_SIGNATURE = "MD5withRSA";
    /**
     * ç”Ÿæˆå…¬ç§å¯†é’¥å¯¹
     */
    public static Map<String, Object> init() {
        Map<String, Object> map = null;
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA);
            //设置密钥对的bit数,越大越安全,但速度减慢,一般使用512或1024
            generator.initialize(KEYSIZE);
            KeyPair keyPair = generator.generateKeyPair();
            // èŽ·å–å…¬é’¥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            // èŽ·å–ç§é’¥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            // å°†å¯†é’¥å¯¹å°è£…为Map
            map = new HashMap<>(2);
            map.put(KEY_RSA_PUBLICKEY, publicKey);
            map.put(KEY_RSA_PRIVATEKEY, privateKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * èŽ·å–Base64编码的公钥字符串
     */
    public static String getPublicKey(Map<String, Object> map) {
        String str = "";
        Key key = (Key) map.get(KEY_RSA_PUBLICKEY);
        str = encryptBase64(key.getEncoded());
        return str;
    }
    /**
     * èŽ·å–Base64编码的私钥字符串
     */
    public static String getPrivateKey(Map<String, Object> map) {
        String str = "";
        Key key = (Key) map.get(KEY_RSA_PRIVATEKEY);
        str = encryptBase64(key.getEncoded());
        return str;
    }
    /**
     * BASE64 è§£ç 
     *
     * @param key éœ€è¦Base64解码的字符串
     * @return å­—节数组
     */
    public static byte[] decryptBase64(String key) {
       // return Base64.getDecoder().decode(key);
        return Base64.decode(key);
    }
    /**
     * BASE64 ç¼–码
     *
     * @param key éœ€è¦Base64编码的字节数组
     * @return å­—符串
     */
    public static String encryptBase64(byte[] key) {
       // return new String(Base64.getEncoder().encode(key));
        return new String(Base64.encode(key));
    }
    /**
     * å…¬é’¥åР坆  å¦‚果大于245则分段加密
     */
    public static String encryptByPublic(String encryptingStr, String publicKeyStr) {
        try {
            // å°†å…¬é’¥ç”±å­—符串转为UTF-8格式的字节数组
            byte[] publicKeyBytes = decryptBase64(publicKeyStr);
            // è޷得公钥
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            // å–得待加密数据
            byte[] data = encryptingStr.getBytes(StandardCharsets.UTF_8);
            KeyFactory factory;
            factory = KeyFactory.getInstance(KEY_RSA);
            PublicKey publicKey = factory.generatePublic(keySpec);
            // å¯¹æ•°æ®åР坆
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // å¯¹æ•°æ®åˆ†æ®µåР坆
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            // è¿”回加密后由Base64编码的加密信息
            return encryptBase64(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * ç§é’¥è§£å¯† å¦‚果大于256则分段解密
     */
    public static String decryptByPrivate(String encryptedStr, String privateKeyStr) {
        try {
            // å¯¹ç§é’¥è§£å¯†
            byte[] privateKeyBytes = decryptBase64(privateKeyStr);
            // èŽ·å¾—ç§é’¥
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            // èŽ·å¾—å¾…è§£å¯†æ•°æ®
            byte[] data = decryptBase64(encryptedStr);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PrivateKey privateKey = factory.generatePrivate(keySpec);
            // å¯¹æ•°æ®è§£å¯†
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // å¯¹æ•°æ®åˆ†æ®µè§£å¯†
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            // è¿”回UTF-8编码的解密信息
            return new String(decryptedData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * ç§é’¥åР坆  å¦‚果大于245则分段加密
     */
    public static String encryptByPrivate(String encryptingStr, String privateKeyStr) {
        try {
            byte[] privateKeyBytes = decryptBase64(privateKeyStr);
            // èŽ·å¾—ç§é’¥
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            // å–得待加密数据
            byte[] data = encryptingStr.getBytes(StandardCharsets.UTF_8);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PrivateKey privateKey = factory.generatePrivate(keySpec);
            // å¯¹æ•°æ®åР坆
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // å¯¹æ•°æ®åˆ†æ®µåР坆
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            // è¿”回加密后由Base64编码的加密信息
            return encryptBase64(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * å…¬é’¥è§£å¯† å¦‚果大于256则分段解密
     */
    public static String decryptByPublic(String encryptedStr, String publicKeyStr) {
        try {
            // å¯¹å…¬é’¥è§£å¯†
            byte[] publicKeyBytes = decryptBase64(publicKeyStr);
            // å–得公钥
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            // å–得待加密数据
            byte[] data = decryptBase64(encryptedStr);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PublicKey publicKey = factory.generatePublic(keySpec);
            // å¯¹æ•°æ®è§£å¯†
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // å¯¹æ•°æ®åˆ†æ®µè§£å¯†
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            // è¿”回UTF-8编码的解密信息
            return new String(decryptedData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * ç”¨ç§é’¥å¯¹åŠ å¯†æ•°æ®è¿›è¡Œç­¾å
     */
    public static String sign(String encryptedStr, String privateKey) {
        String str = "";
        try {
            //将私钥加密数据字符串转换为字节数组
            byte[] data = encryptedStr.getBytes();
            // è§£å¯†ç”±base64编码的私钥
            byte[] bytes = decryptBase64(privateKey);
            // æž„造PKCS8EncodedKeySpec对象
            PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
            // æŒ‡å®šçš„加密算法
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            // å–私钥对象
            PrivateKey key = factory.generatePrivate(pkcs);
            // ç”¨ç§é’¥å¯¹ä¿¡æ¯ç”Ÿæˆæ•°å­—签名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initSign(key);
            signature.update(data);
            str = encryptBase64(signature.sign());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
    /**
     * æ ¡éªŒæ•°å­—签名
     *
     * @return æ ¡éªŒæˆåŠŸè¿”å›žtrue,失败返回false
     */
    public static boolean verify(String encryptedStr, String publicKey, String sign) {
        boolean flag = false;
        try {
            //将私钥加密数据字符串转换为字节数组
            byte[] data = encryptedStr.getBytes();
            // è§£å¯†ç”±base64编码的公钥
            byte[] bytes = decryptBase64(publicKey);
            // æž„造X509EncodedKeySpec对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            // æŒ‡å®šçš„加密算法
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            // å–公钥对象
            PublicKey key = factory.generatePublic(keySpec);
            // ç”¨å…¬é’¥éªŒè¯æ•°å­—签名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initVerify(key);
            signature.update(data);
            flag = signature.verify(decryptBase64(sign));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    /**
     * åŠŸèƒ½æè¿°:格式化公私钥 C++格式
     * å…¬é’¥å­—符串开头要加上“-----BEGIN PUBLIC KEY-----\n”,结尾加上“\n-----END PUBLIC KEY-----\n”
     * ç§é’¥å­—符串开头要加上“-----BEGIN RSA PRIVATE KEY-----\n”,结尾加上“\n-----END RSA PRIVATE KEY-----\n”
     *
     * @param str  è¦æ ¼å¼çš„字符串, flag
     * @param flag true为公 false为私
     * @return java.lang.String
     * @author xiaobu
     * @date 2020/3/18 16:40
     * @version 1.0
     */
    public static String formatStr(String str, boolean flag) {
        StringBuilder sb = new StringBuilder(str);
        for (int i = 0, len = sb.length(); i < len; i++) {
            if (i % 64 == 0) {
                sb.insert(i, "\n");
            }
        }
        if (flag) {
            sb = new StringBuilder("-----BEGIN PUBLIC KEY-----").append(sb).append("\n-----END PUBLIC KEY-----\n");
        } else {
            sb = new StringBuilder("-----BEGIN RSA PRIVATE KEY-----").append(sb).append("\n-----END RSA PRIVATE KEY-----\n");
        }
        return sb.toString();
    }
}
src/main/java/com/fzzy/gateway/view/GatewayConf.view.xml
@@ -15,10 +15,6 @@
        <Property name="label">库区代码</Property>
        <Property name="required">true</Property>
      </PropertyDef>
      <PropertyDef name="appId">
        <Property></Property>
        <Property name="label">appId</Property>
      </PropertyDef>
      <PropertyDef name="gatewayId">
        <Property></Property>
        <Property name="label">网关ID</Property>
@@ -276,11 +272,6 @@
            <AutoFormElement>
              <Property name="name">gatewayHardDisk</Property>
              <Property name="property">gatewayHardDisk</Property>
              <Editor/>
            </AutoFormElement>
            <AutoFormElement>
              <Property name="name">appId</Property>
              <Property name="property">appId</Property>
              <Editor/>
            </AutoFormElement>
            <AutoFormElement>
src/main/java/com/fzzy/push/gb2022/HttpClientUtil.java
@@ -3,7 +3,6 @@
import com.alibaba.fastjson.JSON;
import com.fzzy.api.dto.ResponseDto;
import com.fzzy.gateway.data.GatewayResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
@@ -138,100 +137,6 @@
            responseDto = JSON.parseObject(rs, ResponseDto.class);
            if (responseDto == null) return new ResponseDto(99, "接口请求发生未知错误");
            responseDto.setJSESSIONID(JSESSIONID);
            return responseDto;
        } finally {
            try {
                outputStream.close();
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
            }
            outputStream = null;
            if (connection != null)
                connection.disconnect();
            connection = null;
        }
    }
    public static GatewayResponse pushGateway(String url, Map<String, Object> map) throws Exception {
        log.info("---------接口请求地址:" + url + "----------参数:" + JSON.toJSONString(map) + "---------");
        BufferedReader in = null;
        URL urls = new URL(url);
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        String rs = "";
        GatewayResponse responseDto;
        try {
            connection = (HttpURLConnection) urls.openConnection();
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Range", "bytes=" + "");
            connection.setConnectTimeout(20000);
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            StringBuffer buffer = new StringBuffer();
            outputStream = connection.getOutputStream();
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                // æ¯æ¬¡éƒ½æ¸…空buffer,避免写入上次的数据
                buffer.delete(0, buffer.length());
                buffer.append("------footfoodapplicationrequestnetwork\r\n");
                Object value = entry.getValue();
                if (!(value instanceof File)) {
                    buffer.append("Content-Disposition: form-data; name=\"");
                    buffer.append(entry.getKey());
                    buffer.append("\"\r\n\r\n");
                    buffer.append(entry.getValue());
                    buffer.append("\r\n");
                    outputStream.write(buffer.toString().getBytes());
                } else {
                    buffer.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"; filename=\"" + ((File) entry.getValue()).getName() + "\"\r\n");
                    buffer.append("Content-Type: " + "zip" + "\r\n\r\n");
                    outputStream.write(buffer.toString().getBytes());
                    File file = (File) entry.getValue();
                    DataInputStream ins = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = ins.read(bufferOut)) != -1) {
                        outputStream.write(bufferOut, 0, bytes);
                    }
                    // æ–‡ä»¶æµåŽé¢æ·»åŠ æ¢è¡Œï¼Œå¦åˆ™æ–‡ä»¶åŽé¢çš„ä¸€ä¸ªå‚æ•°ä¼šä¸¢å¤±
                    outputStream.write("\r\n".getBytes());
                }
            }
            if (entries != null && map.size() > 0) {
                buffer.delete(0, buffer.length());
                buffer.append("------footfoodapplicationrequestnetwork--\r\n");
            }
            outputStream.write(buffer.toString().getBytes());
            try {
                connection.connect();
                if (connection.getResponseCode() == 200) {
                    in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        rs += line;
                    }
                } else {
                    log.error("http状态:" + connection.getResponseCode());
                    log.error("http消息:" + connection.getResponseMessage());
                }
            } catch (Exception e) {
                System.out.println("发生异常");
                log.error(e.getMessage(), e);
                rs = null;
                return new GatewayResponse(99, e.getMessage());
            }
            log.info("---------接口返回:" + rs + "---------");
            responseDto = JSON.parseObject(rs, GatewayResponse.class);
            if (responseDto == null) return new GatewayResponse(99, "接口请求发生未知错误");
            return responseDto;
        } finally {
            try {