当前位置:   article > 正文

JAVA -- sm3加密签名,以及防止重复攻击_java sm3

java sm3

背景:

        后端开发基本都遇到过使用签名校验的情况,签名的作用是为了防止请求数据被别人截取篡改重新请求。

        为什么签名验证可以防止请求数据被篡改,因为一般签名的规则就是,你的所有请求参数,按照约定好的格式进行拼接,后面得到一个拼接后的字符串,这个字符串后面再加上一个双方私下确认后的签名秘钥(固定),最后组合成一个待签名字符串,用这个字符串进行sm3加密。sm3加密是个不可逆的加密(理论上),请求方把这个加密后面签名字段放到请求头中,服务提供方本地根据相同的方法进行组合签名字符串和加密,然后对面本地加密的签名和请求头中的签名是否相同,相同则认为这个数据是可靠的,未被篡改过的(加密前数据不同,加密后的签名肯定不同)。

        PS:签名只能验证防止请求数据被篡改,并不能说你把数据加密让别人看不见,只要是互联网上传输,数据就可能被别人获取到

签名优化:

        请求头加上时间戳,代码上验证请求的时间戳和当前时间戳时间差距,差距过大就拒绝请求(比如只接受一分钟内请求),同时把这个时间戳加到签名字符串去,这样签名的数据内容就包含时间戳(可以防止别人用同一份签名发起重复请求攻击,因为时间戳是一直在变的,签名中的时间戳和请求报文头的时间戳不同,验证签名就不会通过),这样就可以做到即使有人获取到了某个请求的参数和签名,以此发起多次重复请求攻击,这种攻击最多只有一分钟的有效期。

代码:

        

  1. package com.dw.task.utils;
  2. import cn.hutool.crypto.SmUtil;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.stereotype.Component;
  5. import java.lang.reflect.Field;
  6. import java.util.Objects;
  7. @Slf4j
  8. @Component
  9. public class Sm3UtilHua {
  10. private static Integer httpCheckSignTimeOut = 1;//请求签名有效时间 默认1分钟
  11. /**
  12. * 获取实体类拼成的加密字段
  13. * @param checkSign 前端传入的签名(从请求报文头获取)
  14. * @param signModel 查询的DTO模型类
  15. * @param privateKey 签名加密私钥
  16. * @param timestamp 时间戳(从请求报文头获取)
  17. * @return 比对结果
  18. */
  19. public boolean checkSign(String checkSign , Object signModel , String privateKey,Long timestamp) throws Exception {
  20. Long thisTime = System.currentTimeMillis() - timestamp;
  21. Integer checkSignTimeOut = httpCheckSignTimeOut;
  22. if (!(Objects.isNull(checkSignTimeOut) || checkSignTimeOut.intValue() == 0)){
  23. //时间为0或者未配置签名超时时间,默认不验证时间戳
  24. if(thisTime >= 60*1000*checkSignTimeOut || thisTime<=0){
  25. //checkSignTimeOut分钟内的时间戳才处理
  26. log.error("时间戳异常,非"+checkSignTimeOut+"分钟内请求,当前时间戳:"+System.currentTimeMillis());
  27. return false;
  28. }
  29. }
  30. String signValue = getSignValue(signModel) + "&timestamp=" + timestamp +"&privateKey=" +privateKey;
  31. String sign = getSign(signValue);
  32. log.info("【本地加密后 sm3 签名】" + sign);//生产上建议注释此行,防止泄露
  33. return sign.toUpperCase().equals(checkSign.toUpperCase())? true : false;
  34. }
  35. /**
  36. * 加密签名
  37. * @param signValue 待加密签名字符串
  38. * @return 加密后签名字符串
  39. */
  40. public String getSign(String signValue){
  41. return SmUtil.sm3(signValue);
  42. }
  43. /**
  44. * 获取实体类拼成的加密字段
  45. * @param classA 传入参数实体类
  46. * @return 待加密字符串
  47. */
  48. public String getSignValue(Object classA) {
  49. Field[] fs = classA.getClass().getDeclaredFields();//获取所有属性
  50. String[][] temp = new String[fs.length][2]; //用二维数组保存 参数名和参数值
  51. for (int i=0; i<fs.length; i++) {
  52. fs[i].setAccessible(true);
  53. temp[i][0] = fs[i].getName().toLowerCase(); //获取属性名
  54. try {
  55. temp[i][1] = String.valueOf(fs[i].get(classA)) ;//把属性值放进数组
  56. } catch (Exception e) {
  57. log.error("【签名字段:"+fs[i].getName()+"添加失败】");
  58. }
  59. }
  60. temp = doChooseSort(temp); //对参数实体类按照字母顺序排续
  61. String result = "";
  62. for (int i = 0; i < temp.length; i++) {//按照签名规则生成待加密字符串
  63. result = result + temp[i][0]+"="+temp[i][1]+"&";
  64. }
  65. result = result.substring(0, result.length()-1);//消除掉最后的“&”
  66. log.info("【签名信息】{}" ,result);
  67. return result;
  68. }
  69. /**
  70. * 对二维数组里面的数据进行选择排序,按字段名按abcd顺序排列
  71. * @param data 未按照字母顺序排序的二维数组
  72. * @return
  73. */
  74. private String[][] doChooseSort(String[][] data) {//排序方式为选择排序
  75. String[][] temp = new String[data.length][2];
  76. temp = data;
  77. int n = temp.length;
  78. for (int i = 0; i < n-1; i++) {
  79. int k = i;// 初始化最小值的小标
  80. for (int j = i+1; j<n; j++) {
  81. if (temp[k][0].compareTo(temp[j][0]) > 0) { //下标k字段名大于当前字段名
  82. k = j;// 修改最大值的小标
  83. }
  84. }
  85. // 将最小值放到排序序列末尾
  86. if (k > i) { //用相加相减法交换data[i] 和 data[k]
  87. String tempValue ;
  88. tempValue = temp[k][0];
  89. temp[k][0] = temp[i][0];
  90. temp[i][0] = tempValue;
  91. tempValue = temp[k][1];
  92. temp[k][1] = temp[i][1];
  93. temp[i][1] = tempValue;
  94. }
  95. }
  96. return temp;
  97. }
  98. }

测试代码:

  1. public static void main(String[] args) throws Exception {
  2. //模拟请求参数
  3. QueryDTO dto = new QueryDTO();
  4. dto.setName("张三");
  5. dto.setAge(18);
  6. dto.setIdCard("666666666666666");
  7. //模拟请求报文头时间戳
  8. Long nowTime = System.currentTimeMillis();
  9. //签名加密私钥(不要在互联网上传输,调用方和提供方私下物理确认和设置)
  10. String privateKey = "48d95af20fa1bc438db42e280085707b60841c";
  11. Sm3UtilHua sm3UtilHua = new Sm3UtilHua();
  12. System.out.println("1:请求签名错误的案例");
  13. //模拟请求错误的签名
  14. String errorSign = "2222222222222222222";
  15. System.out.println("验签校验结果:" + sm3UtilHua.checkSign(errorSign,dto, privateKey,nowTime));
  16. System.out.println();
  17. System.out.println("2:请求签名正确的案例");
  18. String signValue = sm3UtilHua.getSignValue(dto) + "&timestamp=" + nowTime +"&privateKey=" +privateKey;//复制上面1请求的加密后签名
  19. String trueSign = sm3UtilHua.getSign(signValue);
  20. System.out.println("验签校验结果:" + sm3UtilHua.checkSign(trueSign,dto, privateKey,nowTime));
  21. System.out.println();
  22. System.out.println("3:请求签名正确,但是时间非一分钟内请求的案例");
  23. Long oldTime = 1688036145560L;//这个时间戳大概是2023年06月29号的时间戳,所以必不是当前一分钟内时间
  24. System.out.println("验签校验结果:" + sm3UtilHua.checkSign(trueSign,dto, privateKey,oldTime));
  25. }

测试结果:

        下面的签名信息打印是不完整的,没有拼接时间戳和签名私钥,也是防止打印到日志然后泄露

  1. 1:请求签名错误的案例
  2. 10:42:11.506 [main] ERROR com.dw.task.utils.Sm3UtilHua - 时间戳异常,非1分钟内请求,当前时间戳:1688092931498
  3. 验签校验结果:false
  4. 2:请求签名正确的案例
  5. 10:42:11.522 [main] INFO com.dw.task.utils.Sm3UtilHua - 【签名信息】age=18&idcard=666666666666666&name=张三
  6. 10:42:12.358 [main] INFO com.dw.task.utils.Sm3UtilHua - 【签名信息】age=18&idcard=666666666666666&name=张三
  7. 10:42:12.359 [main] INFO com.dw.task.utils.Sm3UtilHua - 【本地加密后 sm3 签名】e60bf8ea2453f44a4a6d3b43f55399c2ce09a6f5b4be68378506d95d2d6f4491
  8. 验签校验结果:true
  9. 3:请求签名正确,但是时间非一分钟内请求的案例
  10. 10:42:12.359 [main] ERROR com.dw.task.utils.Sm3UtilHua - 时间戳异常,非1分钟内请求,当前时间戳:1688092932359
  11. 验签校验结果:false

引申优化:

        上面的代码已经可以防止一定程度的重复请求攻击,但是一分钟内的重复请求攻击还是无法防止的,如果别人截取请求信息后一分钟内发起大量重复请求的话,还是会通过签名并且穿透到业务层,对此呢如果要再优化,就可以把每次验证成功的签名放到redis缓存中,数据有效期是1分钟。这样每次在验签之前先查询redis缓存中是否有相同的签名,有即代表这个请求是重复请求,直接拦截

        思路就是这样,代码就不写了

感谢各位观众朋友阅读,如有不同意见,请不吝赐教

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/420288
推荐阅读
相关标签
  

闽ICP备14008679号