Search code examples
hexbase64rust

How to convert hexadecimal values to Base64 in Rust


I'm having some issues understanding the concept of traits in Rust. I'm trying to encode a simple hex value to Base64 but with no luck, here is my code (with an example of string to Base64 also)

extern crate serialize;

use serialize::base64::{ToBase64, STANDARD};
use serialize::hex::{FromHex, ToHex};

fn main () {
  let stringOfText = "This is a String";
  let mut config = STANDARD;

  println!("String to base64 = {}", stringOfText.as_bytes().to_base64(config));

  // Can't figure out this 

The solution provided by Vladimir works for 0x notated hex values. Now I'm looking to convert a hex value that is represented in a string:

extern crate serialize;

use serialize::base64::{ToBase64, STANDARD};
use serialize::hex::{FromHex, ToHex};
fn main () {
  let stringOfText = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
  let mut config = STANDARD;

  println!("String to base64 = {}", stringOfText.from_hex().from_utf8_owned().as_bytes().to_base64(config));

  // result should be: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

}

from_hex() gives me a Vec<u8> and .to_base64() is expecting a buffer of u8, first I thought to convert the Vec<u8> to string and then use the as_bytes() to get the buffer, so far still no luck.


Solution

  • It is now 2017, and rustc-serialize is now deprecated as well (see here). The new big serialization library is called serde but I think that's a little heavy for this problem.

    Here's a quick solution that manually converts from the String of hex to a Vec<u8> and then uses this to convert to a base64-encoded String.

    I am not convinced that this for loop is anywhere near the best solution for converting a String of hex into a Vec<u8>, but I'm fairly new to Rust and this is all I've got. Comments/improvements are appreciated.

    (Hey, wait a minute, I recognize these encoded strings, are you doing cryptopals?)

    extern crate base64;
    use std::u8;
    use base64::{Engine as _, engine::general_purpose};
    
    pub fn hex_to_base64(hex: String) -> String {
    
        // Make vector of bytes from octets
        let mut bytes = Vec::new();
        for i in 0..(hex.len()/2) {
            let res = u8::from_str_radix(&hex[2*i .. 2*i+2], 16);
            match res {
                Ok(v) => bytes.push(v),
                Err(e) => println!("Problem with hex: {}", e),
            };
        };
    
        general_purpose::STANDARD.encode(&bytes) // now convert from Vec<u8> to b64-encoded String
    }