Base64 Encoding
Encode and decode data using Base64 format. Useful for binary data in text-based contexts like JSON, URLs, and HTTP headers.
Overview
Base64 encoding represents binary data in ASCII format. It's commonly used when:
- Embedding binary data in JSON or XML
- Storing binary data in text-based formats
- Transmitting binary data over protocols that only support text
- Encoding small files or images in HTML/CSS
Static Methods
Base64.encode(value)
Encodes a string to Base64 format using standard encoding (with + and / characters).
encoded = Base64.encode("Hello, World!")
# "SGVsbG8sIFdvcmxkIQ=="
# Encoding numbers and special characters
Base64.encode("123"); # "MTIz"
Base64.encode("\n\t"); # "CQo="
Base64.decode(value)
Decodes a Base64 string back to the original string. Returns an error for invalid Base64.
decoded = Base64.decode("SGVsbG8sIFdvcmxkIQ==")
# "Hello, World!"
# Decoding preserves original content
original = "Hello, World!"
round_trip = Base64.decode(Base64.encode(original))
assert_eq(round_trip, original);
Base64.urlsafe_encode(value)
Encodes to the URL-safe alphabet (RFC 4648 §5): - and _ replace + and /, and the output is never padded with =. This is the form required by JWS, JWK, PKCE and JWK thumbprints, so there is deliberately no padding option.
# Safe to drop straight into a URL or a JWT segment
Base64.urlsafe_encode("Hello, World!"); # "SGVsbG8sIFdvcmxkIQ"
# PKCE S256 challenge. Crypto.sha256 returns hex, so decode to raw
# bytes first — encoding the hex *text* yields a different, wrong value.
challenge = Base64.urlsafe_encode(Hex.decode(Crypto.sha256(code_verifier)))
Base64.urlsafe_decode(value)
Decodes URL-safe Base64. Padding is optional — producers in the wild disagree on whether to strip =, so both forms are accepted. Like Base64.decode, it returns a String when the bytes are valid UTF-8 and an array of byte integers otherwise.
Base64.urlsafe_decode("SGVsbG8sIFdvcmxkIQ"); # "Hello, World!"
Base64.urlsafe_decode("SGVsbG8sIFdvcmxkIQ=="); # same — padding tolerated
# Reading a JWT header without verifying it
header = JSON.parse(Base64.urlsafe_decode(token.split(".")[0]))
Common Use Cases
Embedding Binary in JSON
Encode binary data like images or files to include in JSON payloads.
image_data = slurp("avatar.png")
base64_image = Base64.encode(image_data)
json_response = json_stringify({
"avatar": base64_image,
"filename": "avatar.png"
});
API Authentication
Create Basic Auth credentials for HTTP requests.
def basic_auth_header(username: String, password: String) -> String
credentials = username + ":" + password
encoded = Base64.encode(credentials) "Basic " + encoded
end
# Usage
header = basic_auth_header("user", "secret123")
# "Basic dXNlcjpzZWNyZXQxMjM="
Data URLs
Create data URLs for embedding small files directly in HTML.
svg_content = slurp("icon.svg")
base64_svg = Base64.encode(svg_content)
data_url = "data:image/svg+xml;base64," + base64_svg
# "data:image/svg+xml;base64,PHN2Zz4="
Error Handling
Base64.decode() will return an error if:
- The input contains invalid Base64 characters
- The input has incorrect padding
- The decoded bytes are not valid UTF-8
# Invalid Base64 (wrong padding)
try
Base64.decode("invalid==")
catch e
print("Error: " + e) # "Error: Invalid Base64: ..."
end
# Valid Base64 with proper error handling
def safe_decode(input: String) -> String
try
return Base64.decode(input)
catch e
print("Failed to decode: " + e)
""
end
end