rustsmartcontractsmultiversx

Convert u32 -> sha256 -> String


Really important to mention: I'm working in NOSTD env: elrond_wasm https://docs.rs/elrond-wasm/0.17.1/elrond_wasm/api/trait.CryptoApi.html#tymethod.sha256

I'm trying to get a u32 => sha256 => String

let hash = self.crypto().sha256(&[1u8, 2u8, 3u8]);
if (String::from_utf8(hash.to_vec()).is_err()) {
uri.append_bytes("error".as_bytes());
}

Am I doing something wrong? It's always giving an error. When printed, I get some gibberish like: D�z�G��a�w9��M��y��;oȠc��!

&[1u8, 2u8, 3u8] this is just an example, but I tried a bunch of options

let mut serialized_attributes = Vec::new();
"123".top_encode(&mut serialized_attributes).unwrap();

or 123u32. to_be_bytes() or 123u32.to_string().to_bytes()

all same result.


Solution

  • You should not try to print the raw hash bytes directly (as that is basically binary garbage), but instead convert it into a meaningful representation like hex.

    You can try to use the hex crate for that: https://docs.rs/hex/0.3.1/hex/fn.encode.html