string比较真的不安全?

一些人build议使用简单的string比较来匹配密码是不安全的,因为时间攻击 。 例如看到这个问题 。 那么,我试着测量node.js中两个密码猜测之间的时间差。 这里是代码:

const pass = '................................................................'; const guess1 = '..X.............................................................'; const guess2 = '.............................................................X..'; function ns(hrtime) { return hrtime[0] * 1e9 + hrtime[1]; } test(guess1); test(guess2); test(guess1); test(guess2); test(guess1); test(guess2); test(guess1); test(guess2); test(guess1); test(guess2); test(guess1); test(guess2); function test(guess) { const start = process.hrtime(); for (let i = 0; i < 1e5; ++i) { if (guess === pass) throw new Error('HIT'); } const time = ns(process.hrtime(start)); console.log('%d ns %s', time, guess); } 

以下是我的机器执行的结果:

 2073045 ns ..X............................................................. 58420 ns .............................................................X.. 57778 ns ..X............................................................. 57468 ns .............................................................X.. 57554 ns ..X............................................................. 57436 ns .............................................................X.. 57589 ns ..X............................................................. 57798 ns .............................................................X.. 57798 ns ..X............................................................. 57506 ns .............................................................X.. 57969 ns ..X............................................................. 57974 ns .............................................................X.. 

时间和不同的密码猜测似乎没有关联。 我做错了什么,或者真的没有可测量的时间差?

1)我希望你安全地哈希密码。 这意味着人们可能会知道哈希值是多么接近。 只要哈希函数是安全的,根本没有帮助。

2)直接测量机器和现实世界的攻击是有区别的。 当攻击者计算出包含networking延迟以及node.js延迟的请求时。 如果我们谈论的是纳秒,没有人会注意到任何差异。