NSData Quickies

From macwrench
Jump to navigation Jump to search

MD5-Prüfsumme erstellen

Folgender Header muss dazu importiert werden:

#import <CommonCrypto/CommonDigest.h>

Methode 1:

- (NSString *)md5
{
	unsigned char digest[16];
	char finaldigest[32];
	int i;
	
	MD5([self bytes],[self length],digest);
	for(i=0;i<16;i++) sprintf(finaldigest+i*2,"%02x",digest[i]);
	
	return [[[NSString alloc] initWithBytes:finaldigest length:32 encoding:NSUTF8StringEncoding] autorelease];
}

Methode 2 (statisch):

+ (NSString *)md5StringFromData:(NSData *)data
{
    void *cData = malloc([data length]);
    unsigned char resultCString[16];
    [data getBytes:cData length:[data length]];

    CC_MD5(cData, [data length], resultCString);
    free(cData);

    return [NSString stringWithFormat:
                        @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                        resultCString[0], resultCString[1], resultCString[2], resultCString[3], 
                        resultCString[4], resultCString[5], resultCString[6], resultCString[7],
                        resultCString[8], resultCString[9], resultCString[10], resultCString[11],
                        resultCString[12], resultCString[13], resultCString[14], resultCString[15]
                        ];
}

Siehe auch