//
//  NSString+Digest.m
//  Talk
//
//  Created by LiDong on 11-4-1.
//  Copyright 2011 HXHG. All rights reserved.
//

#import "NSString+Digest.h"
#import <CommonCrypto/CommonDigest.h>
#import "Base64.h"


@implementation NSString (MD5)

- (NSString *)MD5 {
	const char *source = [self UTF8String];
	u_char md5[CC_MD5_DIGEST_LENGTH];
	
	CC_MD5(source, strlen(source), md5);
	
	return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7], md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]];
}

- (NSString *)SHA256 {
	const char *source = [self UTF8String];
	u_char sha256[CC_SHA256_DIGEST_LENGTH];
	NSMutableString *retString = [NSMutableString stringWithCapacity:128];
	
	CC_MD5(source, strlen(source), sha256);
	
	for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++ i) {
		[retString appendFormat:@"%02X", sha256[i]];
	}
	return retString;
}

- (NSString *)Base64FromMD5 {
	const char *source = [self UTF8String];
	u_char md5[CC_MD5_DIGEST_LENGTH];
	
	CC_MD5(source, strlen(source), md5);
    
	NSString *base64 = stringEncodedByBase64FromBytes(md5, CC_MD5_DIGEST_LENGTH, true);
    
    DLog(@"BASE64_MD5: %@", base64);
    
    return [base64 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)UUID {
	const char *source = [self UTF8String];
	u_char md5[CC_MD5_DIGEST_LENGTH];
	
	CC_MD5(source, strlen(source), md5);
	
	return [NSString stringWithFormat:@"%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7], md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]];
}

@end
