What is the difference between a hex decoded string and a string.as_bytes()?

52 Views Asked by At

I am hashing a string.

let src = String::from("abcd12342020");
let h1 = sha2::Sha256::digest(&src.as_bytes());
let h2 = sha2::Sha256::digest(hex::decode(&src).expect("this is not hex"));

h1 and h2 are different. What is the underlying reason? What is the difference between a bytes representation and the hex decoded one? (Tried to provide a playground but the hex create is not available there)

1

There are 1 best solutions below

1
PitaJ On BEST ANSWER

h1 and h2 are different because src.as_bytes() and hex::decode(&src) are different. Wrap them with the dbg! macro to see the difference.

They're different because hex::decode parses the text as hex, meaning ab gets parsed into 0xAB etc. But src.as_bytes() returns the text encoded as a UTF-8 byte sequence, meaning ab is encoded in memory as [0x61, 0x62].