Quellcode durchsuchen

修复字符串无法被反转义问题

RuoYi vor 4 Jahren
Ursprung
Commit
acf8d9719f

+ 23 - 11
ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/html/EscapeUtil.java

@@ -69,26 +69,37 @@ public class EscapeUtil
69 69
      */
70 70
     private static String encode(String text)
71 71
     {
72
-        int len;
73
-        if ((text == null) || ((len = text.length()) == 0))
72
+        if (StringUtils.isEmpty(text))
74 73
         {
75 74
             return StringUtils.EMPTY;
76 75
         }
77
-        StringBuilder buffer = new StringBuilder(len + (len >> 2));
76
+
77
+        final StringBuilder tmp = new StringBuilder(text.length() * 6);
78 78
         char c;
79
-        for (int i = 0; i < len; i++)
79
+        for (int i = 0; i < text.length(); i++)
80 80
         {
81 81
             c = text.charAt(i);
82
-            if (c < 64)
82
+            if (c < 256)
83 83
             {
84
-                buffer.append(TEXT[c]);
84
+                tmp.append("%");
85
+                if (c < 16)
86
+                {
87
+                    tmp.append("0");
88
+                }
89
+                tmp.append(Integer.toString(c, 16));
85 90
             }
86 91
             else
87 92
             {
88
-                buffer.append(c);
93
+                tmp.append("%u");
94
+                if (c <= 0xfff)
95
+                {
96
+                    // issue#I49JU8@Gitee
97
+                    tmp.append("0");
98
+                }
99
+                tmp.append(Integer.toString(c, 16));
89 100
             }
90 101
         }
91
-        return buffer.toString();
102
+        return tmp.toString();
92 103
     }
93 104
 
94 105
     /**
@@ -145,11 +156,12 @@ public class EscapeUtil
145 156
     public static void main(String[] args)
146 157
     {
147 158
         String html = "<script>alert(1);</script>";
159
+        String escape = EscapeUtil.escape(html);
148 160
         // String html = "<scr<script>ipt>alert(\"XSS\")</scr<script>ipt>";
149 161
         // String html = "<123";
150 162
         // String html = "123>";
151
-        System.out.println(EscapeUtil.clean(html));
152
-        System.out.println(EscapeUtil.escape(html));
153
-        System.out.println(EscapeUtil.unescape(html));
163
+        System.out.println("clean: " + EscapeUtil.clean(html));
164
+        System.out.println("escape: " + escape);
165
+        System.out.println("unescape: " + EscapeUtil.unescape(escape));
154 166
     }
155 167
 }