This repository has been archived by the owner on Jul 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
InstrumentationKeyHashLookupHelper.cs
65 lines (57 loc) · 2.32 KB
/
InstrumentationKeyHashLookupHelper.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
namespace Microsoft.ApplicationInsights.Common
{
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// A store for instrumentation key hashes. This is order so as to optimize the computation of hashes.
/// </summary>
internal static class InstrumentationKeyHashLookupHelper
{
/// <summary>
/// Max number of component hashes to cache.
/// </summary>
private const int MAXSIZE = 100;
private static ConcurrentDictionary<string, string> knownIKeyHashes = new ConcurrentDictionary<string, string>();
/// <summary>
/// Retrieves the hash for a given instrumentation key.
/// </summary>
/// <param name="instrumentationKey">Instrumentation key string.</param>
/// <returns>SHA256 hash for the instrumentation key.</returns>
public static string GetInstrumentationKeyHash(string instrumentationKey)
{
if (string.IsNullOrEmpty(instrumentationKey))
{
throw new ArgumentNullException("instrumentationKey");
}
string hash;
var found = knownIKeyHashes.TryGetValue(instrumentationKey, out hash);
if (!found)
{
// Simplistic cleanup to guard against this becoming a memory hog.
if (knownIKeyHashes.Keys.Count >= MAXSIZE)
{
knownIKeyHashes.Clear();
}
hash = GenerateEncodedSHA256Hash(instrumentationKey.ToLowerInvariant());
knownIKeyHashes[instrumentationKey] = hash;
}
return hash;
}
/// <summary>
/// Computes the SHA256 hash for a given value and returns it in the form of a base64 encoded string.
/// </summary>
/// <param name="value">Value for which the hash is to be computed.</param>
/// <returns>Base64 encoded hash string.</returns>
private static string GenerateEncodedSHA256Hash(string value)
{
using (var sha256 = SHA256Managed.Create())
{
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(value));
return Convert.ToBase64String(hash);
}
}
}
}