使用安全的HTML编码函数解决XSS攻击

2018/03/26

使用安全的HTML编码函数解决XSS攻击

编码分为很多种,针对HTML代码的编码方式是HtmlEncode

一般来说,要对抗XSS,在编码函数中,至少要实现下列内容:

&-->&

<-->&lt;

>-->&ht;

"-->&quot;

'-->&#27;

/-->&#x2F;

以下是使用JAVA代码的实现形式:

public static String htmlEncode(String str){
    String[] arr="&@<@>@\"@'@/".split("@");
    String[] code="&amp;@&lt;@&gt;@&quot;@&#x27;@&#x2F;".split("@");
    try{
        for(int i=0;i<arr.length;i++){
            str=str.replaceAll(arr[i],code[i]);
        }
    }catch (NullPointerException e){

    }

    return str;

}


Post Directory