com.ludii.excel.utils.EncodeUtils Maven / Gradle / Ivy
/*
* Copyright (c) 2005-2012 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.ludii.excel.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 封装各种格式的编码解码工具类.
* 1.Commons-Codec的 hex/base64 编码
* 2.自制的base62 编码
* 3.Commons-Lang的xml/html escape
* 4.JDK提供的URLEncoder
*
* @author calvin
* @version 2013-01-15
*/
class EncodeUtils {
private static final Logger logger = LoggerFactory.getLogger(EncodeUtils.class);
/**
* 预编译XSS过滤正则表达式
*/
private final static List XSS_PATTERNS;
static {
XSS_PATTERNS = new ArrayList<>();
XSS_PATTERNS.add(Pattern.compile("(<\\s*(script|link|style|iframe)([\\s\\S]*?)(>|\\s*\\1\\s*>))|(\\s*(script|link|style|iframe)\\s*>)", Pattern.CASE_INSENSITIVE));
XSS_PATTERNS.add(Pattern.compile("\\s*(href|src)\\s*=\\s*(\"\\s*(javascript|vbscript):[^\"]+\"|'\\s*(javascript|vbscript):[^']+'|(javascript|vbscript):[^\\s]+)\\s*(?=>)", Pattern.CASE_INSENSITIVE));
XSS_PATTERNS.add(Pattern.compile("\\s*on[a-z]+\\s*=\\s*(\"[^\"]+\"|'[^']+'|[^\\s]+)\\s*(?=>)", Pattern.CASE_INSENSITIVE));
XSS_PATTERNS.add(Pattern.compile("(eval\\((.*?)\\)|xpression\\((.*?)\\))", Pattern.CASE_INSENSITIVE));
XSS_PATTERNS.add(Pattern.compile("^(javascript:|vbscript:)", Pattern.CASE_INSENSITIVE));
}
/**
* XSS 非法字符过滤,内容以开头的用以下规则(保留标签)
*
* @author ThinkGem
*/
public static String xssFilter(String text) {
String oriValue = StringUtils.trim(text);
if (text != null) {
String value = oriValue;
for (Pattern pattern : XSS_PATTERNS) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
value = matcher.replaceAll(StringUtils.EMPTY);
}
}
// 如果开始不是HTML,XML,JOSN格式,则再进行HTML的 "、<、> 转码。
// HTML
//noinspection AlibabaAvoidComplexCondition,AlibabaUndefineMagicConstant
if (!StringUtils.startsWithIgnoreCase(value, "")
// XML
&& !StringUtils.startsWithIgnoreCase(value, "':
sb.append(">");
break;
case '<':
sb.append("<");
break;
case '\'':
sb.append("'");
break;
case '\"':
sb.append(""");
break;
default:
sb.append(c);
break;
}
}
value = sb.toString();
}
if (logger.isInfoEnabled() && !value.equals(oriValue)) {
logger.info("xssFilter: {} <=<=<= {}", value, text);
}
return value;
}
return null;
}
}