NSDataのMD5を計算する方法

データ転送したときに妥当性チェックにMD5を使いたい。でもどーやって計算すればいいんだろと思ってたらNSDataからMD5を計算する方法みっけ。 :-)


カテゴリを使って NSData に組み込んでる。こんな感じ。

NSData+MD5.h

@interface NSData(MD5)
- (NSString *)MD5;
@end

NSData+MD5.m

#import <CommonCrypto/CommonDigest.h>

@implementation NSData(MD5)

- (NSString*)MD5 {
  // Create byte array of unsigned chars
  unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
 
  // Create 16 byte MD5 hash value, store in buffer
  CC_MD5(self.bytes, self.length, md5Buffer);
 
  // Convert unsigned char 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;
}
@end


同じ方法でNSStringのMD5の計算方法も紹介してくれてる。

#import <CommonCrypto/CommonDigest.h>
 
@implementation NSString(MD5)
 
- (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;
}


なるほどね :-)