Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-ASCII.

/Br joynes

like image 414
joynes Avatar asked Oct 07 '09 13:10

joynes


2 Answers

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.

like image 116
sleske Avatar answered Sep 18 '22 12:09

sleske


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.

like image 30
ZZ Coder Avatar answered Sep 20 '22 12:09

ZZ Coder