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 {