Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hexadecimal values to Base64 in Rust

Tags:

hex

base64

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.

like image 613
David Dias Avatar asked Oct 03 '14 19:10

David Dias


2 Answers

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 self::base64::{encode};

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),
        };
    };

    encode(&bytes) // now convert from Vec<u8> to b64-encoded String
}    
like image 75
firechant Avatar answered Oct 26 '22 18:10

firechant


Rust is currently evolving, and the accepted answer does not work properly any more. Specifically, the extern crate statement does not allow quoted parameters, and the name of the rustc-serialize crate is now rustc_serialize.

The following code correctly base64 encodes the string, yielding the same result as the accepted answer (rustc 1.3.0):

extern crate rustc_serialize as serialize;

use serialize::base64::{self, ToBase64};
use serialize::hex::FromHex;

fn main() {
    let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
    let result = input.from_hex().unwrap().to_base64(base64::STANDARD);
    println!("{}", result);
}

Result:

SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

like image 37
Jonatan Avatar answered Oct 26 '22 19:10

Jonatan