Since the class is Disposable I somehow thought it should probably be used as a singleton. How should I use it safely?
// Code uses Nuget package FluentAssertions
var key = "supersecret";
var keybytes = Encoding.UTF8.GetBytes(key);
var hmac = new HMACSHA256(keybytes);
var tokenBytes = Encoding.UTF8.GetBytes("tokentocompute");
var expected = hmac.ComputeHash(tokenBytes);
await Task.WhenAll(
Enumerable.Range(0, 100).Select(i => Task.Run(() =>
{
var hash = hmac.ComputeHash(tokenBytes);
// This throws most of the time
hash.ShouldBeEquivalentTo(expected, $"{i}");
}))
);
I did not think it was a duplicate of HMACSHA1.ComputeHash() thread-safety question since there it talks specifically about different threads setting the key, whereas I am using the same key throughout every call. After rereading it, it may yet be a duplicate. Will wait upon the opinion of you guys.