有人建議使用簡單的字符串比較來匹配密碼是不安全的,因爲timing attacks。例如見this question。 那麼,我試着測量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..
好像有時間和不同的密碼之間沒有相關性猜測。 我做錯了什麼,或者確實沒有可測量的時間差異?
人們沒有冒這個險。因爲在這個問題上已經寫了很多東西,所以做一點研究,僅僅因爲你沒有在第一次嘗試中重現它並不意味着它不存在。請參閱[定時攻擊對比字符串比較](https://thisdata.com/blog/timing-attacks-against-string-comparison/)和[使用node.js事件循環進行定時攻擊](https://snyk.io/blog/node-js-timing-attack-ccc-ctf /)以及在Google搜索中輕鬆找到的數百個其他參考文獻。 – jfriend00
要添加到我之前的評論中,是否存在實際的計時風險取決於所使用的確切環境和代碼。所以,爲了評估時間風險,人們必須展示一些真實世界的生產代碼示例。爲了避免擔心你是否有這種風險,許多人會選擇使用時間中立的比較作爲最安全的最簡單的方法。 – jfriend00