Base64 Encoding in Rust
Rust provides base64 encoding and decoding functionality through the base64
crate, which needs to be added to your Cargo.toml
file:
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:
We import the necessary components from the
base64
crate.We define a string
data
that we’ll use for encoding and decoding.For standard base64 encoding, we use
general_purpose::STANDARD.encode()
. This returns aString
.To decode, we use
general_purpose::STANDARD.decode()
. This returns aResult<Vec<u8>, DecodeError>
, which we unwrap. We then convert the resulting bytes to a string for printing.For URL-safe base64 encoding and decoding, we use
general_purpose::URL_SAFE
instead ofSTANDARD
.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:
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.