SqlUtils 工具类

一、类代码展示

作用:校验sql注入风险

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SqlUtil {

    /**
     * 定义常用的 sql关键字
     */
    public static final String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";

    /**
     * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
     */
    public static final String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";

    /**
     * 检查字符,防止注入绕过
     */
    public static String escapeOrderBySql(String value) {
        if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
            throw new UtilException("参数不符合规范,不能进行查询");
        }
        return value;
    }

    /**
     * 验证 order by 语法是否符合规范
     */
    public static boolean isValidOrderBySql(String value) {
        return value.matches(SQL_PATTERN);
    }

    /**
     * SQL关键字检查
     * 一般检查传入参数的sql注入风险
     */
    public static void filterKeyword(String value) {
        if (StringUtils.isEmpty(value)) {
            return;
        }
        //传入value中是否存在 SQL_REGEX中的数据库关键词
        String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
        for (String sqlKeyword : sqlKeywords) {
            if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
                throw new UtilException("参数存在SQL注入风险");
            }
        }
    }


}

二、测试检查sql关键字

方法:filterKeyword

    public static void main(String[] args) {
        filterKeyword("select * from user");
    }

打印结果

Exception in thread "main" com.ruoyi.common.exception.UtilException: 参数存在SQL注入风险
	at com.ruoyi.common.utils.sql.SqlUtil.filterKeyword(SqlUtil.java:55)
	at com.ruoyi.common.utils.sql.SqlUtil.main(SqlUtil.java:61)

三、测试校验排序

方法:isValidOrderBySql    :

  •  仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
  • 过滤规则: SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+"

 常用排序举例:

 支持的用法如下:
 order by id asc
 order by id asc,create_time asc
 order by id desc,create_time desc
 order by id asc,create_time desc
  public static void main(String[] args) {
        //filterKeyword("select * from user");
        Console.log(isValidOrderBySql("id"));

        Console.log(isValidOrderBySql("id,sex"));

        Console.log(isValidOrderBySql("id,nick_name"));

        Console.log(isValidOrderBySql("id_,"));

        Console.log("校验不通过----------------------------------------");
        Console.log(isValidOrderBySql("id="));


    }

测试将结果:

true
true
true
true
校验不通过----------------------------------------
false

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

syfjava

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值