通用技术 Java--关于自动识别 URL 编码格式并解码

CC · 2016年11月22日 · 最后由 magicyang 回复于 2016年11月23日 · 1685 次阅读

目前测试过程中遇到 URL 编解码问题,在此简单做个小计

目前国内中文用的最多编码格式为 UTF-8 和 GBK 两种方式,GBK 两字节编码,UTF-8 为 1~6 字节编码,其中 GBK 与 UTF-8 有一定的字符集交叉,采用正则方式进行匹配校验

/**
     * 正则方式判断字符编码,默认为UTF-8
     * @param encodeValue
     * @return
     */
    public Boolean getURLEncode(String encodeValue){
        //utf8编码 字符集
        Pattern utf8Pattern = Pattern.compile("^([\\x00-\\x7f]|[\\xc0-\\xdf][\\x80-\\xbf]|[\\xe0-\\xef][\\x80-\\xbf]{2}|[\\xf0-\\xf7][\\x80-\\xbf]{3}|[\\xf8-\\xfb][\\x80-\\xbf]{4}|[\\xfc-\\xfd][\\x80-\\xbf]{5})+$");
        //通用字符集(utf-8和GBK)
        Pattern publicPattern = Pattern.compile("^([\\x01-\\x7f]|[\\xc0-\\xdf][\\x80-\\xbf])+$");
        /**
         * 通用字符集判断
         */
        Matcher publicMatcher = publicPattern.matcher(encodeValue);
        if(publicMatcher.matches()){
            return false;
        }

        Matcher matcher = utf8Pattern.matcher(encodeValue);
        if(matcher.matches()){
            return true; 
        }else {
            return false;
        }
    }
/**
     * 解码
     * @param urlInfo
     * @param encodeStr
     * @return
     */
    public String getUrlDecode(String urlInfo,String encodeStr){
        String result = "";
        if(null == urlInfo){
            return result;
        }       
        try{
            result = URLDecoder.decode(urlInfo, encodeStr);
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return result;
    }
@Test
    public void testAutoURLDecode(){
        //UTF-8编码
        String str0 = "cntaobao%C3%FB%D1%EFy";
        //GBK编码
        String str1 = "cntaobao%e5%90%8d%e6%89%acy";
        String encodeStr0 = "UTF-8";
        String encodeStr1 = "GBK";

        if(getURLEncode(str0).equals(true)){
            System.out.println(getUrlDecode(str0, encodeStr0));
        }else {
            System.out.println(getUrlDecode(str0, encodeStr1));
        }

    }

结果输出:
cntaobao 名扬 y

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 3 条回复 时间 点赞

感觉这个方式并不是最好的. 编码的漏洞还是挺多的. 以前流行 GBK 的时候竟然有人用半个汉字的编码来误导程序. 实现注入.
当有半个汉字的时候, 编码会把后面的字符连接到一起认为是一个汉字. 所以半个汉字 +"之类的组合就变成了一个汉字.导致原有的 html 字符错乱. 这也是早期测试用例设计的时候很偏门又很有意思的一个场景.

CC #2 · 2016年11月23日 Author

#1 楼 @seveniruby 是的,两者结合交叉的地方就是个很大的漏洞,暂时没有看到好的办法去自动识别对应的编码方式,其次现在提供的解码方法中,比如用 UTF-8 解码 GBK 的 URL,没有抛出异常,所以暂时折中处理

哎,URL 就是一个大坑,URI,URL,STRING,有多少转义可能不一致的。
真要弄明白,看协议,我个人表示实在没那个精力。。。。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册