开发者

Encoding java Cookie value

How should you encode the actual value for a Java Cookie object? I cannot pass characters like '=' or any character outside US-ASC开发者_StackOverflowII.

/Br joynes


It does not really matter how, but usually Base64 should work well.

A cautionary note:

This sounds like you want to store arbitrary settings in a cookie. This is generally not a good idea, because cookies (like all client input) are untrusted. Consider storing the data server-side under some generated (random!) identifier, and putting that into the cookie. That way people cannot circumvent access restrictions or inject arbitrary data into your system through manipulated cookies.

If you cannot use this approach, treat cookie values as untrusted input and verify it as usual.

Edit:

Base64 is not appropriate, as it uses "=", which Java cookies do not support. Rather use

java.net.URLEncoder.encode

which only uses characters appropriate for cookies.


Use hex or URL-safe version of Base64 to encode it if you have unsafe chars. Regular Base64 can't be used as cookie values. Older Tomcat used to allow illegal chars in it like "=" but newer versions start to enforce the cookie rules now.


I ended up using Base64 encoding without the padding. This means that trailing equal signs are omitted, so the problem is solved.

To create a padding-free Base64 encoder java.util.Base64.getEncoder().withoutPadding()

To create a padding-free Base64 decoder java.util.Base64.getDecoder()


as i understand you need something like this String name="Женя";Cookie cookie=new Cookie("name",new String(name.getBytes("cp1251"),"utf8"));response.addCookie(cookie);


my php cookie value encode function:

<?
function encode_cookie_value($value)
         {return strtr($value,
                       array_combine(str_split($tmp=",; \t\r\n\013\014"),
                                     array_map('rawurlencode', str_split($tmp))
                                    )
                      );
         }
setrawcookie('kk', encode_cookie_value('jk=jk?jk-/":jk;jk jk,jk'));
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜