URL Safe Base64 Encoding / Decoding in CFML

by Pete Freitag

ColdFusion / CFML has a builtin function that can convert a string or a binary object to a standard Base64 encoded string: toBase64 and you can decode back to a string using toBinary() and toString() or the binaryDecode() function.

These builtin functions are quite handy, but if you need to pass the encoded value in a URL, or simply want a nicer looking encoding of a value then as of Java 8 there is a builtin class java.util.Base64 which has a URL Safe Base64 encoder implementation. The standard base64 implementation has characters such a / or +, and padding characters =.

Here's how you can use this in CFML assuming you have Java 8 or greater:

function urlSafeBase64Encode(str) {
	return createObject("java", "java.util.Base64").getUrlEncoder().withoutPadding().encodeToString(str.getBytes("UTF-8"));
}

function urlSafeBase64Decode(str) {
	var bytes = createObject("java", "java.util.Base64").getUrlDecoder().decode(str);
	return createObject("java", "java.lang.String").init(bytes);
}

The Fixinator Code Security Scanner for ColdFusion & CFML is an easy to use security tool that every CF developer can use. It can also easily integrate into CI for automatic scanning on every commit.

Comments

Linda Miles

How would you decode it in Javascript? When I try doing the regular base64Decode I get "\u0000\u0000" characters added to the back.