PHP中各种Hash算法性能比较

时间:2022-10-27 19:30:10

今天做的模块又用到了Hash函数,突然想起Hash函数可能会比较占CPU资源,所以希望使用一种速度最快的摘要函数。但是PHP中的Hash函数很多,MD4、MD5、SHA-1、SHA-256、SHA-384以及SHA-512,都是比较常见的安全领域的HASH应用。于是写了个程序对比了一下PHP支持的各种Hash函数:

 

<?php
define('testtime', 50000);
$algos = hash_algos();
foreach($algos as $algo) {
    $st = microtime();
    for($i = 0; $i < testtime; $i++) {
        hash($algo, microtime().$i);
    }
    $et = microtime();
    list($ss, $si) = explode(' ', $st);
    list($es, $ei) = explode(' ', $et);
    $time[$algo] = $ei + $es - $si - $ss;
}
asort($time, SORT_NUMERIC);
print_r($time);
?>

 

此程序测试每种hash函数支持的算法,对50000个字符串执行hash计算,然后将耗时按从低到高排序,结果如下:

Array
(
    [crc32b] => 1.14942403926
    [crc32] => 1.15080493481
    [adler32] => 1.17250810205
    [md4] => 1.21484698894
    [md5] => 1.25582505324
    [sha256] => 1.31992111638
    [ripemd256] => 1.34005199425
    [ripemd128] => 1.34174097336
    [sha1] => 1.34424093234
    [ripemd160] => 1.36161398381
    [haval128,3] => 1.37490507759
    [haval160,3] => 1.37925811601
    [haval192,3] => 1.37971906387
    [haval224,3] => 1.38690299403
    [haval256,3] => 1.38968507692
    [tiger128,3] => 1.40321999939
    [tiger192,3] => 1.42025405684
    [tiger160,3] => 1.42113689062
    [ripemd320] => 1.42461802158
    [haval128,4] => 1.4465580045
    [haval160,4] => 1.44935391309
    [haval192,4] => 1.45606506625
    [haval224,4] => 1.4650528846
    [tiger128,4] => 1.47951410777
    [tiger192,4] => 1.49081709387
    [haval256,4] => 1.50713596634
    [haval160,5] => 1.51613600436
    [haval224,5] => 1.51645894888
    [haval192,5] => 1.51678603177
    [haval256,5] => 1.51900808377
    [tiger160,4] => 1.52507308815
    [haval128,5] => 1.53689793875
    [whirlpool] => 1.82801189377
    [snefru] => 1.85931909387
    [gost] => 1.89863007236
    [sha384] => 1.95804009064
    [sha512] => 1.97130295938
    [md2] => 4.99702701607
)

CRC是冗余验证算法,不适合用来做唯一标识符Hash计算,MD4是最快的摘要算法,MD5次之,SHA系列算法居然是SHA-256最快,比SHA-1还快一些。由此得出结论:要把唯一标识符转换成定长字串可以考虑使用MD4,而密码加密则SHA-1或SHA-256更合适。MD5就没有多少使用的必要了,速度比不过MD4,安全性比不过SHA,还是趁早放弃的好。