删除冗余debug信息,优化三方认证/解密代码容错性

This commit is contained in:
zz 2021-12-02 14:59:32 +08:00
parent 318ebf37b0
commit b332702b8b
6 changed files with 73 additions and 78 deletions

View File

@ -48,13 +48,13 @@ public class QueryStopChargeController {
//判断三方的订单号是否存在
EtOrderMapping etOrderMapping = etOrderMappingRepo.findByEvcsOrderNo(startChargeSeq).orElse(null);
if (etOrderMapping == null) {
return failCommonResponse(queryStopChargeResponse);
return failCommonResponse(queryStopChargeResponse, "错误的充电订单号");
}
String xhOrderNo = etOrderMapping.getXhOrderNo();
String pushOrderkey = "pushOrder:".concat(xhOrderNo);
Map<String, Object> pushOrder = REDIS.getCacheMap(pushOrderkey);
if (pushOrder == null || (pushOrder.get("isStopNotified") != null && (Boolean) pushOrder.get("isStopNotified"))) {
return failCommonResponse(queryStopChargeResponse);
return failCommonResponse(queryStopChargeResponse, "已下发停止充电指令");
}
//充电设备接口编码枪编码
String connectorId = queryStopChargeRequest.getConnectorId();
@ -114,15 +114,15 @@ public class QueryStopChargeController {
return commonResponse;
}
private CommonResponse failCommonResponse(QueryStopChargeResponse queryStopChargeResponse) throws JsonProcessingException {
private CommonResponse failCommonResponse(QueryStopChargeResponse queryStopChargeResponse, String msg) throws JsonProcessingException {
queryStopChargeResponse.setStartChargeSeqStat(5);
queryStopChargeResponse.setSuccStat(1);
queryStopChargeResponse.setFailReason(0);
String data = JSONUtil.toJSONString(queryStopChargeResponse);
CommonResponse commonResponse = new CommonResponse();
commonResponse.setRet("1");
commonResponse.setMsg("请求停止充电失败:错误的充电订单号");
commonResponse.setRet("0");
commonResponse.setMsg(msg);
commonResponse.setData(data);
return commonResponse;
}

View File

@ -41,13 +41,16 @@ public class QueryTokenController {
CommonResponse resp = new CommonResponse();
resp.setRet("0");
resp.setMsg("");
String decodedData = (String) tokenRequest.getAdditionalProperties().get("Data");
try {
tokenRequest = JSONUtil.readParams(decodedData, TokenRequest.class);
} catch (Exception e) {
log.error("invalid Data string: {}", decodedData);
}
String operatorID = tokenRequest.getOperatorId();
if (operatorID == null) {
String decodedData = (String) tokenRequest.getAdditionalProperties().get("Data");
try {
tokenRequest = JSONUtil.readParams(decodedData, TokenRequest.class);
} catch (Exception e) {
log.error("invalid Data string: {}", decodedData);
}
}
operatorID = tokenRequest.getOperatorId();
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setOperatorId("MA6DFCTD5");
tokenResponse.setSuccStat(0);

View File

@ -76,18 +76,20 @@ public class EvcsFilter extends OncePerRequestFilter {
CommonRequest commonRequest = JSONUtil.readParams(bodyString, CommonRequest.class);
String operatorId = commonRequest.getOperatorId();
String authorization = request.getHeader("Authorization");
log.debug("Authorization: {}", authorization);
AuthSecretToken authSecretTokenIn;
Date now = Calendar.getInstance().getTime();
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
if (servletPath.endsWith("query_token")) {
if (!handleQueryToken(request, response, chain, requestWrapper, bodyString, commonRequest, operatorId,
responseWrapper)) return;
} else if (authorization != null && authorization.startsWith("Bearer ")) {
String token = authorization.substring(7);
}
if (authorization != null && authorization.startsWith("Bearer ")) {
String token = authorization.replace("Bearer ", "");
authSecretTokenIn =
authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenTypeAndTokenExpiryGreaterThan(
operatorId, AuthSecretToken.SECRET_TOKEN_TYPE_IN, now).orElse(null);
if (authSecretTokenIn == null || !token.equals(authSecretTokenIn.getToken())) {
if (authSecretTokenIn == null) {
CommonResponse resp = new CommonResponse();
resp.setRet("4003");
resp.setMsg("Invalid token");
@ -96,34 +98,36 @@ public class EvcsFilter extends OncePerRequestFilter {
responseWrapper = new ContentCachingResponseWrapper(response);
chain.doFilter(requestWrapper, responseWrapper);
return;
} else if (!token.equals(authSecretTokenIn.getToken())) {
log.error("op[{}] Invalid auth: {}", operatorId, authorization);
}
} else {
log.error("op[{}] Invalid auth: {}", operatorId, authorization);
CommonResponse resp = new CommonResponse();
resp.setRet("4003");
resp.setMsg("Authorization header is not present or invalid");
String data = JSONUtil.toJSONString(resp);
response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
responseWrapper = new ContentCachingResponseWrapper(response);
chain.doFilter(requestWrapper, responseWrapper);
return;
}
//decrypt request
byte[] decryptedReq = null;
String erroMsg = "Decryption error";
CommonResponse resp = new CommonResponse();
authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId,
AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null);
if (authSecretTokenIn != null) {
if (servletPath.endsWith("query_token") ||
(now.before(authSecretTokenIn.getTokenExpiry())
&& authorization != null && authorization.substring(7).equals(authSecretTokenIn.getToken()))) {
try {
try {
// if (authSecretTokenIn.isEncrypt() && !"false".equals(encin)) { // test code
decryptedReq = decrypt(request, authSecretTokenIn, commonRequest, bodyString);
decryptedReq = decrypt(request, authSecretTokenIn, commonRequest, bodyString);
// } else {
// String data = commonRequest.getData();
// if (data == null) data = bodyString;
// decryptedReq = data.getBytes(StandardCharsets.UTF_8);
// }
commonRequest.setData(new String(decryptedReq));
log.debug("in.dec: {}", commonRequest);
} catch (BadPaddingException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException | InvalidKeyException e) {
erroMsg = e.getMessage();
}
} else {
erroMsg = "Authorization error, check OperatorID or token expiry";
}
commonRequest.setData(new String(decryptedReq));
log.debug("in.dec: {}", commonRequest);
} catch (BadPaddingException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException | InvalidKeyException e) {
erroMsg = e.getMessage();
}
if (decryptedReq != null && decryptedReq.length > 0) {
requestWrapper = new HttpServletRequestWritableWrapper(request,
@ -170,11 +174,10 @@ public class EvcsFilter extends OncePerRequestFilter {
}
}
private boolean handleQueryToken(HttpServletRequest request,
HttpServletResponse response, FilterChain chain,
private boolean handleQueryToken(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
ServletRequest requestWrapper, String bodyString, CommonRequest commonRequest,
String operatorId,
ContentCachingResponseWrapper responseWrapper) throws IOException, ServletException {
String operatorId, ContentCachingResponseWrapper responseWrapper) throws IOException,
ServletException {
AuthSecretToken authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId,
AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null);
@ -279,50 +282,42 @@ public class EvcsFilter extends OncePerRequestFilter {
byte[] buf = new byte[]{};
final String encin = request.getHeader("enc.in");
if ("POST".equalsIgnoreCase(request.getMethod())) {
if (request.getServletPath().endsWith("/query_token")) {
String data;
if ((encin != null && "false".equals(encin)) || commonRequest.getData() == null) {
data = bodyString;
} else if (commonRequest.getData() == null) {
data = Aes128Cbc.decryptString(bodyString, authSecretToken.getDataSecret(), authSecretToken
.getDataSecretIV());
} else {
data = Aes128Cbc.decryptString(commonRequest.getData(), authSecretToken.getDataSecret(), authSecretToken
.getDataSecretIV());
}
buf = data.getBytes(StandardCharsets.UTF_8);
if (request.getServletPath().endsWith("/query_token")) {
String data;
if (("false".equals(encin)) || commonRequest.getData() == null) {
data = bodyString;
} else {
String authorization = request.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Bearer ")) {
//decrypt Data field
buf = bodyString.getBytes(StandardCharsets.UTF_8);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(buf);
JsonNode sigNode = rootNode.path("Sig");
JsonNode operatorIDNode = rootNode.path("OperatorID");
JsonNode dataNode = rootNode.path("Data");
JsonNode timestampNode = rootNode.path("TimeStamp");
JsonNode seqNode = rootNode.path("Seq");
if (!dataNode.isNull()) {
if (!dataNode.asText().startsWith("{")) {
String computedSig = HMAC.hmacDigest(
operatorIDNode.asText().concat(dataNode.asText()).concat(timestampNode.asText()).concat(seqNode.asText()),
authSecretToken.getSigSecret());
if ((encin == null || !"false".equals(encin)) && !computedSig.equals(sigNode.asText())) {
throw new InvalidAlgorithmParameterException("Illegal Sig, computed: ".concat(computedSig));
}
}
String rawData = dataNode.asText();
String decryptedData = rawData;
if ((encin == null || encin.equals("true")) || authSecretToken.isEncrypt()) {
decryptedData = Aes128Cbc.decryptString(rawData, authSecretToken.getDataSecret(),
authSecretToken.getDataSecretIV());
((ObjectNode) rootNode).put("Data", decryptedData);
}
buf = decryptedData.getBytes();//rootNode.toString().getBytes();
data = Aes128Cbc.decryptString(commonRequest.getData(), authSecretToken.getDataSecret(), authSecretToken
.getDataSecretIV());
}
buf = data.getBytes(StandardCharsets.UTF_8);
} else {
//decrypt Data field
buf = bodyString.getBytes(StandardCharsets.UTF_8);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(buf);
JsonNode sigNode = rootNode.path("Sig");
JsonNode operatorIDNode = rootNode.path("OperatorID");
JsonNode dataNode = rootNode.path("Data");
JsonNode timestampNode = rootNode.path("TimeStamp");
JsonNode seqNode = rootNode.path("Seq");
if (!dataNode.isNull()) {
if (!dataNode.asText().startsWith("{")) {
String computedSig = HMAC.hmacDigest(
operatorIDNode.asText().concat(dataNode.asText()).concat(timestampNode.asText()).concat(seqNode.asText()),
authSecretToken.getSigSecret());
if (("false".equals(encin)) && !computedSig.equals(sigNode.asText())) {
throw new InvalidAlgorithmParameterException("Illegal Sig, computed: ".concat(computedSig));
}
}
String rawData = dataNode.asText();
String decryptedData = rawData;
if ((encin == null || encin.equals("true")) || authSecretToken.isEncrypt()) {
decryptedData = Aes128Cbc.decryptString(rawData, authSecretToken.getDataSecret(),
authSecretToken.getDataSecretIV());
((ObjectNode) rootNode).put("Data", decryptedData);
}
buf = decryptedData.getBytes();//rootNode.toString().getBytes();
}
}
return buf;

View File

@ -76,7 +76,6 @@ public class NotificationCancelOrderTask extends CoreDispatcher {
public void notify(CancelOrderRequest cancelOrderRequest, AuthSecretToken authSecretTokenOut, String orderNo) throws JsonProcessingException {
String data = JSONUtil.toJSONString(cancelOrderRequest);
//logger.debug(data);
CommonRequest<CancelOrderRequest> commonRequest = new CommonRequest<>();
commonRequest.setData(data);
String responseBody = ok(commonRequest, "/notification_cancel_order", authSecretTokenOut);

View File

@ -76,7 +76,6 @@ public class NotificationChargeOrderInfo4BonusTask extends CoreDispatcher {
etOrderMapping);
operatorIdEvcs = operatorIdEvcs == null ? "MA6DFCTD5" : operatorIdEvcs;
String data = JSONUtil.toJSONString(cdChargeOrderInfo4BonusReq);
logger.debug(data);
CommonRequest<CDChargeOrderInfo4BonusReq> commonRequest = new CommonRequest<>();
commonRequest.setData(data);
String responseBody = ok(commonRequest, "/notification_charge_order_info_for_bonus", authSecretTokenOut);

View File

@ -69,7 +69,6 @@ public class NotificationStartChargeResultTask extends CoreDispatcher {
String operatorIdEvcs = "MA6DFCTD5";
String data = JSONUtil.toJSONString(notificationStartChargeResultRequestData);
logger.debug(data);
CommonRequest<NotificationStartChargeResultRequestData> commonRequest = new CommonRequest<>();
commonRequest.setData(data);
String responseBody = ok(commonRequest, "/notification_start_charge_result", authSecretTokenOut);