0

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.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
dmerlea
  • 894
  • 4
  • 12
  • 2
    I suggest you start by using the up to date documentation and version of the crate – Stargateur Dec 30 '21 at 09:39
  • If you only want to verify the validity of UTF-8, don't use `to_vec()` which will cause an unnecessary allocation, use [`as_bytes()`](https://docs.rs/elrond-wasm/0.25.0/elrond_wasm/types/struct.H256.html#method.as_bytes) and [`str::from_utf8()`](https://doc.rust-lang.org/stable/std/str/fn.from_utf8.html). – Chayim Friedman Dec 30 '21 at 09:49
  • You should not try to print a hash. Even if they're valid UTF-8 (and I'm not sure they're guaranteed to be), they're not meaningful. – Chayim Friedman Dec 30 '21 at 09:53
  • I want to compose a string with that hash. I'm not really printing, but just copied result from unit test – dmerlea Dec 30 '21 at 09:54
  • 1
    But not being guaranteed to be a valid utf8 was indeed my concern :( – dmerlea Dec 30 '21 at 09:57
  • @ChayimFriedman I cannot use `str::from_utf8()` - is part of the std – dmerlea Dec 30 '21 at 09:59
  • @dmerlea Are you using `#![no_std]`? `String` is also part of std, but you're fine with using `String::from_utf8()` (in fact, `str::from_utf8()` only requires `core`, not `std`, which is not true for `String::from_utf8()`). – Chayim Friedman Dec 30 '21 at 10:28
  • 1
    String representations of hashes are typically hex strings of the bytes. Is that what you are trying to do? – Herohtar Dec 30 '21 at 17:33

1 Answers1

1

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

Martin W
  • 733
  • 4
  • 12