From c874b6df2461ed03c3ec9ee15731a19d95d341ec Mon Sep 17 00:00:00 2001 From: ZhuangYumin Date: Fri, 8 Dec 2023 01:20:12 +0000 Subject: [PATCH] upd: optimize hash to avoid being hacked --- backend/include/key2index.hpp | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/backend/include/key2index.hpp b/backend/include/key2index.hpp index 55de193..cd098bc 100644 --- a/backend/include/key2index.hpp +++ b/backend/include/key2index.hpp @@ -14,16 +14,36 @@ class String2Index { constexpr static char salt2[10] = "9B(str.c_str() + i); + ret ^= *reinterpret_cast(inner_salt + (i & 15)); + ret += 0x9e3779b97f4a7c15; + ret = (ret ^ (ret >> 30)) * 0xbf58476d1ce4e5b9; + ret = (ret ^ (ret >> 27)) * 0x94d049bb133111eb; + ret ^= ret >> 31; + } + for (; i < str.length(); ++i) { + ret ^= str[i]; + ret ^= inner_salt[i & 15]; + ret += 0x9e3779b97f4a7c15; + ret = (ret ^ (ret >> 30)) * 0xbf58476d1ce4e5b9; + ret = (ret ^ (ret >> 27)) * 0x94d049bb133111eb; + ret ^= ret >> 31; + } return ret; } struct Node { - size_t main_hash, sub_hash; + hash_t main_hash, sub_hash; int val, nxt_idx = 0; Node() = default; Node(std::string str, int _val) @@ -70,7 +90,7 @@ class String2Index { } } void Insert(const std::string &str, int val) noexcept { - size_t hash_val = Hash(str); + hash_t hash_val = Hash(str); int idx = hash_table[hash_val % kBucketSize]; Node nd(str, val); if (idx == 0) { @@ -83,7 +103,7 @@ class String2Index { } } void Delete(const std::string &str, int val) noexcept { - size_t str_main_hash = Hash(str), + hash_t str_main_hash = Hash(str), str_sub_hash = Hash(sub_salt1 + str + sub_salt2); int idx = hash_table[str_main_hash % kBucketSize]; Node nd, last_nd; @@ -109,7 +129,7 @@ class String2Index { } std::vector Find(const std::string &str) noexcept { std::vector ret; - size_t str_main_hash = Hash(str), + hash_t str_main_hash = Hash(str), str_sub_hash = Hash(sub_salt1 + str + sub_salt2); int idx = hash_table[str_main_hash % kBucketSize]; Node nd;