From 1ae45581a6024db5187c64621d01729e0d1dead5 Mon Sep 17 00:00:00 2001 From: jiazx0107@163.com <jiazx0107@163.com> Date: 星期二, 07 十一月 2023 23:40:32 +0800 Subject: [PATCH] 提交网关功能 --- src/main/java/com/fzzy/gateway/hx2023/service/ApiInitService.java | 2 src/main/java/com/fzzy/gateway/util/GatewayHttpUtil.java | 69 ++++ src/main/java/com/fzzy/gateway/hx2023/data/CloudResp.java | 44 ++ src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java | 203 ++++++++--- src/main/java/com/fzzy/api/utils/RedisConst.java | 10 src/main/java/com/fzzy/gateway/hx2023/ScConstant.java | 3 src/main/java/com/fzzy/push/gb2022/HttpClientUtil.java | 95 ----- src/main/java/com/fzzy/gateway/api/GatewayRemoteService.java | 19 src/main/java/com/fzzy/gateway/package-info.java | 8 src/main/java/com/fzzy/gateway/service/GatewayConfService.java | 45 + src/main/java/com/fzzy/gateway/hx2023/data/RespKey.java | 18 + src/main/java/com/fzzy/gateway/util/GatewayRSAUtils.java | 370 +++++++++++++++++++++ src/main/java/com/fzzy/gateway/view/GatewayConf.view.xml | 9 src/main/java/com/fzzy/gateway/entity/GatewayConf.java | 8 src/main/java/com/fzzy/gateway/GatewayRunner.java | 4 src/main/java/com/fzzy/gateway/GatewayTimerScheduled.java | 67 +++ 16 files changed, 777 insertions(+), 197 deletions(-) diff --git a/src/main/java/com/fzzy/api/utils/RedisConst.java b/src/main/java/com/fzzy/api/utils/RedisConst.java index 4d79b15..6b9869f 100644 --- a/src/main/java/com/fzzy/api/utils/RedisConst.java +++ b/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"; diff --git a/src/main/java/com/fzzy/gateway/GatewayRunner.java b/src/main/java/com/fzzy/gateway/GatewayRunner.java index c8da840..e4827f5 100644 --- a/src/main/java/com/fzzy/gateway/GatewayRunner.java +++ b/src/main/java/com/fzzy/gateway/GatewayRunner.java @@ -22,7 +22,9 @@ @Override public void run(String... args) throws Exception { - log.info("缃戝叧鎺ュ彛闅忕郴缁熷惎鍔�------------"); + //鎵ц鍒濆鍖栨柟妗� + + apiInitService.init(); } } diff --git a/src/main/java/com/fzzy/gateway/GatewayTimerScheduled.java b/src/main/java/com/fzzy/gateway/GatewayTimerScheduled.java new file mode 100644 index 0000000..b26ff83 --- /dev/null +++ b/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); + } + } + +} diff --git a/src/main/java/com/fzzy/gateway/api/GatewayRemoteService.java b/src/main/java/com/fzzy/gateway/api/GatewayRemoteService.java index 2ea3152..d187dc4 100644 --- a/src/main/java/com/fzzy/gateway/api/GatewayRemoteService.java +++ b/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); } diff --git a/src/main/java/com/fzzy/gateway/entity/GatewayConf.java b/src/main/java/com/fzzy/gateway/entity/GatewayConf.java index c697ffe..2284dd6 100644 --- a/src/main/java/com/fzzy/gateway/entity/GatewayConf.java +++ b/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 = "鐪佸钩鍙版帴鍙e湴鍧�") @Column(name = "apiUrl", length = 200) private String apiUrl; diff --git a/src/main/java/com/fzzy/gateway/hx2023/ScConstant.java b/src/main/java/com/fzzy/gateway/hx2023/ScConstant.java index 11c5db1..2786342 100644 --- a/src/main/java/com/fzzy/gateway/hx2023/ScConstant.java +++ b/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; } diff --git a/src/main/java/com/fzzy/gateway/hx2023/data/CloudResp.java b/src/main/java/com/fzzy/gateway/hx2023/data/CloudResp.java new file mode 100644 index 0000000..68e1b20 --- /dev/null +++ b/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; + + +/** + * 鐪佸钩鍙版帴鍙h繑鍥炲皝瑁� + */ +@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; + } +} diff --git a/src/main/java/com/fzzy/gateway/hx2023/data/RespKey.java b/src/main/java/com/fzzy/gateway/hx2023/data/RespKey.java new file mode 100644 index 0000000..7df4081 --- /dev/null +++ b/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; +} diff --git a/src/main/java/com/fzzy/gateway/hx2023/service/ApiInitService.java b/src/main/java/com/fzzy/gateway/hx2023/service/ApiInitService.java index 05ebc0e..e98cafa 100644 --- a/src/main/java/com/fzzy/gateway/hx2023/service/ApiInitService.java +++ b/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); } } diff --git a/src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java b/src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java index d95db6b..a6088d8 100644 --- a/src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java +++ b/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); } diff --git a/src/main/java/com/fzzy/gateway/package-info.java b/src/main/java/com/fzzy/gateway/package-info.java index 303f360..7353582 100644 --- a/src/main/java/com/fzzy/gateway/package-info.java +++ b/src/main/java/com/fzzy/gateway/package-info.java @@ -1,12 +1,4 @@ /** * 缃戝叧鎺ュ彛 - * - * - * - * 娴嬭瘯鎻愪氦 - * - * - * - * */ package com.fzzy.gateway; \ No newline at end of file diff --git a/src/main/java/com/fzzy/gateway/service/GatewayConfService.java b/src/main/java/com/fzzy/gateway/service/GatewayConfService.java index eabbf30..81ddd0a 100644 --- a/src/main/java/com/fzzy/gateway/service/GatewayConfService.java +++ b/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; + } + } diff --git a/src/main/java/com/fzzy/gateway/util/GatewayHttpUtil.java b/src/main/java/com/fzzy/gateway/util/GatewayHttpUtil.java new file mode 100644 index 0000000..30359de --- /dev/null +++ b/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; + } + +} \ No newline at end of file diff --git a/src/main/java/com/fzzy/gateway/util/GatewayRSAUtils.java b/src/main/java/com/fzzy/gateway/util/GatewayRSAUtils.java new file mode 100644 index 0000000..c81de2f --- /dev/null +++ b/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(); + // 灏嗗瘑閽ュ灏佽涓篗ap + 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 瑙g爜 + * + * @param key 闇�瑕丅ase64瑙g爜鐨勫瓧绗︿覆 + * @return 瀛楄妭鏁扮粍 + */ + public static byte[] decryptBase64(String key) { + // return Base64.getDecoder().decode(key); + return Base64.decode(key); + } + + /** + * BASE64 缂栫爜 + * + * @param key 闇�瑕丅ase64缂栫爜鐨勫瓧鑺傛暟缁� + * @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 { + // 灏嗗叕閽ョ敱瀛楃涓茶浆涓篣TF-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; + } + + /** + * 绉侀挜瑙e瘑 濡傛灉澶т簬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; + } + + /** + * 鍏挜瑙e瘑 濡傛灉澶т簬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(); + // 瑙e瘑鐢眀ase64缂栫爜鐨勭閽� + byte[] bytes = decryptBase64(privateKey); + // 鏋勯�燩KCS8EncodedKeySpec瀵硅薄 + 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锛屽け璐ヨ繑鍥瀎alse + */ + public static boolean verify(String encryptedStr, String publicKey, String sign) { + boolean flag = false; + try { + //灏嗙閽ュ姞瀵嗘暟鎹瓧绗︿覆杞崲涓哄瓧鑺傛暟缁� + byte[] data = encryptedStr.getBytes(); + // 瑙e瘑鐢眀ase64缂栫爜鐨勫叕閽� + byte[] bytes = decryptBase64(publicKey); + // 鏋勯�燲509EncodedKeySpec瀵硅薄 + 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(); + } + +} diff --git a/src/main/java/com/fzzy/gateway/view/GatewayConf.view.xml b/src/main/java/com/fzzy/gateway/view/GatewayConf.view.xml index fb93759..368136a 100644 --- a/src/main/java/com/fzzy/gateway/view/GatewayConf.view.xml +++ b/src/main/java/com/fzzy/gateway/view/GatewayConf.view.xml @@ -15,10 +15,6 @@ <Property name="label">搴撳尯浠g爜</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> diff --git a/src/main/java/com/fzzy/push/gb2022/HttpClientUtil.java b/src/main/java/com/fzzy/push/gb2022/HttpClientUtil.java index f7fb25b..b52cd8e 100644 --- a/src/main/java/com/fzzy/push/gb2022/HttpClientUtil.java +++ b/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) { - // 姣忔閮芥竻绌篵uffer锛岄伩鍏嶅啓鍏ヤ笂娆$殑鏁版嵁 - 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 { -- Gitblit v1.9.3