充气城堡HMAC SHA1



我有以下代码使用BouncyCastle(dotnet版本(从消息中获取HMAC-SHA1。

我有这个小库类:

public class HashingTools
{
static string hmacKey = "81310910a060c5705c1d3cedf370bcf9";
public static int HashSizeInBytes = 20;
static KeyParameter keyParameter = null;
private static HMac hmacInstance;
static HashingTools()
{
hmacInstance = new HMac(new Sha1Digest());
hmacInstance.Init(newKeyParameter(Encoding.UTF8.GetBytes(hmacKey)));
}
public static byte[] HashSha1(byte[] message)
{
byte[] result = new byte[hmacInstance.GetMacSize()];
hmacInstance.BlockUpdate(message, 0, message.Length);
hmacInstance.DoFinal(result, 0);
return result;
}
}

我有很多消息通过这种方法,都使用相同的键:hmacKey,我想尽可能加快速度,并尽可能多地重用,仍然在安全参数方面(随机性、新鲜度......

如果我尝试重用或并行化hmac实例,我会在Org.BouncyCastle.Crypto.Macs.Hmac.BlockUpdate中出现"数组越界"异常。

我为重现创建了这个单元测试(1 或 2 个并行哈希函数正常,100 个出错(:

[Test]
public void TestBulkHashing()
{
var messages = new List<byte[]>();
foreach (var index in Enumerable.Range(0, 100))
{
var buffer = new byte[4096];
Random r = new Random();
r.NextBytes(buffer);
messages.Add(buffer);
}
Parallel.ForEach(messages, m =>
{
HashingTools.HashSha1(m);
});
}

> 正如@dlatikay正确推测的那样,这是一个同步错误。Bouncycastle 的类不是线程安全的,除非他们明确表示它是。

如果修改HashSha1方法以显式同步线程,则不会收到异常:

public static byte[] HashSha1(byte[] message) {
byte[] result = new byte[hmacInstance.GetMacSize()];
lock(hmacInstance) {
hmacInstance.BlockUpdate(message, 0, message.Length);
hmacInstance.DoFinal(result, 0);
}
return result;
}

至于你关于优化的问题,Bouncycastle已经预先计算了涉及密钥的计算部分。调用DoFinal(...)时,内部状态将重置为此预先计算的值,因此,如果使用相同的键,则无需为下一个 HMac 再次调用Init()。您的代码已经利用了此优化,因此我认为除非您想编写自己的哈希代码,否则您无能为力。

最新更新