I am trying to add two MD5 hash values in Objective-c.
i have imported the CommonCrypto/CommonDigest.h
Header file and converted two strings into MD5 hash using CC_MD5 function.
How do I perform addition of these two hash values?
I am trying to add two MD5 hash values in Objective-c.
i have imported the CommonCrypto/CommonDigest.h
Header file and converted two strings into MD5 hash using CC_MD5 function.
How do I perform addition of these two hash values?
As some people said in the linked post, it's not true that MD5hash(part1 + part2) = MD5hash(part1) + MD5hash(part2). Maybe try this solution: http://www.joel.lopes-da-silva.com/2010/09/07/compute-md5-or-sha-hash-of-large-file-efficiently-on-ios-and-mac-os-x/ . I haven't tested it, but the code should work for you. You're feeding subsequent parts of your file into CC_MD5_Update(...) and to get the final hash, just call CC_MD5_Final(...). It's probably the only way you can process large files, if that's your aim.
Sorry if I'm missing something.
I've made a NSString category for hashing:
- (NSString *)MD5 {
// Create pointer to the string as UTF8
const char *ptr = [self UTF8String];
// Create byte array of unsigned chars
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
// Create 16 byte MD5 hash value, store in buffer
CC_MD5(ptr, strlen(ptr), md5Buffer);
// Convert MD5 value in the buffer to NSString of hex values
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x",md5Buffer[i]];
}
return output;
}
I dont know why would you like to add two hashes together but this might help you.
@PiotrK seems to have the most helpful answer. I reviewed the code at the link, and it looks pretty good (didn't try it myself, either). However, two items regarding the code at the link. First, Lopes-da-silva (the author of the PiotrK's link) argues against creating a local autorelease pool as that would be inefficient. This myth has been debunked. Go ahead and create and destroy autorelease pools, it's cheap (although this code is probably faster). Second, the linked code declares "buffer" (which ought to be reused) inside the while loop; it ought to be scoped outside the while loop. Most likely, a compiler would handle this by allocating the buffer on the stack frame only once and not per loop. But, ironically, it could create the very problem the author was hoping to avoid by coding around an autorelease pool.
Finally, for the OP, I'm hoping by ADD you meant streaming data through the MD5 Hash algorithm and aren't intending to invent your own security algorithm. That's usually a bad idea. If you are trying something novel in the security algorithm world, I would refer you to some Cryptography Books, like Applied Cryptography by Bruce Schneier. Or, just clarify your question above with what you're trying to accomplish.