com.nhncorp.lucy.security.xss.XssPreventer.java Source code

Java tutorial

Introduction

Here is the source code for com.nhncorp.lucy.security.xss.XssPreventer.java

Source

/*
 *   Copyright 2014 Naver Corp.
 *   
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *   
 *      http://www.apache.org/licenses/LICENSE-2.0
 *   
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.nhncorp.lucy.security.xss;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ? ? {@code Cross Site Scripting}  ? {@code String} ?? 
 * Apache Common Lang3?        ? . <br/><br/> 
 * ? XssFilter, XssSaxFilter  ???    ??.  
 * ? ?  ? ? .
 *
 * <pre>
 * ...
 *
 * String clean = XssPreventer.htmlEscaper(dirty);
 * String dirty = XssPreventer.htmlUnEscaper(clean);
 *
 * ...
 * </pre>
 *
 * @author Naver Labs
 *
 */
public class XssPreventer {

    private static final Log LOG = LogFactory.getLog(XssFilter.class);
    private static Pattern escapePattern = Pattern.compile("'");
    private static Pattern unescapePttern = Pattern.compile("&#39;");

    /**
     * ?  XSS({@code Cross Site Scripting}) ??  ?  
     *      ? .
     *  ? XssFilter, XssSaxFilter  ???    ??.  
     * 
     * @param dirty
     *            XSS({@code Cross Site Scripting})? ??  .            
     * @return    .
     */
    public static String escape(String dirty) {

        String clean = StringEscapeUtils.escapeHtml4(dirty);

        if (clean == null) {
            return null;
        }

        Matcher matcher = escapePattern.matcher(clean);

        if (matcher.find()) {
            return matcher.replaceAll("&#39;");
        }

        return clean;
    }

    /**
     * ?  XssPreventer  ?  ? ? . <br/>   
     * 
     * @param clean
     *            XssPreventer   ?.            
     * @return XssPreventer  ? ?.
     */
    public static String unescape(String clean) {

        String str = StringEscapeUtils.unescapeHtml4(clean);

        if (str == null) {
            return null;
        }

        Matcher matcher = unescapePttern.matcher(str);

        if (matcher.find()) {
            return matcher.replaceAll("'");
        }

        return str;
    }
}