public class SecurityString {
public static String getHtml(String str) {
//过滤敏感字符
str = filter(str);
if (str != null) {
return str.replaceAll("\r\n", "<BR>");
} else {
return " ";
}
}
/**
* 防止跨站脚本攻击
* 过滤敏感字符
* 将HTML特殊字符转换为相应的实体字符。
*/
public static String filter(String value) {
if (value == null || value.length() == 0) {
return value;
}
StringBuffer result = null;
String filtered = null;
for (int i = 0; i < value.length(); i++) {
filtered = null;
switch (value.charAt(i)) {
case '<' :
filtered = "<";
break;
case '>' :
filtered = ">";
break;
case '&' :
filtered = "&";
break;
case '"' :
filtered = """;
break;
case '\'' :
filtered = "'";
break;
}
if (result == null) {
if (filtered != null) {
result = new StringBuffer(value.length() + 50);
if (i > 0) {
result.append(value.substring(0, i));
}
result.append(filtered);
}
} else {
if (filtered == null) {
result.append(value.charAt(i));
} else {
result.append(filtered);
}
}
}
return result == null ? value : result.toString();
}
/**
* 防止SQL注入
* 验证字符类型不能包含特殊字
*/
public static boolean checkNonlicetCharacters(String string) {
boolean flag = true;
// 不许出现单引号
if (string != null && string.indexOf("'") > 0) {
flag = false;
}
return flag;
}
/**
* 防止SQL注入
*/
public static String getValidSQLPara(String string) {
if (string == null || string.length() == 0) {
return string;
}
return string.replaceAll("'", "''");
}
}
JAVA 安全性转码代码(包括sql注入,跨站脚本)
最新推荐文章于 2021-05-31 07:34:39 发布