待签名字符串的构造规则如下:
待签名字符串=contentMD5\nrequestDate\nservicePath。
1. 关于字符串MD5值操作
/**
* 将输入字符串转换为MD5
*
* @param contentMD5Source 目标字符串
* @return contentMD5 MD5加密后的字符串
*/
public static String toMD5Base64(String contentMD5Source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(contentMD5Source.getBytes());
return new String(org.apache.commons.codec.binary.Base64.encodeBase64(md.digest()));
} catch (Exception e) {
log.error("字符串转换为MD5异常:{}", e);
return null;
}
示例:
空字符串(“”),计算得到:1B2M2Y8AsgTpgAmY7PhCfg==
2. Hmac值计算验证
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
/**
* 根据HmacSHA1算法生成HMAC信息摘要
*
* @param secret 私钥
* @param data 待加密字符串
* @return 信息摘要
*/
public static String calculateHMAC(String secret, String data) {
log.debug("密钥:{}", secret);
log.debug("待加密字符串:{}", data);
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(secretKeySpec);
return new String(Base64.encodeBase64(mac.doFinal(data.getBytes())));
} catch (Exception e) {
log.debug("calculateHMAC-生成HMAC信息摘要报错{}", e);
throw new IllegalArgumentException("HmacSHA1算法生成HMAC信息摘要异常");
}
}
}
3.签名应用及示例
示例:
参数名 | 值 | 说明 |
secretKey | dfc39deb3f63cea3a26207c3e912ca383ac7b7a2 | 接口提供 |
contentMD5 | 1B2M2Y8AsgTpgAmY7PhCfg== | 调用方计算 |
requestDate | Fri, 26 Aug 2022 06:49:11 UTC | 调用方计算 |
servicePath | /api/weakpw/statics | 请求地址原始路径 |
hmac | HN5xHDfcgwW2qM2T3GCCV1Uoi6g= | 调用方计算 |