方式一、
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.LinkedHashMap;
/**
* 获取验签
* @throws NoSuchAlgorithmException
*/
public String getSignature(CfPayResultDto dto) {
String data = "";
secretKey = "35346etgrey575678686797807856756";//商户的密钥
Mac sha256_HMAC = null;
try {
LinkedHashMap<String, String> postData = new LinkedHashMap<String, String>();
postData.put("orderId", dto.getOrderId());
postData.put("orderAmount", dto.getOrderAmount());
postData.put("referenceId", dto.getReferenceId());
postData.put("txStatus", dto.getTxStatus());
postData.put("paymentMode", dto.getPaymentMode());
postData.put("txMsg", dto.getTxMsg());
postData.put("txTime", dto.getTxTime());
for (String key : postData.keySet()) {
data = data + postData.get(key);
}
sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key_spec = new SecretKeySpec(secretKey.getBytes(),"HmacSHA256");
sha256_HMAC.init(secret_key_spec);
String signature = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes()));
return signature;
} catch (NoSuchAlgorithmException e) {
log.error("支付验签校验失败NoSuchAlgorithmException={}",e.getMessage());
}catch (InvalidKeyException e) {
log.error("支付验签校验失败InvalidKeyException={}",e.getMessage());
}
return null;
}
获取验签的工具类:
方式二 使用 TreeMap 方式遍历、
/**
* OCR外部接口签名验证
* @param baseReq
* @return
*/
public static NewResponseUtil checkSign(OcrBaseReq baseReq,String password) throws InvocationTargetException, IllegalAccessException {
LOGGER.info("当前时间戳盐={}",(System.currentTimeMillis() + password));
try {
String sourceSign = baseReq.getSign();//先获取签名
baseReq.setSign(null);//签名清空
JSONObject json = JSONObject.parseObject(JSON.toJSONString(baseReq));//使用 json 对象
TreeMap<String, Object> data = new TreeMap(json);//新json 对象转成 TreeMap
data.remove("sign");//再去掉 sign 节点
StringBuffer buf = new StringBuffer();
for (Map.Entry<String, Object> entry : data.entrySet()) {
buf.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");//循环拼接
}
buf.deleteCharAt(buf.length() - 1);//去掉最后一个 &
String newSign = Md5Util.stringMD5(buf.toString(),password);//加盐码进行获取标签
if(!StringUtils.equals(sourceSign,newSign)){
return new NewResponseUtil(AuthOcrTypeEnum.OCR_PARAMETERS_VERIFY_FAIL.getCode() + "" ,AuthOcrTypeEnum.OCR_PARAMETERS_VERIFY_FAIL.getDesc());
}
return NewResponseUtil.newSucceedResponse();
}catch (Exception e){
LOGGER.error("商户鉴权失败...");
}
return NewResponseUtil.newFailureResponse();
}