替换字符串中指定字符串(不区分大小写)

背景:修补Http请求中夹带script攻击的
apache自带的防止XSS攻击的util:StringEscapeUtils,但是不能替换script(攻击者会使用不同方式的大小写组合)

public static void main(String[] args) {
		String str = "<sCript>HTTP://www</sCripT>.<script>for</SCRIPT>ta.</SCripT>com/.";
		String temp = str.toLowerCase(); //先转换成小写进行精确匹配
        Set<String> senSet= new HashSet<String>();
        senSet.add("</script>");
        senSet.add("<script>");
        for(String regex:senSet) {
        	if(temp.contains(regex)) {
        		temp = temp.replaceAll(regex, "");
        	}
        }
        System.err.println(temp);
        
        
        for(String regex:senSet) {
        	//不区分大小写匹配
        	Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
        	Matcher matcher = pattern.matcher(str);
        	//不区分大小写匹配
        	while (matcher.find()) {
               //截取字符串,临时保存匹配到的字符串
               //起始位置和结束位置都要加一个len长度
               String match = str.substring(matcher.start(), matcher.end());
               //替换首次找到的字符串(替换成同等长度的小写)
               str = str.replaceFirst(match, regex);
              
             }
        }
        System.out.println("*********"+str);
        for(String key:senSet) {
        	str = str.replaceAll(key, "");
        }
        System.out.println("======="+str);
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章