使用 Windows 加密 API,如何在恒定时间内比较两个字节数组是否相等?
编辑:秘密的长度是固定的并且是公共知识。
使用 Windows 加密 API,如何在恒定时间内比较两个字节数组是否相等?
编辑:秘密的长度是固定的并且是公共知识。
时间安全比较需要知道哪个数组来自用户(这决定了它将花费的时间),以及哪个数组是你的秘密(你不想泄露它有多长的秘密)
//Code released into public domain. No attribution required.
Boolean TimingSafeArrayCompare(Byte[] safe, Byte[] user)
{
/*
A timing safe array comparison.
To prevent leaking length information,
it is important that user input is always used as the second parameter.
safe: The internal (safe) value to be checked
user: The user submitted (unsafe) value
Returns True if the two arrays are identical.
*/
int safeLen = safe.Length;
int userLen = user.Length;
// Set the result to the difference between the lengths.
// This means that arrays of different length will already cause nDiff to be non-zero
int nDiff = safeLen - userLen;
// Note that we ALWAYS iterate over the user-supplied length
// This is to prevent leaking length information
for (i = 0 to userLen-1)
{
//Using mod here is a trick to prevent leaking.
//It's safe, since if the lengths are different, nDiff will already be non-zero
nDiff = nDiff | ( User[i] xor Safe[i mod safeLen] );
}
// They are only identical strings if nDiff is exactly zero
return (nDiff == 0);
}
这是一种巧妙的技术,我在这里第一次看到。