Last updated: May 2026
How Do You Add Base64 to a Rust Project?
Rust's standard library does not include Base64 encoding. Add the base64 crate to your project by including it in Cargo.toml. The base64 crate is the most widely used Base64 implementation in the Rust ecosystem and follows RFC 4648.
# Cargo.toml
[dependencies]
base64 = "0.22"
After adding the dependency, run cargo build to download and compile the crate. Import the engine and alphabet types you need at the top of your Rust file. The crate uses an Engine trait to decouple the encoding logic from the alphabet and padding configuration.
use base64::{Engine, engine::general_purpose};
The Engine trait is the core abstraction. Each predefined engine (like general_purpose::STANDARD) bundles an alphabet with a padding configuration. You call encode() and decode() on the engine. For a browser-based alternative that requires no code, use the Base64 text encoder.
How Do You Encode a String to Base64 in Rust?
Call .encode() on any of the predefined engines in general_purpose. The method accepts any type that implements AsRef<[u8]>, including &str, String, and &[u8]. It returns an owned String containing the Base64-encoded output.
use base64::{Engine, engine::general_purpose};
fn main() {
let input = "Hello, World!";
let encoded = general_purpose::STANDARD.encode(input);
println!("{}", encoded);
// Output: SGVsbG8sIFdvcmxkIQ==
}
String slices (&str) implement AsRef<[u8]>, so you can pass them directly without calling .as_bytes(). The STANDARD engine uses the standard Base64 alphabet (A-Z, a-z, 0-9, +, /) with = padding as defined in RFC 4648 Section 4. For binary data, pass a byte slice (&[u8]) directly. For a complete explanation of the Base64 format, see the What is Base64 guide.
How Do You Decode Base64 in Rust?
Call .decode() on an engine to decode a Base64 string. The method returns Result<Vec<u8>, DecodeError>. You must handle the error case because invalid Base64 input causes a DecodeError rather than a panic. Convert the decoded bytes back to a string using String::from_utf8().
use base64::{Engine, engine::general_purpose};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let encoded = "SGVsbG8sIFdvcmxkIQ==";
// Decode Base64 to bytes
let decoded_bytes = general_purpose::STANDARD.decode(encoded)?;
// Convert bytes to UTF-8 string
let decoded_str = String::from_utf8(decoded_bytes)?;
println!("{}", decoded_str);
// Output: Hello, World!
Ok(())
}
The ? operator propagates errors up the call stack. In production code, match on the Result to provide specific error messages. DecodeError variants include InvalidByte (unexpected character), InvalidLength (input length not valid for Base64), and InvalidPadding (malformed = padding). String::from_utf8() fails if the decoded bytes are not valid UTF-8. To decode Base64 interactively in your browser, use the Base64 text decoder.
What Are the Base64 Engines in Rust?
The base64 crate provides 4 predefined engines in the engine::general_purpose module. Each engine is a combination of an alphabet (standard or URL-safe) and a padding policy (with or without = padding). Choose the engine that matches the system you are interoperating with.
| Engine Constant | Alphabet | Padding | Common Use |
|---|---|---|---|
STANDARD |
+, / (RFC 4648 §4) | Yes (=) |
General Base64, MIME, email |
STANDARD_NO_PAD |
+, / (RFC 4648 §4) | No | Compact storage, no padding needed |
URL_SAFE |
-, _ (RFC 4648 §5) | Yes (=) |
URL query parameters, filenames |
URL_SAFE_NO_PAD |
-, _ (RFC 4648 §5) | No | JWT tokens, OAuth tokens |
URL-safe engines replace + with - and / with _ to prevent conflicts when Base64 strings appear in URLs or filenames. JWT tokens use URL_SAFE_NO_PAD because the JWT specification (RFC 7519) requires URL-safe Base64 without padding. For browser-based URL-safe encoding, use the URL-safe Base64 tool. For the full character reference, see the Base64 character table.
How Do You Encode Files in Rust?
Read the file into a byte vector using std::fs::read(), then pass the byte slice to the engine's encode() method. The fs::read() function loads the entire file into a Vec<u8>, which is suitable for files that fit within available memory.
use base64::{Engine, engine::general_purpose};
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Read the entire file as bytes
let file_bytes = fs::read("image.png")?;
// Encode to Base64
let encoded = general_purpose::STANDARD.encode(&file_bytes);
println!("Encoded length: {} chars", encoded.len());
// Create a data URI for HTML embedding
let data_uri = format!("data:image/png;base64,{}", encoded);
println!("{}", &data_uri[..50]); // Print first 50 chars
// Write Base64 output to a file
fs::write("image.b64", encoded)?;
Ok(())
}
For large files, consider encoding in chunks using the engine's encode_slice() method with a pre-allocated output buffer, or use the lower-level chunked_encoder module for streaming support. The Base64 file encoder performs the same operation in your browser without any Rust code. To decode back to a file, call engine.decode() and write the resulting bytes with fs::write().
Frequently Asked Questions
How do I add Base64 to a Rust project?
Add base64 = "0.22" (or the latest version) to the [dependencies] section of your Cargo.toml file, then run cargo build. Import the engine trait and the predefined engines with use base64::{Engine, engine::general_purpose};. The base64 crate is the standard community choice for Base64 in Rust and is available on crates.io.
How do I encode Base64 in Rust?
Call general_purpose::STANDARD.encode("your text") after importing use base64::{Engine, engine::general_purpose};. The encode() method accepts any type that implements AsRef<[u8]>, including string slices, String, and byte slices. It returns an owned String containing the Base64-encoded output with standard padding.
What is the difference between STANDARD and URL_SAFE in Rust base64?
STANDARD uses the standard Base64 alphabet with + and / characters as defined in RFC 4648 Section 4. URL_SAFE replaces + with - and / with _ as defined in RFC 4648 Section 5. Use URL_SAFE or URL_SAFE_NO_PAD when the Base64 string will appear in a URL, filename, or JSON field where + and / have special meaning.
How do I handle Base64 decode errors in Rust?
The decode() method returns Result<Vec<u8>, DecodeError>. Handle errors with pattern matching: match engine.decode(input) { Ok(bytes) => { ... }, Err(e) => { eprintln!("Decode error: {}", e); } }. The ? operator propagates the error to the caller. Common error variants are InvalidByte, InvalidLength, and InvalidPadding. Use the Base64 validator to verify input before decoding.
Related Base64 Tools and Guides
- What is Base64? - Comprehensive guide to the Base64 encoding format
- Base64 Text Encoder - Encode text to Base64 in your browser
- Base64 Text Decoder - Decode Base64 strings in your browser
- URL-Safe Base64 Encoder - Encode with the URL-safe alphabet
- Base64 in Go - Base64 encoding with Go's standard library
- Base64 in Python - Base64 encoding with Python's base64 module
- Base64 Character Table - Complete alphabet reference
- Base64 Validator - Validate Base64 strings instantly
- All Base64 Tools - Browse the complete toolset