[sha2 crate] obtain hashing output as a String

I'm trying to use the sha2 crate from the rust crypto project.
Most of it works, but the output hash is a value of GenericArray<u8, _>:

use sha2::{Digest, Sha512};

let input = String::from("hello");

let mut hasher = Sha512::new();
hasher.update(input);
let hash_result = hasher.finalize(); // <-- GenericArray<u8, _>

However, what I need is not a byte array but a String as output.
I tried converting it with std::str::from_utf8(&hash_result[..]) but that errors out with Err(Utf8Error { valid_up_to: 0, error_len: Some(1) }) as an error value. This indicates that the byte array does in fact not contain valid UTF-8.

Does anyone know how I can get a valid UTF-8 string from hash_result?

You probably want to convert it to a hex representation. The type implements UpperHex and LowerHex.

You could do:

let string = format!("{:x}", hash_result);

from_utf8 would be used when you have a byte array of utf8 characters.

Note that this solution will not work after migration to const generics, so I would recommend to use the hex crate instead.

Judging by this issue, the author has found a satisfying solution.

That's too bad. By using the accepted solution I was hoping to precisely not have to use the hex crate.
I like the simplicity of just hex debug printing it.

It could be implemented in future Rust versions, see the following issues:


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.