博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文本入库特殊字符处理, 防止SQL注入
阅读量:4043 次
发布时间:2019-05-24

本文共 1088 字,大约阅读时间需要 3 分钟。

很多SQL注入都是通过文本特殊字符引入,所以很多入库的文本都需要处理特殊字符转译

1.简单的特殊字符替换成转译的字符

简单的代码如下:

public static String escapeSql(String str) {    if (str == null) {        return null;    }    str = StringUtils.replace(str, "\\", "\\\\");    str = StringUtils.replace(str, "'", "''");    str = StringUtils.replace(str, ";", ";");    str = StringUtils.replace(str, "\"", "\\\"");    return str;}

org.apache包下有StringEscapeUtils处理特殊字符的工具类,但是需谨慎使用,避免其他字符被替换

2.使用Base64处理文本

byte[] encodeBase64 = Base64.encodeBase64(str.getBytes("UTF-8"));  System.out.println("AA: " + new String(encodeBase64));
注意加密以及解密时编码问题,也许与数据编码支持

Base64处理时会导致字符串变长,这时需要设置数据库表的字段长度

MySQL在5.6版本的时候增加了to_base64和from_base64函数,这样也方便了通过MySQL查询数据时查看数据

select to_base64('helloworld中国、/"sd ##@$@$\'') from dual  ;SELECT from_base64('aGVsbG93b3JsZOS4reWbveOAgS8ic2QgIyNAJEAkJw==') from dual ;
3.采用org.hibernate.internal.util.StringHelper方式

利用这种方式生成SQL语句

这种的需要入库DB底层支持Hibernate的方式

参考源码地址:http://www.programcreek.com/java-api-examples/index.php?api=org.hibernate.internal.util.StringHelper

http://www.docjar.com/html/api/org/hibernate/util/StringHelper.java.html

转载地址:http://shadi.baihongyu.com/

你可能感兴趣的文章
1066. Root of AVL Tree (25)
查看>>
1086. Tree Traversals Again (25)
查看>>
1043. Is It a Binary Search Tree (25)
查看>>
大数阶乘!
查看>>
1039. Course List for Student (25)
查看>>
1022. Digital Library (30)(字符串分割) 模拟
查看>>
1024. Palindromic Number (25) 回文字符串
查看>>
1051. Pop Sequence (25) 判断出栈序列是否合理
查看>>
判断出栈序列是否合理
查看>>
1026. Table Tennis (30)
查看>>
1028. List Sorting (25) COUT和 cin 超时
查看>>
1064. Complete Binary Search Tree (30)
查看>>
1098. Insertion or Heap Sort (25)
查看>>
1099. Build A Binary Search Tree (30) 给定二叉搜索树插值
查看>>
1083. List Grades (25)
查看>>
1036. Boys vs Girls (25)
查看>>
1094. The Largest Generation (25)
查看>>
1056. Mice and Rice (25)
查看>>
1030. Travel Plan (30)寻找最短路径
查看>>
1053. Path of Equal Weight (30)
查看>>