1

I am working on setting a cookie in a browser, and I'd like to base64 encode a string of data as the value. The call to base 643 encode is trivial

public static String encodeToBase64(String input) {
    return new String(Base64.encodeBase64(input.getBytes()));
}

But I'm wondering, can I include a + or an = in a cookie? My cookie generation device looks something like this

String parameterData = Base64Utils.encodeToBase64(JsonUtils.objectToJson(parameters));
String expires = epochMillisToExpirationString(getExpiration());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("data=");
stringBuilder.append(parameterData);

Has anyone seen this break down? Is there any documentation on Cookie standards that discuss this sort of issue?

David Williams
  • 8,388
  • 23
  • 83
  • 171

3 Answers3

2

If you are passing the data within a URI parameter you will probably want to uri-encode the data, escaping reserved special characters.

This question/answer thread should tell you all you need to know about how.

(!) Remember to uri-decode it next time you read it before using it internally.

Community
  • 1
  • 1
Aaron Cronin
  • 2,093
  • 14
  • 13
2

It's not cookie specific, but Base64 has dialects. For example,

To use standard Base64 in URL requires encoding of '+', '/' and '=' characters into special percent-encoded hexadecimal sequences ('+' = '%2B', '/' = '%2F' and '=' = '%3D'). Remembering to decode those sequences when you read it in again.

Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You should be fine, I've seen SAML response values contain special characters like this before. When in doubt encode the value :) Are you having odd results?