Skip to Content
Course content

71: Base64 Encoding and Decoding

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this bug more times than I care to admit, usually during a late-night debugging session where someone is trying to integrate a third-party API. You're following the documentation perfectly, your credentials are correct, but the server keeps returning a 401 Unauthorized. Here is a snippet of the kind of code that causes it:

require 'base64'

user_pass = "admin:secret123"
encoded_creds = Base64.encode64(user_pass)

# Let's simulate sending this in an HTTP header
puts "Authorization: Basic #{encoded_creds}"
# Output: 
# Authorization: Basic YWRtaW46c2VjcmV0MTIz
# 

At first glance, it looks fine. The string is encoded, and the output looks like standard Base64. But if you actually inspect that encoded_creds variable using p instead of puts, you'll see the culprit:

p encoded_creds 
# Output: "YWRtaW46c2VjcmV0MTIz\n"

The Invisible Newline Bug

The issue is that Ruby's Base64.encode64 method follows the RFC 2045 standard, which automatically inserts a newline character every 60 characters, and always adds a newline at the end. While this was great for old email systems that had strict line-length limits, it's a nightmare for modern HTTP headers or JSON payloads. The API server receives that \n as part of the token, fails to decode it, and rejects your request.

Switching to Strict Encoding

When you're working with APIs, tokens, or database keys, you almost always want "strict" encoding. Ruby provides a specific method for this that omits those pesky line breaks. Here is the fix:

require 'base64'

user_pass = "admin:secret123"
# Use strict_encode64 instead of encode64
encoded_creds = Base64.strict_encode64(user_pass)

p encoded_creds 
# Output: "YWRtaW46c2VjcmV0MTIz" (No newline!)

By using strict_encode64, you're generating a single continuous string. It's cleaner, it's predictable, and it's what 99% of modern web services actually expect.

Handling the Reverse Process

Decoding is generally more straightforward because the Base64.decode64 method is forgiving; it typically ignores those newlines if they happen to be there. However, for consistency and safety, I recommend using strict_decode64 if you know the input should be a strict string.

encoded = "YWRtaW46c2VjcmV0MTIz"
decoded = Base64.strict_decode64(encoded)
puts decoded # => "admin:secret123"

One thing to keep in mind: Base64 isn't encryption. I can't stress this enough. It's just a way of representing binary data as text. If you're using Base64 to "hide" a password in a client-side script, you aren't securing anything—you're just obfuscating it. Anyone with a browser console can decode a Base64 string in seconds.

When to actually use binary encoding

You'll most often reach for the Base64 module when you need to transmit something that isn't plain text—like a small image file or a compiled PDF—inside a format that only supports text (like JSON). Since binary data can contain bytes that would be interpreted as control characters or end-of-file markers, encoding it into the 64-character ASCII set ensures it arrives at the destination exactly as it left.




📋 Practical Task

Exercise: Basic Auth Header Generator

You are building a helper method for an API client. Your goal is to create a method called generate_auth_header(username, password) that returns a properly formatted HTTP Authorization string.

  • The method should take two arguments: username and password.
  • It must combine them into a string with a colon separator (username:password).
  • It must encode that string using strict Base64 encoding.
  • The final return value should be the string: "Basic [encoded_string]".

Test your code with: generate_auth_header("ruby_dev", "p@ssword123"). It should return "Basic cnVieV9kZXY6cEBzc3dvcmQxMjM=" without any hidden newline characters.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.