cat_gateway/utils/
blake2b_hash.rs

1//! Types of Blake-2b Hash
2
3use blake2b_simd::Params;
4
5/// Generates a UUID string from the provided key and data using `BLAKE2b` hashing.
6///
7/// # Arguments
8/// - `key`: A string slice that is used as part of the hash function input.
9/// - `data`: A vector of strings which will be included in the `BLAKE2b` hash
10///   computation.
11///
12/// # Returns
13/// A UUID string generated from the `BLAKE2b` hash of the concatenated data with the key.
14pub(crate) fn generate_uuid_string_from_data(key: &str, data: &[String]) -> String {
15    // Where we will actually store the bytes we derive the UUID from.
16    let mut bytes: uuid::Bytes = uuid::Bytes::default();
17
18    // Generate a unique hash of the data.
19    let mut hasher = Params::new()
20        .hash_length(bytes.len())
21        .key(key.as_bytes())
22        .personal(b"Project Catalyst")
23        .to_state();
24
25    for datum in data {
26        hasher.update(datum.as_bytes());
27    }
28
29    // Finalize the hash and get the digest as a byte array
30    let hash = hasher.finalize();
31
32    // Create a new array containing the first 16 elements from the original array
33    bytes.copy_from_slice(hash.as_bytes());
34
35    // Convert the hash to a UUID
36    uuid::Builder::from_custom_bytes(bytes)
37        .as_uuid()
38        .as_hyphenated()
39        .to_string()
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn test_generate_uuid_string_from_data() {
48        let key = "test key";
49        let data = vec!["test1".to_string(), "test2".to_string()];
50
51        // Call the function under test
52        let uuid_str = generate_uuid_string_from_data(key, &data);
53
54        // Verify that the output is a valid UUID string
55        assert!(uuid::Uuid::parse_str(&uuid_str).is_ok());
56    }
57
58    #[test]
59    fn test_generate_uuid_string_from_data_empty_data() {
60        let key = "test key";
61        let data: Vec<String> = vec![];
62
63        // Call the function under test
64        let uuid_str = generate_uuid_string_from_data(key, &data);
65
66        // Verify that the output is a valid UUID string
67        assert!(uuid::Uuid::parse_str(&uuid_str).is_ok());
68    }
69
70    #[test]
71    fn test_generate_uuid_string_from_data_empty_key() {
72        let key = "";
73        let data = vec!["test1".to_string(), "test2".to_string()];
74
75        // Call the function under test
76        let uuid_str = generate_uuid_string_from_data(key, &data);
77
78        // Verify that the output is a valid UUID string
79        assert!(uuid::Uuid::parse_str(&uuid_str).is_ok());
80    }
81}