This page summarizes Base64 usage in Rust with the base64
crate.
It covers common APIs, URL-safe variants, error handling, and small file I/O examples.
Use the crate base64
. The primary functions are encode
and decode
,
and the more flexible Engine
API under base64::engine
.
Typical engines include general_purpose::STANDARD
and general_purpose::URL_SAFE
,
with or without padding.
[dependencies]
base64 = "0.22"
use base64::{encode, decode};
fn main() {
let text = "Hello, world";
let b64 = encode(text);
println!("{}", b64); // SGVsbG8sIOS4lueVjw==
let bytes = decode(&b64).expect("valid base64");
let decoded = String::from_utf8(bytes).expect("utf8");
println!("{}", decoded); // Hello, world
}
use base64::{engine::general_purpose, Engine as _};
fn main() {
let raw = b"token:id/123+scope";
let url_b64 = general_purpose::URL_SAFE.encode(raw);
println!("{}", url_b64); // dG9rZW46aWQvMTIzK3Njb3Bl
let bytes = general_purpose::URL_SAFE.decode(url_b64).unwrap();
println!("{:?}", bytes); // b"token:id/123+scope"
}
use base64::decode;
fn main() {
match decode("@@invalid@@") {
Ok(bytes) => println!("{} bytes", bytes.len()),
Err(err) => eprintln!("Decode failed: {}", err),
}
}
use std::{fs, io};
use base64::{engine::general_purpose, Engine as _};
fn main() -> io::Result<()> {
// Binary file โ Base64 text
let bytes = fs::read("input.bin")?;
let b64 = general_purpose::STANDARD.encode(&bytes);
fs::write("output.txt", b64)?;
// Base64 text โ Binary file
let b64_text = fs::read_to_string("output.txt")?;
let data = general_purpose::STANDARD
.decode(b64_text.trim())
.expect("valid base64");
fs::write("restored.bin", data)?;
Ok(())
}
STANDARD
, URL_SAFE
, and their NO_PAD
variants.String::from_utf8
when converting decoded bytes to text.Result<Vec<u8>, base64::DecodeError>
; handle gracefully.