JAVA 安全性转码代码(包括sql注入,跨站脚本)

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("'", "''");
    }

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值