Cng版本应该会更快一些,但我写了一个小程序来比较它们的速度。(我有一个客户在询问MD5和SHA1的性能特征)。
我惊讶地发现,MD5和SHA1之间几乎没有区别,但也惊讶地发现Cng和CryptoServiceProvider之间有轻微差异。
源代码非常简单,我添加了重复运行相同迭代多次的操作,以便在任何奇怪的情况下可以进行平均处理,比如在我的机器上执行其中一个运行时。
使用类似以下方式调用:
CalculateHash(1, 1024, new SHA1CryptoServiceProvider());
static long CalculateHash(UInt64 repetitions, UInt64 size, HashAlgorithm engine)
{
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[][] goo = new byte[repetitions][];
for (UInt64 i = 0; i < repetitions; i++)
{
goo[i] = new byte[size];
rng.GetBytes(goo[i]);
}
DateTime start = DateTime.Now;
for (UInt64 i = 0; i < repetitions; i++)
{
engine.ComputeHash(goo[i]);
}
return DateTime.Now.Subtract(start).Ticks;
}
我在一个逐渐增加的循环中运行了这个程序,以确定在使用大或小输入时是否会出现错误。以下是循环和数据(我的计算机在2^28时已经耗尽了内存):
int loops = 32;
UInt64 reps = 1;
int width = 20;
Console.WriteLine("Loop#".PadRight(6) +
"MD5".PadRight(width) +
"SHA1".PadRight(width) +
"SHA1Cng".PadRight(width) +
"SHA256".PadRight(width) +
"SHA256Cng".PadRight(width));
for (int i = 0; i < loops; i++)
{
UInt64 size = (UInt64)Math.Pow((double)2, (double)i);
Console.WriteLine((i + 1).ToString().PadRight(6) +
CalculateHash(reps, size, new MD5CryptoServiceProvider()).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA1CryptoServiceProvider()).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA1Cng() ).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA256CryptoServiceProvider()).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA256Cng()).ToString().PadRight(width));
}
Loop
1 50210 0 0 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
6 0 0 0 0 0
7 0 0 0 0 0
8 0 0 0 0 0
9 0 0 0 0 0
10 0 0 10042 0 0
11 0 0 0 0 0
12 0 0 0 0 0
13 0 0 0 0 0
14 0 0 0 0 0
15 10042 0 0 10042 10042
16 10042 0 0 0 0
17 0 0 0 10042 10042
18 0 10042 10042 20084 10042
19 0 10042 10042 30126 40168
20 20084 20084 20084 70294 70294
21 30126 40168 40168 140588 140588
22 60252 70294 80336 291218 281176
23 120504 140588 180756 572394 612562
24 241008 281176 361512 1144788 1215082
25 482016 572394 723024 2289576 2420122
26 953990 1134746 1456090 4538984 4830202
27 1907980 2259450 2982474 9118136 9660404
28 3805918 4508858 5804276 18336692 19581900