本文共 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/