From 0408d802db25d57f428521f822b933708a1c5ad8 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Mon, 13 Nov 2023 10:58:18 +0100 Subject: [PATCH] id128: add id128_digest() helper This helper hashes some arbitrary data and turns it into a v4 UUID. --- src/libsystemd/sd-id128/id128-util.c | 19 +++++++++++++++++++ src/libsystemd/sd-id128/id128-util.h | 2 ++ 2 files changed, 21 insertions(+) diff --git a/src/libsystemd/sd-id128/id128-util.c b/src/libsystemd/sd-id128/id128-util.c index 596b8786bf6..dbe4d201505 100644 --- a/src/libsystemd/sd-id128/id128-util.c +++ b/src/libsystemd/sd-id128/id128-util.c @@ -9,6 +9,7 @@ #include "hexdecoct.h" #include "id128-util.h" #include "io-util.h" +#include "sha256.h" #include "stdio-util.h" #include "string-util.h" #include "sync-util.h" @@ -234,3 +235,21 @@ int id128_get_product(sd_id128_t *ret) { *ret = uuid; return 0; } + +sd_id128_t id128_digest(const void *data, size_t size) { + assert(data || size == 0); + + /* Hashes a UUID from some arbitrary data */ + + if (size == SIZE_MAX) + size = strlen(data); + + uint8_t h[SHA256_DIGEST_SIZE]; + sd_id128_t id; + + /* Take the first half of the SHA256 result */ + assert_cc(sizeof(h) >= sizeof(id.bytes)); + memcpy(id.bytes, sha256_direct(data, size, h), sizeof(id.bytes)); + + return id128_make_v4_uuid(id); +} diff --git a/src/libsystemd/sd-id128/id128-util.h b/src/libsystemd/sd-id128/id128-util.h index 80c36e5a7ba..53ba50a8ace 100644 --- a/src/libsystemd/sd-id128/id128-util.h +++ b/src/libsystemd/sd-id128/id128-util.h @@ -47,6 +47,8 @@ sd_id128_t id128_make_v4_uuid(sd_id128_t id); int id128_get_product(sd_id128_t *ret); +sd_id128_t id128_digest(const void *data, size_t size); + /* A helper to check for the three relevant cases of "machine ID not initialized" */ #define ERRNO_IS_NEG_MACHINE_ID_UNSET(r) \ IN_SET(r, \ -- 2.47.3