Base64 Encoding in Squirrel
Our first program demonstrates base64 encoding and decoding. Here’s the full source code:
Java provides built-in support for base64 encoding/decoding through the java.util.Base64
class.
We start by defining our input string that we’ll encode and decode.
To perform standard base64 encoding, we use Base64.getEncoder().encodeToString()
. This method takes a byte array as input, so we convert our string to bytes using getBytes()
.
For decoding, we use Base64.getDecoder().decode()
. This method returns a byte array, which we then convert back to a string. Note that decoding can throw an IllegalArgumentException
if the input is not valid base64, so we wrap it in a try-catch block.
Java also supports URL-safe base64 encoding and decoding. We use Base64.getUrlEncoder()
and Base64.getUrlDecoder()
for these operations. The process is similar to standard base64, but it uses a slightly different character set that’s safe for use in URLs.
To run the program, compile and execute it:
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing +
vs -
), but they both decode to the original string as desired.
This example demonstrates how to use Java’s built-in base64 encoding and decoding capabilities, which are useful for various tasks such as encoding binary data for transmission over text-based protocols.