Skip to content

Instantly share code, notes, and snippets.

@fphilipe
Created August 21, 2012 09:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fphilipe/3413755 to your computer and use it in GitHub Desktop.
Save fphilipe/3413755 to your computer and use it in GitHub Desktop.
Objective-C -hash method clash
// This code demonstrates -hash collision on NSString. Two strings have the same
// hash when the first, center, and last 32 chars are identical. The other chars
// don't matter at all.
//
// I had to find this out the hard way when loading images from cache while
// using the url string hash as the cache key. Unfortunately the urls were all
// gravatar urls, thus first 32 chars were identical. Further, all urls also had
// a fallback image url appended as query which covered the 32
// center and end chars. The varying part was between the start and center parts
// and thus the hash was identical for all urls.
#import <Foundation/Foundation.h>
// Random string made out of ASCII chars.
NSString *randomString(NSUInteger length) {
NSMutableString *s = [NSMutableString stringWithCapacity:length];
for (NSUInteger i = 0U; i < length; i++)
[s appendFormat:@"%C", (unichar)(arc4random() % 128)];
return s;
}
int main(int argc, char *argv[]) {
@autoreleasepool {
NSString *start = randomString(32);
NSString *center = randomString(32);
NSString *end = randomString(32);
for (NSUInteger i = 1U; i <= 256; i++) {
NSString *a = [NSString stringWithFormat:@"%@%@%@%@%@", start, randomString(i), center, randomString(i), end];
NSString *b = [NSString stringWithFormat:@"%@%@%@%@%@", start, randomString(i), center, randomString(i), end];
NSLog(@"%3lu: %d", i, [a hash] == [b hash]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment