Search code examples
rustsha

How to convert the hash as string?


How to print the hash as string?

use sha3::{Digest, Keccak256};

fn main() {
    let vote = "Alice".to_owned();
    let mut hasher = Keccak256::new();
    hasher.update(vote.as_bytes());
    let result = hasher.finalize();
    let hashstring = result.to_owned();
    println!("{:?}", hashstring);
    // [129, 55, 107, 152, 104, 178, 146, 164, 106, 28, 72, 109, 52, 78, 66, 122, 48, 136, 101, 127, 218, 98, 155, 95, 74, 100, 120, 34, 211, 41, 205, 106]
    // I need the hex string, instead of numbers
}

sha3 docs


Solution

  • You don't need any additional crates. Just format it as either upper- or lower-case hex:

    use sha3::{Digest, Keccak256};
    
    fn main() {
        let vote = "Alice".to_owned();
        let mut hasher = Keccak256::new();
        hasher.update(vote.as_bytes());
        let result = hasher.finalize();
        println!("{:x}", result); // 81376b9868b292a46a1c486d344e427a3088657fda629b5f4a647822d329cd6a
        println!("{:X}", result); // 81376B9868B292A46A1C486D344E427A3088657FDA629B5F4A647822D329CD6A
    }