🎓 A1Learner
🔍

Rust Token Maker Project

The token maker is a small tool that draws random bytes and writes them as text tokens. It writes the same bytes two ways, as hex and as Base64.

Draw the bytes from a seed

A seeded generator fills sixteen bytes. The seed keeps this page honest: the tokens below never change.

fn make_bytes(seed: u64) -> [u8; 16] {
    let mut rng = StdRng::seed_from_u64(seed);
    let mut bytes = [0u8; 16];
    rng.fill(&mut bytes);
    bytes
}

Hex spells every byte

Sixteen bytes become thirty-two hex characters. Any eye can proofread them.

let hex_token = hex::encode(bytes);
println!("hex token = {hex_token}");

Base64 packs them tighter

The URL-safe alphabet keeps the token safe inside a link. No padding rides along.

let b64_token = URL_SAFE_NO_PAD.encode(bytes);
println!("base64 token = {b64_token}");

Prove the round trip

Decode both tokens. Both must hand back the very same bytes.

println!("hex round trip = {}", hex::decode(&hex_token).unwrap() == bytes);

Example

// Cargo.toml: rand = "0.10", hex = "0.4", base64 = "0.22"
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::prelude::*;
use rand::rngs::StdRng;

fn make_bytes(seed: u64) -> [u8; 16] {
    let mut rng = StdRng::seed_from_u64(seed);
    let mut bytes = [0u8; 16];
    rng.fill(&mut bytes);
    bytes
}

fn main() {
    let bytes = make_bytes(99);
    let hex_token = hex::encode(bytes);
    let b64_token = URL_SAFE_NO_PAD.encode(bytes);
    println!("hex token = {hex_token}");
    println!("base64 token = {b64_token}");
    println!("hex round trip = {}", hex::decode(&hex_token).unwrap() == bytes);
    println!("base64 round trip = {}", URL_SAFE_NO_PAD.decode(&b64_token).unwrap() == bytes);
}

Key points

  • A token is just bytes in a text costume
  • Hex and Base64 are two costumes for the same body
  • Sixteen bytes carry 128 bits of randomness
  • That is the same budget a UUID spends
  • Use the URL-safe Base64 alphabet inside links
  • The standard alphabet can print + and /, and both break URLs
  • Always decode and compare when you build a round trip
  • A token that cannot come back is a bug with good branding

In this example, make_bytes starts a seeded generator and fills sixteen bytes. Seed 99 fixes the draw, so the tokens on this page are the same on every run. hex::encode spells the bytes out as thirty-two characters. The URL-safe Base64 engine packs the same bytes into twenty-two characters. Both decoders then hand the bytes back, and both comparisons print true. Swap the seed for rand::rng() and the same programme mints a fresh token every run.

Note

The seed in this project exists only so the page can print exact tokens

Real tokens draw from rand::rng() or the system

A seeded token is a published token

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why must a real token never come from a seeded generator?