How to convert a Base64 string to a hex string using Rust?
Asked
Active
Viewed 273 times
1 Answers
2
Here's an implementation inspired by https://stackoverflow.com/a/44532957 and the docs for base64.
extern crate base64;
use std::u8;
use base64::{Engine as _, alphabet, engine::{self, general_purpose}};
pub fn base64_to_hex(base64: String) -> String {
let mut buffer = Vec::<u8>::new();
general_purpose::STANDARD.decode_vec(base64, &mut buffer,).unwrap();
// Convert to hex thanks to https://stackoverflow.com/a/73358987
return buffer.iter()
.map(|b| format!("{:02x}", b).to_string())
.collect::<Vec<String>>()
.join("");
}
fn main() {
print!("{}", base64_to_hex("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t".to_string()));
// Outputs 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
}

ReinstateMonica3167040
- 732
- 9
- 27