Newbyte
Newbyte

Reputation: 3292

Convert u8 array to base64 string in Rust

I have an array of u8 in Rust. How would I go about converting these to a String representing them as base64?

Upvotes: 21

Views: 25893

Answers (3)

natiiix
natiiix

Reputation: 1195

According to the v0.22.1 documentation of the base64 crate, there is now a slightly cleaner method of encoding and decoding:

use base64::prelude::*;

assert_eq!(BASE64_STANDARD.decode(b"+uwgVQA=")?, b"\xFA\xEC\x20\x55\0");
assert_eq!(BASE64_STANDARD.encode(b"\xFF\xEC\x20\x55\0"), "/+wgVQA=");

The encode function's input can be [u8; N], &[u8; N], Vec<u8>, &[u8], String, &str, and probably many more.

The decode function also accepts at least the aforementioned types as its input.

I wanted to add an up-to-date answer in case anyone else gets this as their first search result, and becomes displeased with what they find. I also included the decode counterpart, since it seems likely to me that someone searching for a way to encode may also want to decode.

Minimal working example

Here is an example of a Base64 conversion, specifically from a u8 array ([u8; N]) to a String, as mentioned in the original question.

Please note that the decode function returns Vec<u8>, not [u8; N].

src/main.rs:

use base64::prelude::*;

fn main() {
    let input_vec = b"Hello, World!".to_owned();
    let expected_base64 = "SGVsbG8sIFdvcmxkIQ==".to_owned();

    let input_base64 = "SGVsbG8sIFdvcmxkIQ==".to_owned();
    let expected_vec = b"Hello, World!".to_owned();

    assert_eq!(BASE64_STANDARD.encode(input_vec), expected_base64);
    assert_eq!(BASE64_STANDARD.decode(input_base64).unwrap(), expected_vec);
}

cargo.toml:

[package]
name = "base64test"
version = "0.1.0"
edition = "2021"

[dependencies]
base64 = "0.22.1"

Upvotes: 2

Marco Moschettini
Marco Moschettini

Reputation: 1735

Please note that the base64::encode function has been deprecated.

From version 0.21.0 the preferred way to achieve the same result would be

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

fn main() {
    let data: Vec<u8> = vec![1,2,3,4,5];
    println!("{}", general_purpose::STANDARD.encode(&data));
}

Upvotes: 25

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19672

What you're looking for is the base64 crate, particularly its encode() function. Usage is pretty straightforward:

extern crate base64;

fn main() {
    let data: Vec<u8> = vec![1,2,3,4,5];
    println!("{}", base64::encode(&data))
}

Upvotes: 13

Related Questions