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); }
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:
- ColdFusion Heap / Non-Heap Memory Usage Script
- Serializing CFC's in ColdFusion 8
- Null Java References in CF 6 vs 7
- DNS Query with ColdFusion
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
When I try doing the regular base64Decode I get "\u0000\u0000" characters added to the back.