COOKIE值中包括等号

系统中有一些值使用BASE64编码后存储在COOKIE中,当编码后的字符串最后有一个或者两个等号(=)时,使用Request.getCookies().getValue()会丢失等号,再BASE64解码时产生错误.

https://issues.apache.org/bugzilla/show_bug.cgi?id=44679,可以看到这个链接里面的讨论.

里面提到:

org.apache.tomcat.util.http.ServerCookie.ALLOW_EQUALS_IN_VALUE system property
that was introduced in Tomcat 6.0.24.  Looks like Mark has seen the light. :)
I just wanted to update this issue so everyone that needs this feature is aware
of it.

处理方法:
1) 直接从Http Head里面取Cookie的值,然后自己解析,保留value中的等号.(Cookie值的格式: name=value;name2=value2;name3=value3

2) Base64解码前,计算长度,补充等号后再解码

public static String decodeBase64(String s) {
        switch(s.length()%4) {
            case 3:
                s+= "==="; break; // 注:其实只需要补充一个或者两个等号,不存在补充三个等号的情况
            case 2:
                s+= "=="; break;
            case 1:
                s+= "="; break;
            default:
        }
        return new BASE64Encoder().decode(s.getBytes())););
    }

    public static String encodeBase64(String s) {
        String encoded = BASE64Encoder().encode(s.getBytes())));
        return encoded.replaceAll("[\n=]", "");
    }

备注:

Cookie规范介绍

 

你可能感兴趣的:(base64,cookie)