使用WindowsencryptionAPI在恒定时间比较2个秘密

使用WindowsencryptionAPI,如何比较两个字节数组在常量时间的相等性?

编辑:秘密的长度是固定的,是公共知识。

时间安全的比较需要知道哪个数组来自用户(这决定了它将花费的时间),以及哪个数组是你的秘密(你不想泄漏它的多久的秘密)

//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); } 

这是一个巧妙的技巧,我第一次在这里看到。