RustCrypto / hashes

Collection of cryptographic hash functions written in pure Rust
1.82k stars 247 forks source link

DynDigest not stringable: The trait `LowerHex` is not implemented for `Box<[u8]>` #445

Closed Sozialarchiv closed 1 year ago

Sozialarchiv commented 1 year ago

The DynDigest example is not working for me.

If I try to get string:

use digest::DynDigest;

// Dynamic hash function
fn use_hasher(hasher: &mut dyn DynDigest, data: &[u8]) -> Box<[u8]> {
    hasher.update(data);
    hasher.finalize_reset()
}

// You can use something like this when parsing user input, CLI arguments, etc.
// DynDigest needs to be boxed here, since function return should be sized.
fn select_hasher(s: &str) -> Box<dyn DynDigest> {
    match s {
        "md5" => Box::new(md5::Md5::default()),
        "sha1" => Box::new(sha1::Sha1::default()),
        "sha224" => Box::new(sha2::Sha224::default()),
        "sha256" => Box::new(sha2::Sha256::default()),
        "sha384" => Box::new(sha2::Sha384::default()),
        "sha512" => Box::new(sha2::Sha512::default()),
        _ => unimplemented!("unsupported digest: {}", s),
    }
}

fn get_checksum() -> String  {
    let mut hasher1 = select_hasher("md5");
    let hash1_1 = use_hasher(&mut *hasher1, b"foo");
    format!("{:x}", hash1_1)
}

I get the following error:

The trait `LowerHex` is not implemented for `Box<[u8]>`

The other examples are working for me. I am using the newest rust version

newpavlov commented 1 year ago

You need to convert the boxed slice to &[u8], if you want to use the built-in formatting. But I would recommend to use specialized serialization crates instead, e.g. base16ct or hex.

Sozialarchiv commented 1 year ago

Thank you very much for the fast helpful reply.

I could solve it with:

format!("{}", &hex::encode)