'iPhone'에 해당되는 글 1건

  1. 2014.11.21 [iOS] 문자열 해쉬값 구하기 (NSString MD5)
2014. 11. 21. 11:40
NSString을 확장하는 방식으로 구현한 방법입니다.

<헤더>

 #import <Foundation/Foundation.h>


@interface NSData(MD5)


 

- (NSString*)MD5;


@end


<구현부>

#import <CommonCrypto/CommonDigest.h>

#import "NSDataMD5.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 

 

 

출처 : http://skyrack.tistory.com/117

 

덧붙임 : 원글에서는 NSString을 확장하는 방식이라 했으나 소스를 보면 NSString이 아닌

             NSData를 카테고리를 이용해서 처리하는 방식임. NSString으로 할 경우 self.bytes에서

             경고가 발생합니다. 

Posted by 작은0악마