Constant time compare

- fix case when second part of the && conditional is skipped when data is not equal

- isEqual variable marked volatile to prevent case when it doesn't equal 0, the loop can break early since it can never be 0 again

- tested with Fastest O3 and Whole Module optimization (App Store Release)

// FREEBIE
This commit is contained in:
Collin B. Stuart 2018-02-13 16:44:47 -05:00 committed by Michael Kirk
parent b358a75e3e
commit cc94573e9b
1 changed files with 3 additions and 3 deletions

View File

@ -10,7 +10,7 @@ NS_ASSUME_NONNULL_BEGIN
- (BOOL)ows_constantTimeIsEqualToData:(NSData *)other
{
BOOL isEqual = YES;
volatile UInt8 isEqual = 0;
if (self.length != other.length) {
return NO;
@ -21,10 +21,10 @@ NS_ASSUME_NONNULL_BEGIN
for (int i = 0; i < self.length; i++) {
// rather than returning as soon as we find a discrepency, we compare the rest of
// the byte stream to maintain a constant time comparison
isEqual = isEqual && (leftBytes[i] == rightBytes[i]);
isEqual |= leftBytes[i] ^ rightBytes[i];
}
return isEqual;
return isEqual == 0;
}
@end