Botan 3.14.1
Crypto and TLS for C&
x509_cert_cache.cpp
Go to the documentation of this file.
1/*
2* (C) 2026 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/internal/x509_cert_cache.h>
8
9#include <botan/hash.h>
10#include <iterator>
11
12namespace Botan {
13
14X509_Certificate_Cache::X509_Certificate_Cache(size_t max_entries) : m_max_entries(max_entries) {}
15
16X509_Certificate X509_Certificate_Cache::find_or_insert(std::span<const uint8_t> encoding) {
17 if(m_max_entries == 0) {
18 return X509_Certificate(encoding);
19 }
20
21 // Hash the DER
22 auto sha256 = HashFunction::create_or_throw("SHA-256");
23 DER_Hash hash;
24 sha256->update(encoding);
25 sha256->final(hash.m_hash);
26
27 // Check for a cache hit
28 {
29 const lock_guard_type<mutex_type> lock(m_mutex);
30 if(const auto it = m_cache.find(hash); it != m_cache.end()) {
31 return it->second;
32 }
33 }
34
35 // Deserialize the certificate
36 X509_Certificate cert(encoding);
37
38 // Lock again
39 const lock_guard_type<mutex_type> lock(m_mutex);
40
41 // Check for a cache hit (possibly racing with another thread)
42 if(const auto it = m_cache.find(hash); it != m_cache.end()) {
43 return it->second;
44 }
45
46 // Evict if required
47 //
48 // Drop a pseudo-random entry, chosen by the hash of the new one. Erasing
49 // begin() is not a random drop: the standard library implementations
50 // insert a node whose bucket was empty at the front of the list, so that
51 // would often evict the entry inserted immediately before, and two
52 // certificates that are looked up alternately could evict each other on
53 // every lookup.
54 //
55 // Might make sense to add LRU here
56 if(m_cache.size() >= m_max_entries) {
57 auto victim = m_cache.begin();
58 std::advance(victim, hash.hash() % m_cache.size());
59 m_cache.erase(victim);
60 }
61
62 // Add the newly deserialized cert to the cache
63 const auto it = m_cache.emplace(hash, std::move(cert)).first;
64 return it->second;
65}
66
67} // namespace Botan
static std::unique_ptr< HashFunction > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition hash.cpp:311
X509_Certificate find_or_insert(std::span< const uint8_t > encoding)
X509_Certificate_Cache(size_t max_entries=64)
secure_vector< T > lock(const std::vector< T > &in)
Definition secmem.h:145
lock_guard< T > lock_guard_type
Definition mutex.h:58