encode_base64#

Encode a byte string as standard RFC 2045 base64, optionally wrapping at 76 characters.

Synopsis#

use MIME::Base64;
my $encoded = encode_base64($bytes);         # wrapped at 76, "\n"-terminated
my $oneline = encode_base64($bytes, "");     # no wrapping, no trailing EOL
my $crlf    = encode_base64($bytes, "\r\n"); # MIME-style CRLF wrapping

What you get back#

A plain (non-UTF8) ASCII string containing only characters from [A-Za-z0-9+/=] plus the caller’s end-of-line sequence. With the default "\n" terminator, every 76-character line — including the final short one — ends with "\n". Pass "" to get a single unbroken token with no trailing newline; useful for HTTP headers, credential strings, and anywhere a single atomic value is expected. The output always pads to a multiple of four characters with =.

Examples#

encode_base64("Aladdin:open sesame");

## "QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n"

encode_base64("Aladdin:open sesame", "");

## "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

encode_base64("\x00\x00\x00");

## "AAAA\n"

Edge cases#

  • Empty input returns the empty string.

  • A single character (or any input whose length is not a multiple of 3) is padded with = so the output length is a multiple of four.

  • Binary bytes are encoded as-is; there is no byte-order or encoding transformation.

  • Input with code points above 255 is a programming error in the caller; base64 is defined over octets only. Encode to UTF-8 first if the source is a text string.

Differences from upstream#

Fully compatible with upstream MIME::Base64 3.16.

See also#

  • decode_base64 — the inverse operation.

  • encode_base64url — the URL-safe variant, no padding, no wrapping.

  • encoded_base64_length — size the output without encoding.