Base64 Encoding in Rust

use base64::{engine::general_purpose, Engine as _};

fn main() {
    // Here's the string we'll encode/decode.
    let data = "abc123!?$*&()'-=@~";

    // Rust provides base64 encoding/decoding through the `base64` crate.
    // Here's how to encode using the standard encoder.
    let s_enc = general_purpose::STANDARD.encode(data);
    println!("{}", s_enc);

    // Decoding may return an error, which you can handle with `unwrap()` 
    // if you're certain the input is well-formed.
    let s_dec = general_purpose::STANDARD.decode(&s_enc).unwrap();
    println!("{}", String::from_utf8_lossy(&s_dec));
    println!();

    // This encodes/decodes using a URL-compatible base64 format.
    let u_enc = general_purpose::URL_SAFE.encode(data);
    println!("{}", u_enc);
    let u_dec = general_purpose::URL_SAFE.decode(&u_enc).unwrap();
    println!("{}", String::from_utf8_lossy(&u_dec));
}

Rust provides base64 encoding and decoding functionality through the base64 crate, which needs to be added to your Cargo.toml file:

[dependencies]
base64 = "0.21.0"

In this example, we’re using the base64 crate to perform standard and URL-safe base64 encoding and decoding. Here’s a breakdown of the code:

  1. We import the necessary components from the base64 crate.

  2. We define a string data that we’ll use for encoding and decoding.

  3. For standard base64 encoding, we use general_purpose::STANDARD.encode(). This returns a String.

  4. To decode, we use general_purpose::STANDARD.decode(). This returns a Result<Vec<u8>, DecodeError>, which we unwrap. We then convert the resulting bytes to a string for printing.

  5. For URL-safe base64 encoding and decoding, we use general_purpose::URL_SAFE instead of STANDARD.

  6. We print the results of each operation to see the differences between standard and URL-safe encoding.

When you run this program, you’ll see output similar to this:

YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing + vs -), but they both decode to the original string as desired.