校驗時間戳和簽名

1.獲取url連接裏面的時間戳和簽名 服務器

// 時間戳
            String timestamp = qpMap.get("timestamp");
            // 簽名
            String sign = qpMap.get("sign");
2.進行校驗工具

        // 校驗簽名先後過時時間
            checkSignTime(timestamp);

            // 校驗簽名
            checkSign(streamStr, timestamp, sign);
private void checkSignTime(String timestamp) {
        if (StringUtils.isBlank(timestamp)) {
            //logger.error("{}-鑑權時間戳缺失", MsgCode.SIGN_PARAM_ERROR_CODE);
            throw new BusinessException(MsgCode.SIGN_PARAM_ERROR_MSG, MsgCode.SIGN_PARAM_ERROR_CODE);
        }
        long currentTime = System.currentTimeMillis() / 1000;// 統一都傳毫秒
        long requestTime = 0;
        try {
            requestTime = Long.parseLong(timestamp);
        } catch (NumberFormatException e) {
            //logger.error("{}-鑑權時間戳錯誤 timestamp:{}", MsgCode.SIGN_PARAM_ERROR_CODE, timestamp);
            throw new BusinessException(MsgCode.SIGN_PARAM_ERROR_MSG, MsgCode.SIGN_PARAM_ERROR_CODE);
        }
        if (Math.abs(currentTime - requestTime) > APPIConstants.Filter.OUT_OF_DATE_TIME_LONG) {
            logger.error("{}-簽名已過時,服務器當前時間:{}", MsgCode.OUT_OF_DATE_SIGN_CODE, currentTime);
            throw new BusinessException(String.format(MsgCode.OUT_OF_DATE_SIGN_MSG, currentTime), MsgCode.OUT_OF_DATE_SIGN_CODE);
        }
    }

        if (StringUtils.isBlank(sign)) {
            //logger.error("{}-簽名爲空", MsgCode.SIGN_PARAM_ERROR_CODE);
            throw new BusinessException(MsgCode.SIGN_PARAM_ERROR_MSG, MsgCode.SIGN_PARAM_ERROR_CODE);
        }

        // 驗證簽名
         streamStr = Base64.encode(streamStr);
         if (!SignUtil.checkSign(streamStr, APPIConstants.Filter.key, timestamp, sign)) {
            //logger.error("{}-簽名錯誤", MsgCode.SIGN_ERR_CODE);
            throw new BusinessException(MsgCode.SIGN_ERR_MSG, MsgCode.SIGN_ERR_CODE);
        }
    }
驗證工具類: url

public class SignUtil {
private final static Logger logger = LoggerFactory.getLogger(SignUtil.class);

/**
* @Description 驗證簽名
* @param content 驗籤內容
* @param key 簽名key值
* @param additionContent 附加的簽名信息
* @param sign 待驗證的簽名
*/
public static boolean checkSign(String content, String key, String additionContent, String sign) {
if (StringUtils.isBlank(sign)) {
return false;
}
String _sign = createSign(content, key, additionContent);
if (sign.equalsIgnoreCase(_sign)) {
return true;
}
logger.error("參數sign:{},驗籤sign:{}", sign, _sign);
return false;
}

/**
* @Description 生成簽名
* @param content 簽名內容
* @param key 簽名key值
*/
public static String createSign(String content, String key, String additionContent) {
if(StringUtils.isEmpty(additionContent)){
return MD5Util.getMd5(content + key);
}else{
return MD5Util.getMd5(content + key + additionContent);
}
}
}
 
---------------------

原文:https://blog.csdn.net/riju4713/article/details/81457479

.net

相關文章
相關標籤/搜索