Java Encoding Cookie Value

How should you encode the actual value for a Java cookie? I cannot pass characters like '=' or any character outside of US-ASCII.

/ Br joynes

+6
java encoding cookies
source share
5 answers

It doesn't really matter as usual, but usually Base64 should work well.

Warning note:

It looks like you want to save arbitrary settings in a cookie. This is usually not a good idea, because cookies (like all client inputs) are not trusted. Consider storing server-side data under some generated (random!) Identifier and placed in a cookie. Thus, people cannot bypass access restrictions or enter arbitrary data into your system using processed cookies.

If you cannot use this approach, treat the cookie values ​​as an untrusted input and check it as usual.

Edit:

Base64 is not suitable as it uses "=" which Java cookies do not support. Use more likely

java.net.URLEncoder.encode 

which uses only cookie matching characters.

+8
source share

Use the hex or URL-safe version of Base64 to encode if you have unsafe characters. Normal Base64 cannot be used as cookie values. The old Tomcat used to resolve illegal characters as "=", but newer versions are now starting to apply cookie rules.

+5
source share

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

To create a base64 baseless encoder java.util.Base64.getEncoder().withoutPadding()

To create a Base64 no deposit decoder java.util.Base64.getDecoder()

+1
source share

as I understand it, you need something like this String name = "Zhenya"; Cookie cookie = new Cookie ("name", new line (name.getBytes ("cp1251"), "utf8")); response.addCookie (cookies);

-2
source share

my php cookie encoding 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')); ?> 
-3
source share

All Articles