Base64 Encoding in Ruby

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

require 'base64'

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

# Ruby supports both standard and URL-compatible
# base64. Here's how to encode using the standard
# encoder.
s_enc = Base64.strict_encode64(data)
puts s_enc

# Decoding may raise an error, which you can rescue
# if you don't already know the input to be
# well-formed.
s_dec = Base64.strict_decode64(s_enc)
puts s_dec
puts

# This encodes/decodes using a URL-compatible base64
# format.
u_enc = Base64.urlsafe_encode64(data)
puts u_enc
u_dec = Base64.urlsafe_decode64(u_enc)
puts u_dec

To run the program, save it as base64_encoding.rb and use the ruby command:

$ ruby base64_encoding.rb
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.

In Ruby, the Base64 module is part of the standard library, so we don’t need to install any additional gems. The strict_encode64 and strict_decode64 methods are used for standard base64 encoding and decoding, while urlsafe_encode64 and urlsafe_decode64 are used for URL-safe base64 encoding and decoding.

Ruby’s Base64 module automatically handles the conversion between strings and byte arrays, so we don’t need to explicitly convert between them like in some other languages.