UUID from hash of string

I'm trying to generate a UUID by hashing a string.

  • Rust playground doesn't have sha3 yet, and the examples in the sha3 docs won't run.
  • The UUID crate understands how to take in a MD5 hash, but not a SHA3 hash.

Is there some elegant way to do this, or do I have to push bytes around until the crates catch up?

Is there a reason you can't use an MD5 hash? Is there some set of SHA3 hashes you want to use?

Already include sha3 in the project, but avoid using md5 because it's deprecated and don't want it showing in Cargo.toml

MD5 is not good enough for security-related contexts, but it's still fine if there aren't any serious consequences from a malicious actor intentionally causing collisions.

1 Like

It's not that it "understands" one but not the other, rather the spec for UUIDs specifies a version of UUIDs derived from a md5 hash (and one for UUIDs derived from a sha1 hash) but not from a sha3 hash.

3 Likes

The sha3 example works for me. Taking that and turning the first half of the hash into a UUID looks like this:

use sha3::{Digest, Sha3_256};
use uuid::Builder;

fn main() {
    let mut hasher = Sha3_256::new();
    hasher.update(b"abc");
    let result = hasher.finalize();
    let uuid = Builder::from_bytes(result[..16].try_into().unwrap()).into_uuid();

    dbg!(uuid);
}

That is not a valid UUID. You are directly using the hashed bytes as UUID, but a UUID requires certain parts of the UUID to have certain values depending on the UUID version.

The options for a hash based UUID are v3 (md5 based), v5 (sha-1 based) or v8 (custom, which allows you to specify 122 bits, with the remaining 6 bits having a fixed value indicating a v8 uuid)

You can use the Uuid::new_v8 method to create a v8 uuid.

11 Likes

Got past this. Thanks.