Nyx by Example

Base64

std/base64 provides RFC 4648 encoding and decoding for both standard Base64 (with +/ and padding) and URL-safe Base64 (with -_ and no padding). This is essential for encoding binary data in text-based protocols like HTTP headers, JWT tokens, and data URIs.

Code

// Base64 encoding and decoding (RFC 4648)

import "std/base64"

fn main() -> int {
    let original: String = "Hello, Nyx!"
    let encoded: String = base64_encode(original)
    print("original: " + original)
    print("encoded:  " + encoded)

    let decoded: String = base64_decode(encoded)
    print("decoded:  " + decoded)

    // URL-safe Base64 (no padding, - and _ instead of + and /)
    let url_enc: String = base64url_encode("https://nyxlang.com/?q=hello world")
    print("url-safe: " + url_enc)

    let url_dec: String = base64url_decode(url_enc)
    print("url-dec:  " + url_dec)

    return 0
}

Output

original: Hello, Nyx!
encoded:  SGVsbG8sIE55eCE=
decoded:  Hello, Nyx!
url-safe: aHR0cHM6Ly9ueXhsYW5nLmNvbS8_cT1oZWxsbyB3b3JsZA
url-dec:  https://nyxlang.com/?q=hello world

Explanation

base64_encode and base64_decode use the standard Base64 alphabet (A-Z, a-z, 0-9, +, /) with = padding. This is the format used in MIME, PEM certificates, and most APIs.

base64url_encode and base64url_decode use the URL-safe variant: - replaces +, _ replaces /, and padding is omitted. This is the format required by JWT (JSON Web Tokens) and safe for use in URLs and filenames.

← Previous Next →

Source: examples/by-example/41-base64.nx