type-conversionhexrust

How do I convert a string to hex in Rust?


I want to convert a string of characters (a SHA256 hash) to hex in Rust:

extern crate crypto;
extern crate rustc_serialize;

use rustc_serialize::hex::ToHex;
use crypto::digest::Digest;
use crypto::sha2::Sha256;

fn gen_sha256(hashme: &str) -> String {
    let mut sh = Sha256::new();
    sh.input_str(hashme);

    sh.result_str()
}

fn main() {
    let hash = gen_sha256("example");

    hash.to_hex()
}

The compiler says:

error[E0599]: no method named `to_hex` found for type `std::string::String` in the current scope
  --> src/main.rs:18:10
   |
18 |     hash.to_hex()
   |          ^^^^^^

I can see this is true; it looks like it's only implemented for [u8].

What am I to do? Is there no method implemented to convert from a string to hex in Rust?

My Cargo.toml dependencies:

[dependencies]
rust-crypto = "0.2.36"
rustc-serialize = "0.3.24"

edit I just realized the string is already in hex format from the rust-crypto library. D'oh.


Solution

  • I will go out on a limb here, and suggest that the solution is for hash to be of type Vec<u8>.


    The issue is that while you can indeed convert a String to a &[u8] using as_bytes and then use to_hex, you first need to have a valid String object to start with.

    While any String object can be converted to a &[u8], the reverse is not true. A String object is solely meant to hold a valid UTF-8 encoded Unicode string: not all bytes pattern qualify.

    Therefore, it is incorrect for gen_sha256 to produce a String. A more correct type would be Vec<u8> which can, indeed, accept any bytes pattern. And from then on, invoking to_hex is easy enough:

    hash.as_slice().to_hex()