.NET 框架附带 6 种不同的散列算法:
- MD5:16 字节(哈希 500MB 的时间:1462 毫秒)
- SHA-1:20 字节(1644 毫秒)
- SHA256:32 字节(5618 毫秒)
- SHA384:48 字节(3839 毫秒)
- SHA512:64 字节(3820 毫秒)
- RIPEMD:20 字节(7066 毫秒)
这些功能中的每一个都执行不同的操作;MD5 是最快的,RIPEMD 是最慢的。
MD5的优点是适合内置Guid类型;它是类型 3 UUID 的基础。SHA-1 哈希是类型 5 UUID 的基础。这使得它们非常容易用于识别。
然而,MD5 容易受到碰撞攻击,SHA-1 也容易受到攻击,但程度较轻。
在什么情况下我应该使用哪种哈希算法?
我真的很想看到答案的具体问题是:
MD5不可信吗?在正常情况下,当您使用没有恶意的 MD5 算法并且没有第三方有任何恶意时,您会期望任何冲突(意味着两个任意字节 [] 产生相同的哈希)
RIPEMD 比 SHA1 好多少?(如果它更好的话)它的计算速度慢了 5 倍,但哈希大小与 SHA1 相同。
散列文件名(或其他短字符串)时发生非恶意冲突的几率是多少?(例如 2 个具有相同 MD5 哈希的随机文件名)(使用 MD5 / SHA1 / SHA2xx) 一般来说,非恶意冲突的几率是多少?
这是我使用的基准:
static void TimeAction(string description, int iterations, Action func) {
var watch = new Stopwatch();
watch.Start();
for (int i = 0; i < iterations; i++) {
func();
}
watch.Stop();
Console.Write(description);
Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}
static byte[] GetRandomBytes(int count) {
var bytes = new byte[count];
(new Random()).NextBytes(bytes);
return bytes;
}
static void Main(string[] args) {
var md5 = new MD5CryptoServiceProvider();
var sha1 = new SHA1CryptoServiceProvider();
var sha256 = new SHA256CryptoServiceProvider();
var sha384 = new SHA384CryptoServiceProvider();
var sha512 = new SHA512CryptoServiceProvider();
var ripemd160 = new RIPEMD160Managed();
var source = GetRandomBytes(1000 * 1024);
var algorithms = new Dictionary<string,HashAlgorithm>();
algorithms["md5"] = md5;
algorithms["sha1"] = sha1;
algorithms["sha256"] = sha256;
algorithms["sha384"] = sha384;
algorithms["sha512"] = sha512;
algorithms["ripemd160"] = ripemd160;
foreach (var pair in algorithms) {
Console.WriteLine("Hash Length for {0} is {1}",
pair.Key,
pair.Value.ComputeHash(source).Length);
}
foreach (var pair in algorithms) {
TimeAction(pair.Key + " calculation", 500, () =>
{
pair.Value.ComputeHash(source);
});
}
Console.ReadKey();
}