The Base64 class provides basic ability to encode and decode strings using base64.
// 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); The decoded string
Decodes a base64 string into a string.
The decoded memory block as a MemoryBuffer object
Decodes a base64 string into a MemoryBuffer object
The encoded string
Encodes a string into a base64 string.