[Java] Java防止路径操控和命令注入 →→→→→进入此内容的聊天室

来自 , 2019-08-09, 写在 Java, 查看 187 次.
URL http://www.code666.cn/view/6195f47d
  1. public class Test  
  2. {  
  3.     public static void main(String[] args)  
  4.     {  
  5.         System.out.println(getSafeCommand("abcd&efg"));  
  6.         System.out.println(getSafePath("abcd/efg"));  
  7.     }  
  8.  
  9.     /**
  10.      * Get the safe path
  11.      * @param filePath Enter the path
  12.      * @return Safe path
  13.      */  
  14.     public static String getSafePath(String filePath)  
  15.     {  
  16.         // return safe path  
  17.         StringBuffer safePath = new StringBuffer();  
  18.         // safe path white list  
  19.         String whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-=[];',. ~!@#$%^&*()_+\"{}|:<>?";  
  20.         char[] safePathChars = filePath.toCharArray();  
  21.  
  22.         for (int i = 0, length = safePathChars.length; i < length; i++)  
  23.         {  
  24.             int whiteListIndex = whiteList.indexOf(safePathChars[i]);  
  25.             if (-1 == whiteListIndex)  
  26.             {  
  27.                 return safePath.toString();  
  28.             }  
  29.             safePath.append(whiteList.charAt(whiteListIndex));  
  30.         }  
  31.         return safePath.toString();  
  32.     }  
  33.  
  34.     /**
  35.      * Get the safe command
  36.      * @param command Enter the command
  37.      * @return Safe command
  38.      */  
  39.     public static String getSafeCommand(String command)  
  40.     {  
  41.         // return safe command  
  42.         StringBuffer safeCommand = new StringBuffer();  
  43.         // safe command white list  
  44.         String whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-=[]\\',./ ~!@#$%^*()_+\"{}:<>?";  
  45.         char[] safeCommandChars = command.toCharArray();  
  46.  
  47.         for (int i = 0, length = safeCommandChars.length; i < length; i++)  
  48.         {  
  49.             int whiteListIndex = whiteList.indexOf(safeCommandChars[i]);  
  50.             if (-1 == whiteListIndex)  
  51.             {  
  52.                 return safeCommand.toString();  
  53.             }  
  54.             safeCommand.append(whiteList.charAt(whiteListIndex));  
  55.         }  
  56.         return safeCommand.toString();  
  57.     }  
  58. }  
  59.  
  60. //java/6689

回复 "Java防止路径操控和命令注入"

这儿你可以回复上面这条便签

captcha