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

我的未来我决定 提交于 2019-12-06 14:00:19

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/840386/gravatar-for-iphone-how-do-i-generate-a-hexadecimal-md5-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!