Skip to main content

How to Base64url-Encode in Rust with the base64 Crate

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

The base64 crate encodes base64url with its URL_SAFE_NO_PAD engine: - and _ instead of + and /, and no = padding at the end, which is the form JSON Web Tokens use. The one thing to remember is to import the Engine trait.

Syntax​

Syntax
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;

URL_SAFE_NO_PAD.encode(data)
URL_SAFE_NO_PAD.decode(text)
PartWhat it does
use base64::Engine;Brings the Engine trait into scope. encode and decode are its methods, so they can't be called without it.
URL_SAFE_NO_PADA ready-made engine: the URL-safe alphabet, with - and _, and no padding.
encode(data)Returns the encoded text as a String. data is anything that can be read as bytes, such as a &str or a Vec<u8>.
decode(text)Returns a Result: Ok with the bytes, a Vec<u8>, or Err when text isn't valid for this engine.

The base64 crate's documentation: "Use an Engine to decode or encode base64, configured with the base64 alphabet and padding behavior best suited to your application." Its list of engines describes URL_SAFE_NO_PAD as "A GeneralPurpose engine using the alphabet::URL_SAFE base64 alphabet and NO_PAD config", where NO_PAD means "Don’t add padding when encoding, and require that there is no padding when decoding."

The Example​

The example encodes the text Hi?> with three engines, STANDARD, URL_SAFE and URL_SAFE_NO_PAD, then decodes the base64url text SGk_Pg back to text. Those four characters were chosen because their base64 contains a / and padding.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.1.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Add the base64 Crate​

Terminal
cargo add base64
Output
Updating crates.io index
Adding base64 v0.23.1 to dependencies
Features:
+ alloc
+ simd-unsafe
+ std
Updating crates.io index
Locking 1 package to highest Rust 1.100.1 compatible version

cargo add base64 adds the newest version of the crate, 0.23.1 here, to the dependencies in Cargo.toml, with its default features.

Step 3: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, which imports the Engine trait and the STANDARD, URL_SAFE and URL_SAFE_NO_PAD engines, prints Hi?> encoded with each, then decodes SGk_Pg with URL_SAFE_NO_PAD and prints the bytes as text.

src/main.rs
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE, URL_SAFE_NO_PAD};

fn main() {
let data = "Hi?>";

println!("{}", STANDARD.encode(data));
println!("{}", URL_SAFE.encode(data));
println!("{}", URL_SAFE_NO_PAD.encode(data));

let decoded = URL_SAFE_NO_PAD.decode("SGk_Pg").expect("valid base64url");
println!("{}", String::from_utf8(decoded).expect("valid UTF-8"));
}
  • The two use lines import the Engine trait and the three engines.
  • Each encode call encodes the same text with a different engine.
  • URL_SAFE_NO_PAD.decode("SGk_Pg") returns a Result. .expect("valid base64url") takes the bytes out of it, or stops the program with that message if the text isn't valid.
  • String::from_utf8(decoded) turns the bytes into a String. It also returns a Result, because not every list of bytes is valid UTF-8 text.

Step 4: Run It​

Terminal
cargo run -q
Output
SGk/Pg==
SGk_Pg==
SGk_Pg
Hi?>

A zsh terminal where cargo run -q prints SGk/Pg==, SGk_Pg==, SGk_Pg and Hi?>.

cargo run compiles the program and runs it, and -q hides Cargo's own status lines.

What Happened​

  • STANDARD gave standard base64, SGk/Pg==.
  • URL_SAFE swapped the / for _ but kept the padding.
  • URL_SAFE_NO_PAD dropped the padding too: SGk_Pg.
  • Decoding SGk_Pg gave back the bytes of Hi?>, and String::from_utf8 turned them into text.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out use base64::Engine;error[E0599]: no method named `encode` found for struct `GeneralPurpose` in the current scope, with the help line trait `Engine` which provides `encode` is implemented but not in scope; perhaps you want to import itAdd use base64::Engine;
Decoding base64url text with STANDARDThe program stopped with valid base64url: Invalid symbol 95, offset 3.: 95 is the code of _Decode with the engine that encoded it, here URL_SAFE_NO_PAD
Decoding padded text with URL_SAFE_NO_PADInvalid paddingUse URL_SAFE, which decoded SGk_Pg==
Printing the decoded value directly{:?} shows the bytes, [72, 105, 63, 62]Turn them into text with String::from_utf8

Troubleshooting​

SymptomLikely causeFix
no method named `encode` found or no method named `decode` foundThe Engine trait isn't importeduse base64::Engine;
Invalid symbol with an offsetThe text uses another alphabet than the engineMatch the engine to the text
Invalid paddingPadded text given to a NO_PAD engine, or the other way roundUse the engine with the matching padding

FAQ​

Why does the crate need an import for a method?​

encode and decode belong to the Engine trait, and Rust only lets you call a trait's methods when the trait is in scope. The compiler says so in its help line: "items from traits can only be used if the trait is in scope".

What does Engine as _ mean in the crate's examples?​

The crate's examples import the trait with Engine as _, as in use base64::{engine::general_purpose::URL_SAFE, Engine as _};. The Rust Reference: "Items can be imported without binding to a name by using an underscore with the form use path as _. This is particularly useful to import a trait so that its methods may be used without importing the trait’s symbol". encode and decode work the same way with it.

Conclusion​

Import base64::Engine, then call URL_SAFE_NO_PAD.encode(data) for the unpadded base64url that JWTs use, and URL_SAFE_NO_PAD.decode(text) to get the bytes back.

Additional Resources​