I need to hash a string using the MD5 technique in cocoa. Any frameworks that are used must be able to be accessed on the iphone. please provide code if possible.
Well, first off, MD5 isn't encryption. So if you're looking for encryption, you're looking in the wrong place.
But if you just want to hash something using MD5 on an iPhone, this should give you the information you need: Calculate MD5 on iPhone
MD5 is not encryption, it is a cryptographic hash function. It's a one-way function whose output is a 128-bit number. The fact that it is cryptographic means that it is a computationally hard problem that, given an MD5 hash output, compute a string whose MD5 is that value. So, MD5 can be used for data integrity checks, but not for encryption.
The good thing about MD5 is that it isn't encryption. When you start using encryption on your iPhone, you need to comply to a lot of guidelines etc too.
Also, when you hash a string, you can't get that string back from the hash.
I added the following to my "NSString+MyGoonk" category:
#include <openssl/md5.h>
- (NSString *)md5
{
NSData *data = [self dataUsingEncoding: NSUTF8StringEncoding];
unsigned char *digest = MD5([data bytes], [data length], NULL);
return [NSString stringWithUTF8String: (char *)digest];
}
Two things:
this assumes your string is UTF8. I'm sure there's a way to make it more generic, but I almost never use anything else.
you have to link -lcrypto into your project.
This is what I use. Credits go to Alistair McMillan.
#import <CommonCrypto/CommonDigest.h>
+ (NSString *) md5:(NSString *)str {
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result );
return [NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
NOTE #1: I didn't have to link to any libraries
NOTE #2: I couldn't find -lcrypto in the external framework list on the iphone, and this works without -lcrypto
After spending too much time trying to figure this out I made a comprehensive post with correct code and how to use it. You can find the post here on my blog. http://www.saobart.com/md5-has-in-objective-c/
Noticed this in the Facebook Connect source code. Looks pretty solid, give it a shot.
#import <CommonCrypto/CommonDigest.h>
...
+ (NSString*)md5HexDigest:(NSString*)input {
const char* str = [input UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
[ret appendFormat:@"%02x",result[i]];
}
return ret;
}
...
FYI: CC_MD5() is 10.5+ although the manual says 10.4. If you need 10.4 compatibility use CC_MD5_Init(), CC_MD5_Update() and CC_MD5_Final() instead.