0

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

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Amiya Behera
  • 2,210
  • 19
  • 32
  • It is common to convert binary data to a hex string to display it ([Function hex::encode](https://docs.rs/hex/0.3.1/hex/fn.encode.html)). Or you could use base-64 ([base64](https://docs.rs/base64/0.12.3/base64/)). – Andrew Morton Aug 15 '20 at 08:57
  • Yes @Herohtar Thank You. – Amiya Behera Aug 16 '20 at 03:32

2 Answers2

3

As per Andrew Morton, here is my answer:

use sha3::{Digest, Keccak256};
use hex;

fn main() {
    let vote = "Alice".to_owned();
    let mut hasher = Keccak256::new();
    hasher.update(vote.as_bytes());
    let result = hasher.finalize();
    println!("{:?}", hex::encode(result));
    // "81376b9868b292a46a1c486d344e427a3088657fda629b5f4a647822d329cd6a"
}
Amiya Behera
  • 2,210
  • 19
  • 32
1

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
}
Herohtar
  • 5,347
  • 4
  • 31
  • 41