Ok, I have found two solutions to this. Here is the first one. Please vote up the solution you like best!
Add back in padding to Base64 encoded strings. Inspiration for this came from http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/
In this solution, the JavaScript stays the same (base64 encode everything) and the server side looks like:
public class CookieDecoder {
private static final Log log = LogFactory.getLog(CookieDecoder.class);
/**
* @param cookieValue The value of the cookie to decode
* @return Returns the decoded string
*/
public String decode(String cookieValue) {
if (cookieValue == null || "".equals(cookieValue)) {
return null;
}
if (!cookieValue.endsWith("=")) {
cookieValue = padString(cookieValue);
}
if (log.isDebugEnabled()) {
log.debug("Decoding string: " + cookieValue);
}
Base64 base64 = new Base64();
byte[] encodedBytes = cookieValue.getBytes();
byte[] decodedBytes = base64.decode(encodedBytes);
String result = new String(decodedBytes);
if (log.isDebugEnabled()) {
log.debug("Decoded string to: " + result);
}
return result;
}
private String padString(String value) {
int mod = value.length() % 4;
if (mod <= 0) {
return value;
}
int numEqs = 4 - mod;
if (log.isDebugEnabled()) {
log.debug("Padding value with " + numEqs + " = signs");
}
for (int i = 0; i < numEqs; i++) {
value += "=";
}
return value;
}
}
On the JavaScript side, you just need to make sure you base64 encode the values:
var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + encodedValue +
"; expires=" + this.expires.toGMTString() +
"; path=" + this.path;