防止路径操控,命令注入

来源:互联网 发布:大数据时代 txt 完整版 编辑:程序博客网 时间:2024/05/16 05:02
public class Test{    public static void main(String[] args)    {        System.out.println(getSafeCommand("abcd&efg"));        System.out.println(getSafePath("abcd/efg"));    }    /**     * Get the safe path     * @param filePath Enter the path     * @return Safe path     */    public static String getSafePath(String filePath)    {        // return safe path        StringBuffer safePath = new StringBuffer();        // safe path white list        String whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-=[];',. ~!@#$%^&*()_+\"{}|:<>?";        char[] safePathChars = filePath.toCharArray();        for (int i = 0, length = safePathChars.length; i < length; i++)        {            int whiteListIndex = whiteList.indexOf(safePathChars[i]);            if (-1 == whiteListIndex)            {                return safePath.toString();            }            safePath.append(whiteList.charAt(whiteListIndex));        }        return safePath.toString();    }    /**     * Get the safe command     * @param command Enter the command     * @return Safe command     */    public static String getSafeCommand(String command)    {        // return safe command        StringBuffer safeCommand = new StringBuffer();        // safe command white list        String whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-=[]\\',./ ~!@#$%^*()_+\"{}:<>?";        char[] safeCommandChars = command.toCharArray();        for (int i = 0, length = safeCommandChars.length; i < length; i++)        {            int whiteListIndex = whiteList.indexOf(safeCommandChars[i]);            if (-1 == whiteListIndex)            {                return safeCommand.toString();            }            safeCommand.append(whiteList.charAt(whiteListIndex));        }        return safeCommand.toString();    }}

输出结果:

abcdabcd

防止路径操控:预防路径跨越,路径中不能出现/../,安全字符中不能出现 /  \ 字符

防止命令注入:预防命令批量执行,命令中不能出现 &  |  ;

原创粉丝点击