Created
March 28, 2011 00:57
-
-
Save seyan/889827 to your computer and use it in GitHub Desktop.
XSS対策:JavaScriptエスケープメソッド
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.assertEquals; | |
import org.junit.Test; | |
public class EscapeJsTest { | |
/** | |
* 引数で与えられた文字列にHTMLエスケープを行った結果文字列を返す | |
* @param str | |
* @return | |
*/ | |
private static String escapeHTML(String str) { | |
if (str == null) { | |
return null; | |
} | |
StringBuilder sb = new StringBuilder(str.length() * 2); | |
// エスケープの対象サイズを確定する事で、余分なエラーチェックの回数を減らす。 | |
char[] ary = str.toCharArray(); | |
for (int i = 0, length = ary.length; i < length; i++) { | |
char c = ary[i]; | |
if (c == ' ') { // 半角スペース | |
sb.append(" "); | |
} else if (c == '\u00A5') { // ¥サイン | |
sb.append("¥"); | |
} else if (c == '<') { | |
sb.append("<"); | |
} else if (c == '>') { | |
sb.append(">"); | |
} else if (c == '&') { | |
sb.append("&"); | |
} else if (c == '"') { | |
sb.append("""); | |
} else if (c == '\'') { | |
sb.append("'"); | |
} else { | |
sb.append(c); | |
} | |
} | |
return sb.toString(); | |
} | |
/** | |
* 引数で与えられた文字列をJavaScript文字列リテラルとしてエスケープする | |
* @param str | |
* @return | |
*/ | |
private static String escapeJS(String str){ | |
StringBuilder sb = new StringBuilder(str.length() * 2); | |
char[] ary = str.toCharArray(); | |
for(int i=0, length = ary.length; i < length; i++){ | |
char c =ary[i]; | |
if(c == '\\'){ | |
sb.append("\\\\"); | |
} | |
else if(c == '\''){ | |
sb.append("\\\'"); | |
} | |
else if(c == '"'){ | |
sb.append("\""); | |
} | |
else if(c == '\n'){ | |
sb.append("\\\n"); | |
} | |
else{ | |
sb.append(c); | |
} | |
} | |
return sb.toString(); | |
} | |
/** | |
* 引数で与えられた文字列に対し、JS文字列としてエスケープした後、HTMLエスケープする | |
* @param str | |
* @return | |
*/ | |
public static String escapeJavaScript(String str){ | |
return escapeHTML(escapeJS(str)); | |
} | |
@Test | |
public void testEscapeHTML() throws Exception{ | |
assertEquals(escapeJavaScript("abcdefg"), "abcdefg"); | |
assertEquals(escapeJavaScript("試験テスト"), "試験テスト"); | |
assertEquals(escapeJavaScript("name=');alert(document.cookie)\\"), "name=\\');alert(document.cookie)\\\\"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment