1

I noticed that if I hash ordinary string using Rust and web3.sha3 I would get the same result. But if the number is big number or hex which would necessitate the inclusion of {encoding: 'hex'} as optional arg to web3.sha3 my result from Rust and web3.sha3 would not be same . So, my question is what should I do to my Rust input before hashing it? For Rust I am using multihash which is a thin wrapper.

let nm_str1 = "00000000000000000000000000000000000000000000000000000000000000ea";
/let output = encode(Hash::Keccak256, &nm_str1.as_bytes()).unwrap();
//JavaScript
const nmStr1 = "00000000000000000000000000000000000000000000000000000000000000ea";//
let output web3.sha3(nmStr1, {encoding: 'hex'} 
9
  • The string is hexadecimal, not base64.
    – user19510
    Commented Jan 21, 2018 at 20:32
  • @smarx .... I mentioned hex in my sketch but I have to show what I have done. BTW, thanks.
    – user618677
    Commented Jan 21, 2018 at 20:45
  • Why did you try base64 decoding something that wasn't base64 encoded?
    – user19510
    Commented Jan 21, 2018 at 20:46
  • I checked what {encoding: 'hex'} does? I found that it prompts a function call before processing, hex.parse .. And I later checked what this function does? I noticed that sort of decodes the hex.
    – user618677
    Commented Jan 21, 2018 at 20:57
  • Yes, it does. I was just confused as to why you used base64::decode when you seemed to already know that the encoding was hex, not base64.
    – user19510
    Commented Jan 21, 2018 at 20:58

1 Answer 1

1

The input is a hexadecimal string, so you have to first convert from hex to bytes.

The code below produces the right output for me (same as web3.sha3 except for a prefix which I assume comes from the multihash encoding):

extern crate multihash;
extern crate rustc_hex;

use multihash::{encode, Hash};
use rustc_hex::{FromHex, ToHex};

fn main() {
    let hex = "00000000000000000000000000000000000000000000000000000000000000ea";
    let bytes = hex.from_hex().unwrap();


    println!("{}", encode(Hash::Keccak256, &bytes).unwrap().to_hex());
}

For those who want the non-multihash version:

extern crate rustc_hex;
extern crate tiny_keccak;

use rustc_hex::{FromHex, ToHex};
use tiny_keccak::Keccak;

fn main() {
    let hex = "00000000000000000000000000000000000000000000000000000000000000ea";
    let bytes = hex.from_hex().unwrap();

    let mut h = Keccak::new_keccak256();
    h.update(&bytes);
    let mut res: [u8; 32] = [0; 32];
    h.finalize(&mut res);

    println!("{}", res.to_hex());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.