HmacMD5Util.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package com.zsElectric.boot.common.util;
  2. import java.nio.charset.StandardCharsets;
  3. import java.security.MessageDigest;
  4. import java.security.NoSuchAlgorithmException;
  5. /**
  6. * HMAC-MD5参数签名工具类
  7. * 严格按照RFC 2104标准的7个步骤实现
  8. * @version 1.0
  9. */
  10. public class HmacMD5Util {
  11. private static final int BLOCK_SIZE = 64; // 块大小为64字节
  12. private static final byte IPAD = 0x36; // 内部填充常量
  13. private static final byte OPAD = 0x5C; // 外部填充常量
  14. /**
  15. * 根据入参顺序生成签名: OperatorID+Data+TimeStamp+Seq
  16. * @param operatorId 操作员ID
  17. * @param data 数据内容
  18. * @param timeStamp 时间戳
  19. * @param seq 序列号
  20. * @param sigSecret 签名密钥
  21. * @return 签名结果(大写)
  22. * @throws NoSuchAlgorithmException
  23. */
  24. public static String genSign(
  25. String operatorId,
  26. String data,
  27. String timeStamp,
  28. String seq,
  29. String sigSecret) throws NoSuchAlgorithmException {
  30. String content = (operatorId + data + timeStamp + seq);
  31. return hmacMD5Hex(content, sigSecret);
  32. }
  33. /**
  34. * 出参
  35. * */
  36. public static String genSign(
  37. int Ret,
  38. String Msg,
  39. String Data,
  40. String sigSecret) throws NoSuchAlgorithmException {
  41. String content = (Ret + Msg + Data).toUpperCase();
  42. return hmacMD5Hex(content, sigSecret);
  43. }
  44. /**
  45. * HMAC-MD5签名生成
  46. * @param data 待签名的消息内容
  47. * @param key 签名密钥
  48. * @return 16字节的HMAC-MD5签名结果
  49. * @throws NoSuchAlgorithmException
  50. */
  51. public static byte[] hmacMD5(byte[] data, byte[] key) throws NoSuchAlgorithmException {
  52. // 步骤1:在签名密钥后面添加0创建长为64字节的字符串
  53. byte[] k = prepareKey(key);
  54. // 步骤2:将密钥与ipad(0x36)做异或运算
  55. byte[] iPadXor = xorWithPad(k, IPAD);
  56. // 步骤3:将消息内容附加到第二步的结果字符串的末尾
  57. byte[] firstInput = concatenate(iPadXor, data);
  58. // 步骤4:对第三步生成的数据流做MD5运算
  59. byte[] firstHash = md5(firstInput);
  60. // 步骤5:将第一步生成的字符串与opad(0x5c)做异或运算
  61. byte[] oPadXor = xorWithPad(k, OPAD);
  62. // 步骤6:将第四步的结果附加到第五步的结果字符串的末尾
  63. byte[] secondInput = concatenate(oPadXor, firstHash);
  64. // 步骤7:对第六步生成的数据流做MD5运算,输出最终结果
  65. return md5(secondInput);
  66. }
  67. /**
  68. * 步骤1:准备密钥 - 填充或哈希到64字节
  69. * @param key 原始密钥
  70. * @return 64字节的密钥
  71. * @throws NoSuchAlgorithmException
  72. */
  73. private static byte[] prepareKey(byte[] key) throws NoSuchAlgorithmException {
  74. byte[] result = new byte[BLOCK_SIZE];
  75. if (key.length > BLOCK_SIZE) {
  76. // 如果密钥长度超过64字节,先进行MD5哈希
  77. byte[] hashedKey = md5(key);
  78. System.arraycopy(hashedKey, 0, result, 0, hashedKey.length);
  79. // 剩余部分填充0
  80. for (int i = hashedKey.length; i < BLOCK_SIZE; i++) {
  81. result[i] = 0;
  82. }
  83. } else if (key.length < BLOCK_SIZE) {
  84. // 如果密钥长度不足64字节,后面补0
  85. System.arraycopy(key, 0, result, 0, key.length);
  86. for (int i = key.length; i < BLOCK_SIZE; i++) {
  87. result[i] = 0;
  88. }
  89. } else {
  90. // 密钥正好64字节
  91. result = key.clone();
  92. }
  93. return result;
  94. }
  95. /**
  96. * 步骤2/5:密钥与pad常量进行异或运算
  97. * @param key 64字节的密钥
  98. * @param pad 填充常量(IPAD或OPAD)
  99. * @return 异或结果
  100. */
  101. private static byte[] xorWithPad(byte[] key, byte pad) {
  102. byte[] result = new byte[BLOCK_SIZE];
  103. for (int i = 0; i < BLOCK_SIZE; i++) {
  104. result[i] = (byte) (key[i] ^ pad);
  105. }
  106. return result;
  107. }
  108. /**
  109. * 字节数组拼接
  110. * @param a 第一个字节数组
  111. * @param b 第二个字节数组
  112. * @return 拼接后的字节数组
  113. */
  114. private static byte[] concatenate(byte[] a, byte[] b) {
  115. byte[] result = new byte[a.length + b.length];
  116. System.arraycopy(a, 0, result, 0, a.length);
  117. System.arraycopy(b, 0, result, a.length, b.length);
  118. return result;
  119. }
  120. /**
  121. * MD5哈希计算
  122. * @param input 输入数据
  123. * @return MD5哈希结果(16字节)
  124. * @throws NoSuchAlgorithmException
  125. */
  126. private static byte[] md5(byte[] input) throws NoSuchAlgorithmException {
  127. MessageDigest md = MessageDigest.getInstance("MD5");
  128. return md.digest(input);
  129. }
  130. /**
  131. * 字节数组转换为十六进制字符串
  132. * @param bytes 字节数组
  133. * @return 十六进制字符串
  134. */
  135. public static String bytesToHex(byte[] bytes) {
  136. StringBuilder hexString = new StringBuilder();
  137. for (byte b : bytes) {
  138. String hex = Integer.toHexString(0xff & b);
  139. if (hex.length() == 1) {
  140. hexString.append('0');
  141. }
  142. hexString.append(hex);
  143. }
  144. return hexString.toString().toUpperCase();
  145. }
  146. /**
  147. * 生成HMAC-MD5签名(十六进制字符串形式)
  148. * @param data 消息内容
  149. * @param key 密钥
  150. * @return 32位十六进制签名字符串
  151. * @throws NoSuchAlgorithmException
  152. */
  153. public static String hmacMD5Hex(String data, String key) throws NoSuchAlgorithmException {
  154. byte[] signature = hmacMD5(data.getBytes(StandardCharsets.UTF_8),
  155. key.getBytes(StandardCharsets.UTF_8));
  156. return bytesToHex(signature);
  157. }
  158. /**
  159. * 生成HMAC-MD5签名(十六进制字符串形式)
  160. * @param data 消息内容字节数组
  161. * @param key 密钥字节数组
  162. * @return 32位十六进制签名字符串
  163. * @throws NoSuchAlgorithmException
  164. */
  165. public static String hmacMD5Hex(byte[] data, byte[] key) throws NoSuchAlgorithmException {
  166. byte[] signature = hmacMD5(data, key);
  167. return bytesToHex(signature);
  168. }
  169. /**
  170. * 验证HMAC-MD5签名
  171. * @param data 原始消息内容
  172. * @param key 密钥
  173. * @param signature 待验证的签名(十六进制字符串)
  174. * @return 验证结果
  175. * @throws NoSuchAlgorithmException
  176. */
  177. public static boolean verify(String data, String key, String signature) throws NoSuchAlgorithmException {
  178. String calculatedSignature = hmacMD5Hex(data, key);
  179. return calculatedSignature.equalsIgnoreCase(signature);
  180. }
  181. /**
  182. * 测试方法
  183. */
  184. public static void main(String[] args) {
  185. try {
  186. // 测试数据
  187. String data = "KYWxoKWK3w8a8867aXCha+tgVE2cbZ4eR1Dc1YExri06DfZWBpUMAzlhY7rWR5SeU+xCVOauk4F7MxCJLN+5aJCBENCOAZtUksMM7VgsOz0=";
  188. String key = "U9xFXjjdYAycq30C";
  189. System.out.println("=== HMAC-MD5签名测试 ===");
  190. System.out.println("原始数据: " + data);
  191. System.out.println("密钥: " + key);
  192. // 生成签名
  193. long startTime = System.nanoTime();
  194. String signature = hmacMD5Hex(data, key);
  195. long signTime = System.nanoTime() - startTime;
  196. System.out.println("HMAC-MD5签名: " + signature);
  197. System.out.println("签名长度: " + signature.length() + "字符(32字节)");
  198. System.out.println("签名耗时: " + signTime + "纳秒");
  199. // 验证签名
  200. startTime = System.nanoTime();
  201. boolean isValid = verify(data, key, signature);
  202. long verifyTime = System.nanoTime() - startTime;
  203. System.out.println("签名验证: " + (isValid ? "成功" : "失败"));
  204. System.out.println("验证耗时: " + verifyTime + "纳秒");
  205. // 测试不同长度密钥
  206. System.out.println("\n=== 不同长度密钥测试 ===");
  207. testWithDifferentKeyLengths();
  208. // 测试签名一致性
  209. System.out.println("\n=== 签名一致性测试 ===");
  210. testSignatureConsistency();
  211. } catch (Exception e) {
  212. e.printStackTrace();
  213. }
  214. }
  215. /**
  216. * 测试不同长度密钥的签名
  217. */
  218. private static void testWithDifferentKeyLengths() throws NoSuchAlgorithmException {
  219. String data = "测试数据";
  220. // 短密钥(小于64字节)
  221. String shortKey = "short";
  222. String signature1 = hmacMD5Hex(data, shortKey);
  223. System.out.println("短密钥签名: " + signature1);
  224. // 长密钥(等于64字节)
  225. String longKey = "thisIsAExactly64BytesLongKeyUsedForHMACMD5SignatureTest123";
  226. String signature2 = hmacMD5Hex(data, longKey);
  227. System.out.println("64字节密钥签名: " + signature2);
  228. // 超长密钥(大于64字节)
  229. String veryLongKey = "thisIsAVeryLongKeyThatExceedsThe64BytesBlockSizeUsedForHMACMD5SignatureTest123456789";
  230. String signature3 = hmacMD5Hex(data, veryLongKey);
  231. System.out.println("超长密钥签名: " + signature3);
  232. }
  233. /**
  234. * 测试签名一致性(相同输入应产生相同输出)
  235. */
  236. private static void testSignatureConsistency() throws NoSuchAlgorithmException {
  237. String data = "一致性测试数据";
  238. String key = "testKey";
  239. // 多次签名应该结果一致
  240. String signature1 = hmacMD5Hex(data, key);
  241. String signature2 = hmacMD5Hex(data, key);
  242. String signature3 = hmacMD5Hex(data, key);
  243. System.out.println("第一次签名: " + signature1);
  244. System.out.println("第二次签名: " + signature2);
  245. System.out.println("第三次签名: " + signature3);
  246. boolean consistent = signature1.equals(signature2) && signature2.equals(signature3);
  247. System.out.println("签名一致性: " + (consistent ? "通过" : "失败"));
  248. // 测试数据微小变化会导致签名完全不同
  249. String similarData = "一致性测试数据 "; // 多一个空格
  250. String differentSignature = hmacMD5Hex(similarData, key);
  251. System.out.println("微小变化后签名: " + differentSignature);
  252. System.out.println("敏感性测试: " + (!signature1.equals(differentSignature) ? "通过" : "失败"));
  253. }
  254. }