1 /* $NetBSD: hash.c,v 1.10 2026/01/29 18:37:54 christos Exp $ */ 2 3 /* 4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC") 5 * 6 * SPDX-License-Identifier: MPL-2.0 7 * 8 * This Source Code Form is subject to the terms of the Mozilla Public 9 * License, v. 2.0. If a copy of the MPL was not distributed with this 10 * file, you can obtain one at https://mozilla.org/MPL/2.0/. 11 * 12 * See the COPYRIGHT file distributed with this work for additional 13 * information regarding copyright ownership. 14 */ 15 16 #include <inttypes.h> 17 #include <stdbool.h> 18 #include <stddef.h> 19 20 #include <isc/ascii.h> 21 #include <isc/hash.h> /* IWYU pragma: keep */ 22 #include <isc/random.h> 23 #include <isc/result.h> 24 #include <isc/siphash.h> 25 #include <isc/string.h> 26 #include <isc/types.h> 27 #include <isc/util.h> 28 29 static uint8_t isc_hash_key[16]; 30 31 void 32 isc__hash_initialize(void) { 33 /* 34 * Set a constant key to help in problem reproduction should 35 * fuzzing find a crash or a hang. 36 */ 37 uint8_t key[16] = { 1 }; 38 #if !FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION 39 isc_random_buf(key, sizeof(key)); 40 #endif /* if FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION */ 41 STATIC_ASSERT(sizeof(key) >= sizeof(isc_hash_key), 42 "sizeof(key) < sizeof(isc_hash_key)"); 43 memmove(isc_hash_key, key, sizeof(isc_hash_key)); 44 } 45 46 const void * 47 isc_hash_get_initializer(void) { 48 return isc_hash_key; 49 } 50 51 void 52 isc_hash_set_initializer(const void *initializer) { 53 REQUIRE(initializer != NULL); 54 55 memmove(isc_hash_key, initializer, sizeof(isc_hash_key)); 56 } 57 58 void 59 isc_hash32_init(isc_hash32_t *restrict state) { 60 isc_halfsiphash24_init(state, isc_hash_key); 61 } 62 63 void 64 isc_hash32_hash(isc_hash32_t *restrict state, const void *data, 65 const size_t length, const bool case_sensitive) { 66 REQUIRE(length == 0 || data != NULL); 67 68 isc_halfsiphash24_hash(state, data, length, case_sensitive); 69 } 70 71 uint32_t 72 isc_hash32_finalize(isc_hash32_t *restrict state) { 73 uint32_t hval; 74 75 isc_halfsiphash24_finalize(state, (uint8_t *)&hval); 76 77 return hval; 78 } 79 80 void 81 isc_hash64_init(isc_hash64_t *restrict state) { 82 isc_siphash24_init(state, isc_hash_key); 83 } 84 85 void 86 isc_hash64_hash(isc_hash64_t *restrict state, const void *data, 87 const size_t length, const bool case_sensitive) { 88 REQUIRE(length == 0 || data != NULL); 89 90 isc_siphash24_hash(state, data, length, case_sensitive); 91 } 92 93 uint64_t 94 isc_hash64_finalize(isc_hash64_t *restrict state) { 95 uint64_t hval; 96 97 isc_siphash24_finalize(state, (uint8_t *)&hval); 98 99 return hval; 100 } 101