SqlUtil.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.ruoyi.common.utils.sql;
  2. import com.ruoyi.common.exception.UtilException;
  3. import com.ruoyi.common.utils.StringUtils;
  4. import lombok.AccessLevel;
  5. import lombok.NoArgsConstructor;
  6. /**
  7. * sql操作工具类
  8. *
  9. * @author ruoyi
  10. */
  11. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  12. public class SqlUtil {
  13. /**
  14. * 定义常用的 sql关键字
  15. */
  16. public static final String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
  17. /**
  18. * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
  19. */
  20. public static final String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
  21. /**
  22. * 检查字符,防止注入绕过
  23. */
  24. public static String escapeOrderBySql(String value) {
  25. if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
  26. throw new UtilException("参数不符合规范,不能进行查询");
  27. }
  28. return value;
  29. }
  30. /**
  31. * 验证 order by 语法是否符合规范
  32. */
  33. public static boolean isValidOrderBySql(String value) {
  34. return value.matches(SQL_PATTERN);
  35. }
  36. /**
  37. * SQL关键字检查
  38. */
  39. public static void filterKeyword(String value) {
  40. if (StringUtils.isEmpty(value)) {
  41. return;
  42. }
  43. String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
  44. for (String sqlKeyword : sqlKeywords) {
  45. if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
  46. throw new UtilException("参数存在SQL注入风险");
  47. }
  48. }
  49. }
  50. }