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
pull/1/head
Collin B. Stuart 7 years ago committed by Michael Kirk
parent b358a75e3e
commit cc94573e9b

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

Loading…
Cancel
Save