Base64 Encode & Decode in Ruby

Encode or decode below — it runs locally in your browser — then grab the canonical Ruby code. Ruby's standard-library Base64 module has three encoders, and the one that trips people up is encode64: it inserts newlines. Reach for strict_encode64 instead.

INPUT
OUTPUT
Type or paste to encode / decode

Encode and decode a string

Require the module, then use the strict_ variants for clean, RFC 4648 output:

require 'base64'

# Encode
encoded = Base64.strict_encode64("Hello, world!")
puts encoded  # "SGVsbG8sIHdvcmxkIQ=="

# Decode
decoded = Base64.strict_decode64("SGVsbG8sIHdvcmxkIQ==")
puts decoded  # "Hello, world!"

Tip: Use strict_encode64, not plain encode64. encode64 inserts a newline every 60 characters (plus a trailing one), which breaks Base64 strings in JSON, HTTP headers, and URLs.

URL-safe Base64

For JWTs, URLs, and filenames, use the URL-safe alphabet (- and _ instead of + and /), with padding turned off:

require 'base64'

data = "data for a URL: a+b/c=d"

# URL-safe encode, no padding
encoded = Base64.urlsafe_encode64(data, padding: false)
puts encoded  # No +, /, or = characters

# URL-safe decode
decoded = Base64.urlsafe_decode64(encoded)
puts decoded  # "data for a URL: a+b/c=d"

Note: Base64 is a default gem (Ruby 3.4+)

The Base64 module ships with Ruby, but as of Ruby 3.4 it became a default gem that is no longer auto-loaded everywhere. If you hit a LoadError, add it to your Gemfile:

# Gemfile
gem "base64"

Then run bundle install. A plain require 'base64' still works in most scripts today.

Frequently asked questions

How do I Base64 encode a string in Ruby?

Add require 'base64', then Base64.strict_encode64("Hello, world!") returns "SGVsbG8sIHdvcmxkIQ==".

How do I Base64 decode in Ruby?

Base64.strict_decode64("SGVsbG8sIHdvcmxkIQ==") returns "Hello, world!"; it rejects invalid characters, while decode64 is lenient.

What's the difference between encode64 and strict_encode64?

encode64 adds a newline every 60 characters and a trailing one; strict_encode64 emits clean RFC 4648 output with no line breaks. Prefer strict_encode64.

How do I do URL-safe Base64?

Use Base64.urlsafe_encode64(data, padding: false) and urlsafe_decode64, which use the - and _ alphabet.

Need image, file, or URL-safe modes?

The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.

Open base64.dev →