比较散列字符串的最佳方法是什么?(PHP) [英] What is the best way to compare hashed strings? (PHP)
本文介绍了比较散列字符串的最佳方法是什么?(PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我应该使用 if(strcmp(md5($ string),$ hash)== 0)
还是 if(md5($ string)== $ hash)
解决方案
直接比较哈希(例如身份验证)之类的东西时应格外小心,因为这可能会打开定时攻击的窗口../p>
尽管听起来很违反直觉,但您应该对字符串进行全面比较,避免进行任何优化(即,如果字符不同,则尽早退出).
以下是有关该问题的一些链接:
- https://wiki.php.net/rfc/timing_attack
- http://codahale.com/a-lesson-in-timing-attacks/
- http://carlos.bueno.org/2011/10/timing.html
以下是一些解决方案:
- 最快,最简单:只要可用,就使用
hash_equals()
(PHP 5.6及更高版本). - https://github.com/symfony/polyfill-php56/blob/master/Php56.php (
hash_equals()
polyfill) - https://github.com/zendframework/zend-crypt/blob/master/src/Utils.php (
compareStrings()
)
Should I use if(strcmp(md5($string),$hash)==0)
or if(md5($string)==$hash)
解决方案
You should be very careful when comparing hashes directly for things like authentification as you could be opening a window to a timing attack.
Although it sounds very counterintuitive, you should to a full comparison of the string, avoiding any optimizations (i.e. exiting early if a character is different).
Here are some links about the problem:
- https://wiki.php.net/rfc/timing_attack
- http://codahale.com/a-lesson-in-timing-attacks/
- http://carlos.bueno.org/2011/10/timing.html
And here are some ideas in order to fix it:
- The fastest and easiest: just use
hash_equals()
if available (PHP 5.6 and greater). - https://github.com/symfony/polyfill-php56/blob/master/Php56.php (
hash_equals()
polyfill) - https://github.com/zendframework/zend-crypt/blob/master/src/Utils.php (
compareStrings()
)
这篇关于比较散列字符串的最佳方法是什么?(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文