Home

Awesome

noir_base64

A Base64 encoding/decoding library written in Noir which can encode arbitrary byte arrays into Base64 and decode Base64-encoded byte arrays (e.g. "SGVsbG8gV29ybGQ=".as_bytes()).

Usage

Configuration

Start by selecting the encoder or decoder for your configuration. These are defined separately so that only one lookup table will be instantiated at a time, since many cases will require either an encoder or a decoder but not both.

RFC 4648 specifies multiple alphabets, including the standard Base 64 Alphabet known as base64 and the "URL and Filename Safe Alphabet" known as base64url. It also specifies that padding should be required in the general case but can be explicitly omitted as an option.

Available encoder configurations:

Available decoder configurations:

fn encode

Takes an arbitrary byte array as input, encodes it in Base64 according to the alphabet and padding rules specified by the configuration, then encodes each Base64 character into UTF-8 to return a byte array representing the Base64 encoding.

// bytes: [u8; N]
let base64 = BASE64_ENCODER.encode(bytes);

fn decode

Takes a utf-8 byte array that encodes a Base64 string and attempts to decoded it into bytes according to the provided configuration specifying the alphabet and padding rules.

// base64: [u8; N]
let bytes = BASE64_DECODER.decode(base64);

Example usage

(see tests in lib.nr for more examples)

fn encode_and_decode() {
    let input: str<88> = "The quick brown fox jumps over the lazy dog, while 42 ravens perch atop a rusty mailbox.";
    let base64_encoded = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZywgd2hpbGUgNDIgcmF2ZW5zIHBlcmNoIGF0b3AgYSBydXN0eSBtYWlsYm94Lg==";

    let encoded:[u8; 120] = noir_base64::BASE64_ENCODER.encode(input.as_bytes());
    assert(encoded == base64_encoded.as_bytes());

    let decoded: [u8; 88] = noir_base64::BASE64_DECODER.decode(encoded);
    assert(decoded == input.as_bytes());
}

Costs

All of the benchmarks below are for the Barretenberg proving backend.

After the initial setup cost it is often cheaper to decode than to encode, as shown by the numbers below where the encode/decode were run over the same pairs of unencoded and base64-encoded text.

UTF-8 LengthBase64 Length# times# Gates to Encode# Gates to Decode
1216129461065
1216230571114
1216331661163
610816173498062
6108162109939181
61081631459710239

encode

Costs are equivalent for all encoder configurations.

decode

Decoding padded inputs costs 1-2 gates more than decoding unpadded inputs. Since the difference is marginal, the numbers below are only for the padded case.