Skip to content

base64

Base64 encoding and decoding (RFC 4648).

Alphabets

Symbol Description
:STANDARD: Standard alphabet, using + and / (RFC 4648 section 4)
:URL: URL-safe alphabet, using - and _ (section 5)
:AUTO: Decoding only; detect the alphabet from the input

Types

TypeDescription
DecodeError Raised when decode is given invalid base64.
DecodeValue A value returned by decode.
EncodeValue A value accepted by encode.

DecodeValue = Bin

A value returned by decode.

EncodeValue = (Str | Bin)

A value accepted by encode.

Functions

decode text … -> DecodeValue

Decodes base64 text and returns the raw bytes.

By default both alphabets and any amount of padding are accepted. Specifying alphabet: or pad: makes decoding strict in that respect.

Parameters

NameTypeDescription
text (Str | Bin) Base64 text to decode.
:alphabet? (:STANDARD: | :URL: | :AUTO:) Alphabet; default :AUTO:.
:pad? Bool Required padding; default none.
:alphabet

:AUTO: uses the alphabet of the first -, _, +, or / in the input; a character of the other alphabet is then invalid. Input containing none of them decodes identically under both.

:pad

When pad: is omitted, canonical padding and any lesser amount — including none — are accepted. pad: true requires canonical padding; pad: false requires that padding be absent.

Errors

DecodeError if the input is not valid base64.

Example

assert_eq (decode "aGVsbG8=") b"hello"
assert_eq (decode "aGVsbG8") b"hello"
assert_eq (decode $ encode "hello") b"hello"
assert_eq (decode "-_8" alphabet: :URL: pad: false) b"\xfb\xff"

encode data … -> Str

Encodes a string or binary value as base64 text.

Parameters

NameTypeDescription
data EncodeValue Data to encode.
:alphabet? (:STANDARD: | :URL:) Alphabet; default :STANDARD:.
:pad? Bool Whether to emit padding; default depends on alphabet:.
:pad

pad: defaults to true for :STANDARD: and false for :URL:, since URL-safe base64 is conventionally unpadded (for example in JSON Web Signatures, RFC 7515). Pass pad: explicitly to override.

Example

assert_eq (encode "") ""
assert_eq (encode "hello") "aGVsbG8="
assert_eq (encode b"hello") "aGVsbG8="
assert_eq (encode b"\xfb\xff") "+/8="
assert_eq (encode b"\xfb\xff" alphabet: :URL:) "-_8"
assert_eq (encode "hello" pad: false) "aGVsbG8"
Open in playground