more efficient html sanitization

auto-update
Zlatin Balevsky 2021-09-29 16:06:35 +01:00
parent 3e268498cd
commit cb7f251a84
No known key found for this signature in database
GPG Key ID: A72832072D525E41
1 changed files with 14 additions and 7 deletions

View File

@ -1,17 +1,24 @@
package com.muwire.gui;
public class HTMLSanitizer {
private static final String escapeChars[] = {"&", "\"", "<", ">"}; //, "'"}; // apostrophe not supported
private static final String escapeCodes[] = {"&amp;amp;", "&amp;quot;", "&amp;lt;", "&amp;gt;", "&amp;apos;"};
private static final String escapedCodes[] = {"&amp;", "&quot;", "&lt;", "&gt;"}; //, "&apos;"}; apostrophe not supported
public static String sanitize(String s) {
if (s == null)
return null;
String escaped = s;
for (int i = 0; i < escapeChars.length; i++) {
escaped = escaped.replace(escapeChars[i], escapedCodes[i]);
StringBuilder sb = new StringBuilder(s.length() * 2 + 26);
sb.append("<html><body>");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch(c) {
case '&': sb.append("&amp;"); break;
case '\"': sb.append("&quot;"); break;
case '<' : sb.append("&lt;"); break;
case '>' : sb.append("&gt;"); break;
default :
sb.append(c);
}
}
return "<html><body>" + escaped + "</body></html>";
sb.append("</body></html>");
return sb.toString();
}
}