©
本文档使用
php.cn手册 发布
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash — 生成哈希值 (消息摘要)
$algo
, string $data
[, bool $raw_output
= false
] )
algo
要使用的哈希算法,例如:"md5","sha256","haval160,4" 等。
data
要进行哈希运算的消息。
raw_output
设置为 TRUE
输出原始二进制数据,
设置为 FALSE
输出小写 16 进制字符串。
如果 raw_output
设置为 TRUE
, 则返回原始二进制数据表示的信息摘要,
否则返回 16 进制小写字符串格式表示的信息摘要。
版本 | 说明 |
---|---|
5.4.0 | tiger 算法使用大端(big-endian)字节序。参见下面的示例。 |
Example #1 一个 hash() 例程
<?php
echo hash ( 'ripemd160' , 'The quick brown fox jumped over the lazy dog.' );
?>
以上例程会输出:
ec457d0a974c48d5685a7efa03d137dc8bbde7e3
Example #2 使用 PHP 5.4 或者更高版本计算 tiger 哈希值
<?php
function old_tiger ( $data = "" , $width = 192 , $rounds = 3 ) {
return substr (
implode (
array_map (
function ( $h ) {
return str_pad ( bin2hex ( strrev ( $h )), 16 , "0" );
},
str_split ( hash ( "tiger192, $rounds " , $data , true ), 8 )
)
),
0 , 48 -( 192 - $width )/ 4
);
}
echo hash ( 'tiger192,3' , 'a-string' ), PHP_EOL ;
echo old_tiger ( 'a-string' ), PHP_EOL ;
?>
以上例程在PHP 5.3中的输出:
146a7492719b3564094efe7abbd40a7416fd900179d02773 64359b7192746a14740ad4bb7afe4e097327d0790190fd16
以上例程在PHP 5.4中的输出:
64359b7192746a14740ad4bb7afe4e097327d0790190fd16 146a7492719b3564094efe7abbd40a7416fd900179d02773
[#1] Nicolas Pamart [2015-01-02 00:47:21]
Be carreful ! SHA256 return plain text string for empty field !!! empty function will not work ! Make a test before hash your POST.
[#2] buar42 at gmail dot com [2013-09-29 20:45:06]
I made a PHP script that will let you sort all the available hashes on your system by generation time or by the length of the hash. It shows a general correlation on my system (longer hashes take longer to calculate) but some are faster than others, for example, sha512 makes the (joint) longest hash, but is actually only ninth slowest (from 43 hashes available on my machine)
As I understand it, the strength of a hash is dependant on the number of collisions that it has (where two input values produce the same hash) so with an infinite number of input values but a finite number of hashes, there are a (theoretically) infinite number of collisions. But, if you have a longer hash, then you're dividing infinity by a larger number, so you'll have fewer collisions.
In reality the number of collisions will be limited by the minimum and maximum password lengths that you choose to allow, so that if you enforce a policy where passwords must be exactly a certain length (20 characters for example) you'll have a large number of unique passwords, but a smaller number of potential inputs than you have hashes coming out, so that should prevent collisions entirely. In theory.
Tl;dr: I think that longer hashes are better.
Anyway, here's the code:
<?php
$data = "hello";
foreach (hash_algos() as $v)
{
$time=microtime(1);
for ($i = 0; $i < 10000; $i++)
{
$r[$v] = strlen(hash($v, $data.$i, false));
}
$t[$v] = microtime(1)-$time;
}
switch ($_GET['sort'])
{
default:
ksort ($r);
$array = 'r';
break;
case 'length':
asort ($r);
$array = 'r';
break;
case 'time':
asort ($t);
$array = 't';
break;
}
echo '<pre> <a href="?sort=alph">Name</a> | <a href="?sort=length">Hash Length</a> | <a href="?sort=time">Time taken for 10000 hashes.</a>'."\n";
foreach ($$array as $key => $value)
{
echo $key;
for ($i = strlen ($key); $i <= 19; $i++)
{
echo ' ';
}
echo '| '.$r[$key];
for ($i = strlen ($r[$key]); $i <= 11; $i++)
{
echo ' ';
}
echo '| '.$t[$key]."\n";
}
echo '</pre>';
?>
[#3] me at akshayjoshi dot com [2013-03-22 03:00:45]
Using luka8088 at gmail dot com's code on my laptop (PHP 5.4.4 on OS X), showing fastest 50 algorithms only:
Results:
1. adler32 (raw) 3340.959 microseconds
2. adler32 (hex) 3345.012 microseconds
3. fnv132 (raw) 5178.928 microseconds
4. fnv164 (hex) 5193.948 microseconds
5. md4 (raw) 5207.061 microseconds
6. fnv132 (hex) 5248.069 microseconds
7. fnv164 (raw) 5290.985 microseconds
8. md4 (hex) 5333.9 microseconds
9. tiger160,3 (raw) 5499.124 microseconds
10. tiger128,3 (hex) 5549.907 microseconds
11. tiger192,3 (raw) 5578.994 microseconds
12. tiger192,3 (hex) 5687.952 microseconds
13. tiger160,3 (hex) 5755.186 microseconds
14. tiger128,3 (raw) 5775.928 microseconds
15. crc32b (raw) 6839.036 microseconds
16. crc32 (raw) 6983.995 microseconds
17. crc32 (hex) 7061.004 microseconds
18. crc32b (hex) 7097.005 microseconds
19. joaat (raw) 7505.893 microseconds
20. tiger160,4 (raw) 7548.093 microseconds
21. joaat (hex) 7570.028 microseconds
22. tiger192,4 (raw) 7591.009 microseconds
23. tiger160,4 (hex) 7630.825 microseconds
24. tiger128,4 (hex) 7750.034 microseconds
25. tiger128,4 (raw) 7750.988 microseconds
26. sha1 (raw) 8049.964 microseconds
27. tiger192,4 (hex) 8301.019 microseconds
28. haval128,3 (raw) 9046.792 microseconds
29. haval192,3 (raw) 9313.106 microseconds
30. haval224,3 (raw) 9315.013 microseconds
31. haval160,3 (raw) 9329.795 microseconds
32. haval256,3 (raw) 9404.182 microseconds
33. haval160,3 (hex) 9521.007 microseconds
34. md5 (raw) 9599.924 microseconds
35. haval128,3 (hex) 9603.023 microseconds
36. haval192,3 (hex) 9624.004 microseconds
37. haval256,3 (hex) 9635.925 microseconds
38. haval224,3 (hex) 9652.853 microseconds
39. md5 (hex) 9654.045 microseconds
40. haval256,4 (raw) 12173.891 microseconds
41. haval160,4 (raw) 12346.982 microseconds
42. haval256,4 (hex) 12598.037 microseconds
43. haval224,4 (hex) 12600.898 microseconds
44. haval128,4 (raw) 12680.053 microseconds
45. sha512 (raw) 12681.961 microseconds
46. haval160,4 (hex) 12733.936 microseconds
47. sha384 (raw) 12766.122 microseconds
48. haval192,4 (hex) 12813.091 microseconds
49. haval192,4 (raw) 12818.098 microseconds
50. haval128,4 (hex) 12836.933 microseconds
It seems that the adler32 algorithm has gotten a lot faster.
[#4] sneskid at hotmail dot com [2012-03-14 21:32:46]
On two different servers I found that crc32() relates to hash('crc32b',)
This may be good to know if you are writing a crc32_file function based on hash_file.
(The example does not compensate for negative crc32 results)
<?php
$val = 'hello';
var_dump(crc32($val) == ( '0x' . hash('crc32b', $val) ) ); // bool(true)
var_dump(crc32($val) == ( '0x' . hash('crc32', $val) ) ); // bool(false)
?>
Also if you are looking for a way to reduce collisions and still keep the hash result small (smaller than say md5) you could get a nice database friendly 64 bit value by using hash/crc32 and hash/crc32b, which is slower than a single md5 but the result may be more suitable for certain tasks.
<?php
$val = 'hello';
$crc64 = ( '0x' . hash('crc32', $val) . hash('crc32b', $val) ) );
var_dump($crc64); // string(18) "0x3d6531193610a686"
var_dump($crc64 + 0); // int(4423996193312384646)
?>
(examples tested on php 5.2.17)
note: ('0x' . $hex . + 0) is faster than base_convert($hex,16,10)
[#5] nmmm at nmmm dot nu [2011-07-20 13:50:33]
I was interested how "long" each hash is, so I did:
<?php
$data = "hello";
foreach (hash_algos() as $v) {
$r = hash($v, $data, false);
printf("%-12s %3d %s\n", $v, strlen($r), $r);
}
?>
which produce (long hashes are cropped)
md2 32 a9046c73e00331af68917d3804f70655
md4 32 866437cb7a794bce2b727acc0362ee27
md5 32 5d41402abc4b2a76b9719d911017c592
sha1 40 aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
sha256 64 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730
sha384 96 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553
sha512 128 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2d
ripemd128 32 789d569f08ed7055e94b4289a4195012
ripemd160 40 108f07b8382412612c048d07d13f814118445acd
ripemd256 64 cc1d2594aece0a064b7aed75a57283d9490fd5705ed3d66bf9a
ripemd320 80 eb0cf45114c56a8421fbcb33430fa22e0cd607560a88bbe14ce
whirlpool 128 0a25f55d7308eca6b9567a7ed3bd1b46327f0f1ffdc804dd8bb
tiger128,3 32 a78862336f7ffd2c8a3874f89b1b74f2
tiger160,3 40 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca
tiger192,3 48 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca39660254
tiger128,4 32 1c2a939f230ee5e828f5d0eae5947135
tiger160,4 40 1c2a939f230ee5e828f5d0eae5947135741cd0ae
tiger192,4 48 1c2a939f230ee5e828f5d0eae5947135741cd0aefeeb2adc
snefru 64 7c5f22b1a92d9470efea37ec6ed00b2357a4ce3c41aa6e28e3b
gost 64 a7eb5d08ddf2363f1ea0317a803fcef81d33863c8b2f9f6d7d1
adler32 8 062c0215
crc32 8 3d653119
crc32b 8 3610a686
haval128,3 32 85c3e4fac0ba4d85519978fdc3d1d9be
haval160,3 40 0e53b29ad41cea507a343cdd8b62106864f6b3fe
haval192,3 48 bfaf81218bbb8ee51b600f5088c4b8601558ff56e2de1c4f
haval224,3 56 92d0e3354be5d525616f217660e0f860b5d472a9cb99d6766be
haval256,3 64 26718e4fb05595cb8703a672a8ae91eea071cac5e7426173d4c
haval128,4 32 fe10754e0b31d69d4ece9c7a46e044e5
haval160,4 40 b9afd44b015f8afce44e4e02d8b908ed857afbd1
haval192,4 48 ae73833a09e84691d0214f360ee5027396f12599e3618118
haval224,4 56 e1ad67dc7a5901496b15dab92c2715de4b120af2baf661ecd92
haval256,4 64 2d39577df3a6a63168826b2a10f07a65a676f5776a0772e0a87
haval128,5 32 d20e920d5be9d9d34855accb501d1987
haval160,5 40 dac5e2024bfea142e53d1422b90c9ee2c8187cc6
haval192,5 48 bbb99b1e989ec3174019b20792fd92dd67175c2ff6ce5965
haval224,5 56 aa6551d75e33a9c5cd4141e9a068b1fc7b6d847f85c3ab16295
haval256,5 64 348298791817d5088a6de6c1b6364756d404a50bd64e645035f
[#6] rojaro at gmail dot com [2010-09-15 08:01:42]
If the given algo parameter contains an algorithm that is not supported, the hash function will return bool(false) and issue a warning.
[#7] robert+nospam at robert-gonzalez dot com [2010-01-17 16:08:18]
I've recently had the need to look at various hash algorithms and their values of the same string. To make my life a little easier I wrote this little script. It takes a string and runs it through all of the available hash algorithms on your server, outputting them in a clean little HTML table.
-----
<?php
$p = empty($_POST['p']) ? null : $_POST['p'];
?>
<html>
<head><title>Hash testing</title></head>
<style type="text/css">
table {border-collapse: collapse;}
table, td, th {border: solid 1px #ccc;}
th {background: #e1e1e1;border-color: #999;}
td, th {padding: 0.25em;}
td.algo {font-weight: bold;}
tr.on td {background: #f0f0f0;}
</style>
<body>
<h1>String hashing</h1>
<form method="post" action="
<?php echo basename(__FILE__) ?>
">
<p><label for="p">Enter a string to hash:</label><br /><input id="p" type="text" name="p" value="
<?php echo $p ?#=#>" /></p>
<p><input type="submit" name="submit" value="Hash It" /></p>
</form>
<?php ?#=#>
<?php if ($p): ?>
<hr />
<h2>Table of hash values for <em>
<?php echo $p ?>
</em> based on algorithm</h2>
<table>
<tr>
<th>Algorithm</th>
<th>Hashed value of <em>
<?php echo $p ?>
</em></th>
</tr>
<?php ?#=#>
<?php $on = false; foreach (hash_algos() as $algo): ?>
<tr
<?php if ($on): ?>
class="on"
<?php endif; ?>
>
<td class="algo">
<?php echo $algo ?>
</td>
<td class="hash">
<?php echo hash($algo, $p) ?>
</td>
</tr>
<?php $on = !$on; endforeach; ?>
</table>
<?php endif; ?>
</body>
</html>
[#8] Kai Petzke [2009-10-16 05:14:54]
The well known hash functions MD5 and SHA1 should be avoided in new applications. Collission attacks against MD5 are well documented in the cryptographics literature and have already been demonstrated in practice. Therefore, MD5 is no longer secure for certain applications.
Collission attacks against SHA1 have also been published, though they still require computing power, which is somewhat out of scope. As computing power increases with time and the attacks are likely to get better, too, attacks against systems relying on SHA1 for security are likely to become feasible within the next few years.
There is no lack of potential alternative hash algorithms, as the many choices for the "algo" argument of PHPs hash() function already suggests. Unfortunately, there is lack of analysis, as to how secure these alternative algorithms are. It is rather safe to assume, though, that the SHA2 family with its most prominent members SHA-256 und SHA-512, is better than SHA1.
When storing password hashes, it is a good idea to prefix a salt to the password before hashing, to avoid the same passwords to hash to the same values and to avoid the use of rainbow tables for password recovery. Unlike suggested in other articles, there is no security advantage in putting the salt in the middle, or even at both the beginning and the end, of the combined salt-password-string.
Rather, there are two other factors, that determine the strength of the salt: Its length and its variability. For example, using the same salt for all passwords is easy to implement, but gives only very little additional security. In particular, if users type the same passwords, they will still hash to the same value!
Therefore, the salt should be random string with at least as many variable bits, as there are bits in the hash result. In the user database, store username, the randomly generated salt for that user, and the result of hashing the salt-password-string. Access authentication is then done by looking up the entry for the user, calculating the hash of the salt found in the database and the password provided by the user, and comparing the result with the one stored in the database.
[#9] luka8088 at gmail dot com [2009-03-14 03:20:23]
Performance test results on my laptop:
Results are here shorten to fit php web notes ...
This was tested with 1024000 bytes (1000 KB) of random data, md4 always gets the first place, and md2 always get the last place :)
Results: (in microseconds)
1. md4 5307.912
2. md5 6890.058
3. crc32b 7298.946
4. crc32 7561.922
5. sha1 8886.098
6. tiger128,3 11054.992
7. haval192,3 11132.955
8. haval224,3 11160.135
9. tiger160,3 11162.996
10. haval160,3 11242.151
11. haval256,3 11327.981
12. tiger192,3 11630.058
13. haval128,3 11880.874
14. tiger192,4 14776.945
15. tiger128,4 14871.12
16. tiger160,4 14946.937
17. haval160,4 15661.954
18. haval192,4 15717.029
19. haval256,4 15759.944
20. adler32 15796.184
21. haval128,4 15887.022
22. haval224,4 16047.954
23. ripemd256 16245.126
24. haval160,5 17818.927
25. haval128,5 17887.115
26. haval224,5 18085.002
27. haval192,5 18135.07
28. haval256,5 18678.903
29. sha256 19020.08
30. ripemd128 20671.844
31. ripemd160 21853.923
32. ripemd320 22425.889
33. sha384 45102.119
34. sha512 45655.965
35. gost 57237.148
36. whirlpool 64682.96
37. snefru 80352.783
38. md2 705397.844
Code for generating this:
(compatible both with browser and cli mode)
<pre>
<?php
echo 'Building random data ...' . PHP_EOL;
@ob_flush();flush();
$data = '';
for ($i = 0; $i < 64000; $i++)
$data .= hash('md5', rand(), true);
echo strlen($data) . ' bytes of random data built !' . PHP_EOL . PHP_EOL . 'Testing hash algorithms ...' . PHP_EOL;
@ob_flush();flush();
$results = array();
foreach (hash_algos() as $v) {
echo $v . PHP_EOL;
@ob_flush();flush();
$time = microtime(true);
hash($v, $data, false);
$time = microtime(true) - $time;
$results[$time * 1000000000][] = "$v (hex)";
$time = microtime(true);
hash($v, $data, true);
$time = microtime(true) - $time;
$results[$time * 1000000000][] = "$v (raw)";
}
ksort($results);
echo PHP_EOL . PHP_EOL . 'Results: ' . PHP_EOL;
$i = 1;
foreach ($results as $k => $v)
foreach ($v as $k1 => $v1)
echo ' ' . str_pad($i++ . '.', 4, ' ', STR_PAD_LEFT) . ' ' . str_pad($v1, 30, ' ') . ($k / 1000) . ' microseconds' . PHP_EOL;
?>
</pre>
[#10] kevin at bionichippo dot com [2009-03-14 00:06:50]
When using hash() for storing passwords, I've found that the best practice is not to use just one salt, but two. This example uses my preferred algorithm for passwords, whirlpool.
This way, even if someone can produce a rainbow table for your algorithm, and has the salt to do it with, they will never know where in the hash parameter the second salt was placed, because they don't know the length of the actual password.
<?php
function doubleSalt($toHash,$username){
$password = str_split($toHash,(strlen($toHash)/2)+1);
var_dump($password);
$hash = hash('md5', $username.$password[0].'centerSalt'.$password[1]);
return $hash;
}
?>
The str_split operation needs a +1 appended, otherwise the last character is cut off when the password is an odd number of characters, so that pass1 and pass2 will return the same value.
[NOTE BY danbrown AT php DOT net: Bug spotted by (Sunil) on 13-Mar-2009 and fix applied by OP.]
[#11] Leigh [2008-08-06 10:10:31]
Just a quick note about these benchmarks and how you should apply them.
If you are hashing passwords etc for security, speed is not your friend. You should use the slowest method.
Slow to hash means slow to crack and will hopefully make generating things like rainbow tables more trouble than it's worth.
[#12] inspiration3 at gmail dot com [2008-05-04 08:12:55]
Another comprehensive benchmark script that orders results from best to worst and includes the crc32(), md5() and sha1() standalone functions:
<?php
define('HASH_TIMES', 1000);
define('HASH_DATA', 'The quick brown fox jumped over!'); // 32 bytes
header('Content-Type: text/plain');
echo 'Testing ' . strlen(HASH_DATA) . ' bytes of data over ' . HASH_TIMES . " iterations:\n";
foreach (hash_algos() as $algo) {
$time = microtime(1);
for ($i = 0; $i < HASH_TIMES; $i++) hash($algo, HASH_DATA);
$results[$algo] = microtime(1) - $time;
}
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) crc32(HASH_DATA); $results['crc32()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) md5(HASH_DATA); $results['md5()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) sha1(HASH_DATA); $results['sha1()'] = microtime(1) - $time;
asort($results, SORT_NUMERIC);
foreach ($results as $algo => $time) echo "\n$time\t$algo";
?>
[#13] Marcus [2008-04-27 05:15:29]
A upgrade of (dani88elx AT gmail DOT com)'s performance test [from 26-Jun-2007], this time grading them by speed (fastest first) and comparing times between hex and raw data.
<?php
function testAlgos() {
$algos = hash_algos();
$word="This will be crypted by all different algoritms";
$results = array();
foreach($algos as $algo)
{
$time=microtime(1);
$data = hash($algo, $word, false);
$results["".(microtime(1)-$time)][] = "$algo (hex)";
}
foreach($algos as $algo)
{
$time=microtime(1);
$data = hash($algo, $word, true);
$results["".(microtime(1)-$time)][] = "$algo (raw)";
}
ksort($results);
foreach($results as $time => &$algos) {
echo $time."\n";
sort($algos);
foreach($algos as $algo)
echo "\t".$algo."\n";
}
}
testAlgos();
?>
[#14] mikael at webhost3 dot eu [2007-03-10 05:34:08]
<?php
------------------------<br>
$time=microtime(1);
for ($i=0;$i<100000;$i++)
hash('md5', 'string');
echo microtime(1)-$time,': hash/md5<br>';
$time=microtime(1);
for ($i=0;$i<100000;$i++)
md5('string');
echo microtime(1)-$time,': md5<br>';
$time=microtime(1);
for ($i=0;$i<100000;$i++)
hash('sha1', 'string');
echo microtime(1)-$time,': hash/sha1<br>';
$time=microtime(1);
for ($i=0;$i<100000;$i++)
sha1('string');
echo microtime(1)-$time,': sha1<br>';
?>
<?php
$time=microtime(1);
for ($i=0;$i<100000;$i++)
hash('md5', $i);
echo microtime(1)-$time,': hash/md5<br>';
$time=microtime(1);
for ($i=0;$i<100000;$i++)
md5($i);
echo microtime(1)-$time,': md5<br>';
$time=microtime(1);
for ($i=0;$i<100000;$i++)
hash('sha1', $i);
echo microtime(1)-$time,': hash/sha1<br>';
$time=microtime(1);
for ($i=0;$i<100000;$i++)
sha1($i);
echo microtime(1)-$time,': sha1<br>';
?>
Gives:
0.33311605453491: hash/md5
1.0671429634094: md5
0.383131980896: hash/sha1
1.3252220153809: sha1
------------------------
0.37684988975525: hash/md5
1.1258299350739: md5
0.43960785865784: hash/sha1
1.3876020908356: sha1