Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

iphone - How do I create a hash of a file on iOS?

I'm trying to create unique file names by renaming them using their hashed value in iOS. How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you could achieve this by extending NSString, Try this in your .h:

@interface NSString(MD5)

- (NSString *)generateMD5Hash

@end

and this in your .m

- (NSString*)generateMD5Hash
{
  const char *string = [self UTF8String];
  unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
  CC_MD5(string, strlen(string), md5Buffer);
  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;
}

you can implement this by making a new class called NSString+MD5, and inserting the code above in the corresponding files (.h and .m)

EDIT: Do not forget to import

< CommonCrypto/CommonDigest.h >

EDIT 2:

And for NSData;

@interface NSData(MD5)

- (NSString *)generateMD5Hash;

@end

your .m:

- (NSString *)generateMD5Hash
{
  unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
  CC_MD5(self.bytes, (CC_LONG)self.length, md5Buffer);
  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;
}

Please note that the value returned is autorelease and might need to be retained by the receiver.

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...