Base64 Encoding in Crystal

Our first program will demonstrate base64 encoding and decoding. Here’s the full source code:

require "base64"

# This example uses the Base64 module for encoding and decoding.

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

# Here's how to encode using the standard encoder.
s_enc = Base64.strict_encode(data)
puts s_enc

# Decoding may raise an exception, which you can rescue
# if you don't already know the input to be well-formed.
begin
  s_dec = Base64.strict_decode(s_enc)
  puts String.new(s_dec)
rescue
  puts "Decoding failed"
end

puts

# This encodes/decodes using a URL-safe base64 format.
u_enc = Base64.urlsafe_encode(data)
puts u_enc
begin
  u_dec = Base64.urlsafe_decode(u_enc)
  puts String.new(u_dec)
rescue
  puts "Decoding failed"
end

To run the program, save it as base64_encoding.cr and use the crystal command:

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

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

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.