Base64 Encoding in Groovy
Groovy provides built-in support for base64 encoding/decoding.
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.
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.