From e82be12be94a67a562b35d19d7955eb97a89c8f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20M=C3=A4kel=C3=A4?= Date: Sat, 26 Oct 2019 15:01:43 +0300 Subject: [PATCH] Cache password hash results Since the user authentication stores a SHA2-512 hash of the password on disk, caching the hash results in memory speeds up the authentication process significantly. Storing the password on disk in plain-text form would also speed it up but this would be quite insecure. --- server/core/users.cc | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/server/core/users.cc b/server/core/users.cc index 267c42e13..0de81ba47 100644 --- a/server/core/users.cc +++ b/server/core/users.cc @@ -272,7 +272,27 @@ private: std::string hash(const std::string& password) { - return mxs::crypt(password, ADMIN_SALT); + const int CACHE_MAX_SIZE = 1000; + static std::unordered_map hash_cache; + auto it = hash_cache.find(password); + + if (it != hash_cache.end()) + { + return it->second; + } + else + { + if (hash_cache.size() > CACHE_MAX_SIZE) + { + auto bucket = rand() % hash_cache.bucket_count(); + mxb_assert(bucket < hash_cache.bucket_count()); + hash_cache.erase(hash_cache.cbegin(bucket)->first); + } + + auto new_hash = mxs::crypt(password, ADMIN_SALT); + hash_cache.insert(std::make_pair(password, new_hash)); + return new_hash; + } } std::string old_hash(const std::string& password)