Encoding java Cookie value

2019-04-27 02:27发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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()



回答4:

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



回答5:

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'));
?>