Friday, May 6, 2011

Gravatar for Iphone? How do I generate a hexadecimal MD5 hash?

I'd like to use gravatar in my iPhone application. Is there anyway to generate a hexadecimal MD5 hash in Objective-C for iPhone? Using openssl on iPhone is a no-go.

From stackoverflow
  • This is how I did it before I removed it from my app:

    #import <CommonCrypto/CommonDigest.h>
    
    NSString* md5( NSString *str ) {
      const char *cStr = [str UTF8String];
      unsigned char result[CC_MD5_DIGEST_LENGTH];
    
      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]
          ] lowercaseString];
    }
    

    It's only fair to add that I didn't write this myself. I found it somewhere on the internet but I didn't record where.

  • The code I used for generating the necessary MD5 hash is up on my github repository, in the CommonCrypto subfolder. There are a bunch of similar routines in there which will either show you how to use CommonCrypto or how to format strings of hex byte values, base-64, etc.

    A potentially better way of generating the string would be:

    NSMutableString * str = [[NSMutableString alloc] initWithCapacity: 33];
    int i;
    for ( i = 0; i < 16; i++ )
    {
      [str appendFormat: @"%02x", result[i]];
    }
    NSString * output = [str copy];
    [str release];
    return ( [output autorelease] );
    

    If you're going to use the code in the answer above, however, I'd personally suggest changing the %02X's to %02x and forgoing the -lowercaseString call completely-- might as well generate the hex values lowercase to start with.

0 comments:

Post a Comment