Base64 Encoding in Crystal
Our first program will demonstrate base64 encoding and decoding. Here’s the full source code:
To run the program, save it as base64_encoding.cr
and use the crystal
command:
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.
Crystal provides built-in support for base64 encoding/decoding through the Base64
module. The strict_encode
and strict_decode
methods are used for standard base64 encoding, while urlsafe_encode
and urlsafe_decode
are used for URL-safe encoding.
Note that in Crystal, the decoding methods return Bytes
, which we convert to a String
using String.new()
. Also, the decoding methods may raise an exception if the input is not valid base64, which we handle with a begin-rescue block.