-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCache.cs
94 lines (81 loc) · 2.68 KB
/
Cache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
namespace X509CertificateTool;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
/// <summary>
/// Caches certificate information.
/// </summary>
internal static class Cache
{
private static Dictionary<StoreLocation, Dictionary<string, Collection<CertData>>> _cache;
internal static Collection<CertData> GetCachedData(
StoreLocation storeLocation,
string storeNameAsString,
bool computeKeyIdentifiersImmediately,
bool computePrivateKeyDataImmediately)
{
Cache.FillCache(
storeLocation, storeNameAsString,
computeKeyIdentifiersImmediately,
computePrivateKeyDataImmediately);
return _cache[storeLocation][storeNameAsString];
}
internal static void Clear()
{
if (_cache == null)
{
return;
}
foreach (StoreLocation storeLocation in _cache.Keys)
{
foreach (string storeName in _cache[storeLocation].Keys)
{
_cache[storeLocation][storeName].Clear();
}
}
}
private static void FillCache(
StoreLocation storeLocation,
string storeNameAsString,
bool computeKeyIdentifiersImmediately,
bool computePrivateKeyDataImmediately)
{
_cache ??= [];
if (!_cache.ContainsKey(storeLocation))
{
_cache[storeLocation] = [];
}
Dictionary<string, Collection<CertData>> cacheLevel2 = _cache[storeLocation];
if (!cacheLevel2.ContainsKey(storeNameAsString))
{
cacheLevel2[storeNameAsString] = new Collection<CertData>();
}
Collection<CertData> cacheLevel3 = cacheLevel2[storeNameAsString];
X509Store store = new X509Store(storeNameAsString, storeLocation);
try
{
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
// Only do the expensive operation when the number of certs changes
if (store.Certificates.Count != cacheLevel3.Count)
{
cacheLevel3.Clear();
foreach (X509Certificate2 cert in store.Certificates)
{
cacheLevel3.Add(CertData.FromCert(
storeLocation, storeNameAsString, cert,
computeKeyIdentifiersImmediately,
computePrivateKeyDataImmediately));
cert.Reset();
}
}
}
catch (CryptographicException)
{
}
finally
{
store?.Close();
}
}
}