Calculating MD5

19 02 2008

On Leopard, you can use CC_MD5 function to produce MD5 hashed data. Here is a code snippet which computes MD5 from NSString.

#import <CommonCrypto/CommonDigest.h>             // contains declaration of CC_MD5 

NSString *testString = @"Test";                   // String data that needs md5 checksum
const char *test_cstr = [testString UTF8String];  // Get data as C language string.
unsigned char md5_result[CC_MD5_DIGEST_LENGTH];   // storage for checksum result
CC_MD5(test_cstr, strlen(test_cstr), md5_result); // do calculation

If you want hexadecimal representation of the checksum as NSString, use stringWithFormat(taken from CocoaDev: MDFive).

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

NSLog(hex_str);

In case you are not sure if the result is correct or not, compare hexidecimal string with other calculation method.
Try this.

perl -MDigest::MD5=md5_hex -le 'print md5_hex("Test")'

Actions

Information

Leave a comment