Pete Freitag Pete Freitag

URL Safe Base64 Encoding / Decoding in CFML

Published on April 22, 2021
By Pete Freitag
coldfusion

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);
}


coldfusion cfml java

URL Safe Base64 Encoding / Decoding in CFML was first published on April 22, 2021.

If you like reading about coldfusion, cfml, or java then you might also like:

Fixinator

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.


Try Fixinator

CFBreak
The weekly newsletter for the CFML Community


Comments

How would you decode it in Javascript?

When I try doing the regular base64Decode I get "\u0000\u0000" characters added to the back.
by Linda Miles on 05/08/2021 at 5:18:12 PM UTC