Tabular IQ

Overview

The Base64 class provides basic ability to encode and decode strings using base64.

Methods

Base64.decode
Decodes a base64 string into a string
Base64.decodeToBuffer
Decodes a base64 string into a MemoryBuffer object
Base64.encode
Encodes a string into a base64 string

Example

// Base64 turns arbitrary bytes into plain ASCII, so data with no textual
// form can travel through something that only accepts printable
// characters -- an HTTP header, an XML element, a JSON string.
//
// All three methods are static.  encode() takes a String or a
// MemoryBuffer; decode() returns a String, decodeToBuffer() the raw
// bytes.  A String is encoded as UTF-8 and decoded back the same way, so
// text survives; anything that is not text must use the buffer forms,
// since decode() would try to read the bytes as UTF-8 and mangle them.

const encoded = Base64.encode("user:password");

let output = `encoded:  ${encoded}\n`;
output += `decoded:  ${Base64.decode(encoded)}\n\n`;

// the classic use -- HTTP basic auth.  (HttpRequest.setBasicAuth() does
// this for you; this is what it does underneath.)
const request = new HttpRequest();
request.setUrl("https://www.example.com/");
request.setRequestHeader("Authorization", `Basic ${encoded}`);

// -- binary --

// every byte value; most are not valid text in any encoding, which is
// the case base64 exists for
const buf = new MemoryBuffer(256);
for (let i = 0; i < 256; ++i) {
    buf[i] = i;
}

const encoded_buf = Base64.encode(buf);
const decoded_buf = Base64.decodeToBuffer(encoded_buf);

output += `256 bytes -> ${encoded_buf.length} characters\n`;
output += `back to ${decoded_buf.getSize()} bytes\n`;
output += `digests match: ${Hash.md5(buf) === Hash.md5(decoded_buf)}\n\n`;

// decodeToBuffer() + toAsciiString() reads a payload known to be plain
// ASCII without going through decode()'s UTF-8 conversion
output += Base64.decodeToBuffer(Base64.encode("plain ascii")).toAsciiString();

alert(output);

Base64.decode

static function Base64.decode(str : String) : String

Arguments

string
The string to decode

Returns

The decoded string

Description

Decodes a base64 string into a string.

Base64.decodeToBuffer

static function Base64.decodeToBuffer(str : String) : MemoryBuffer

Arguments

string
The string to decode

Returns

The decoded memory block as a MemoryBuffer object

Description

Decodes a base64 string into a MemoryBuffer object

Base64.encode

static function Base64.encode(value : String) : String
static function Base64.encode(value : MemoryBuffer) : String

Arguments

value
A string or memory buffer to encode

Returns

The encoded string

Description

Encodes a string into a base64 string.