Base64 Encoding in Groovy

Groovy provides built-in support for base64 encoding/decoding.

import groovy.json.StringEscapeUtils

// Here's the string we'll encode/decode.
def data = "abc123!?\$*&()'-=@~"

// Groovy supports base64 encoding/decoding through the
// java.util.Base64 class. Here's how to encode using the standard encoder.
def sEnc = data.bytes.encodeBase64().toString()
println sEnc

// Decoding may return an error, which you can check
// if you don't already know the input to be well-formed.
def sDec = new String(sEnc.decodeBase64())
println sDec
println()

// This encodes/decodes using a URL-compatible base64 format.
def uEnc = data.bytes.encodeBase64Url().toString()
println uEnc
def uDec = new String(uEnc.decodeBase64Url())
println uDec

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

$ groovy base64_encoding.groovy
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

In Groovy, we use the java.util.Base64 class which is part of the Java standard library. Groovy provides convenient methods on strings and byte arrays to perform base64 encoding and decoding.

The encodeBase64() and decodeBase64() methods are used for standard base64 encoding and decoding, while encodeBase64Url() and decodeBase64Url() are used for URL-safe base64 encoding and decoding.

Note that in Groovy, we don’t need to explicitly import the java.util.Base64 class as it’s automatically available. We also don’t need to catch exceptions when decoding as Groovy will automatically throw a runtime exception if the input is not valid base64.