my humble self

Catalin Voss - [twitter]

So, you want to do MD5 hashing on the iPhone?

 

This works with the standard libraries that come with Mac OS X:

#include <openssl/md5.h>
NSString *someString = @”I like Doritos.”;
NSData *data = [someString dataUsingEncoding:PickYourEncoding];

unsigned char *digest = MD5([data bytes], [data length], NULL);

Yeah, it works. If you need to be absolutely thread safe, use your own buffer instead of using the static one. Now, how do we make a cool helper class out of this? On the iPhone, well, we don’t. It took me a while to figure out that the cool kids use CC_MD5:

NSString *someString = @”I like Doritos.”;
const char *str = [someString UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);

A MD5 digest is a 16 byte binary result, not a string. So CC_MD5_DIGEST_LENGTH is defined as 16 in CommonDigest.h.

Let’s go through the result and append the %02x format, so we get a proper hash.
I ended up doing it this way: 

+ (NSString *)md5HexDigestStringOfString:(NSString *)inString {

const char *str = [inString UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);

NSMutableString *returnString = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];

for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
   [returnString appendFormat:@”%02x”,result[i]];
}

return returnString;

}

For CC_MD5 you need to import <CommonCrypto/CommonDigest.h> which is part of the security framework on the iPhone.

Happy coding!



UILabel should look native as seen in Table Views?

Do this:

theLabel.textColor = [UIColor colorWithRed:0.30 green:0.34 blue:0.42 alpha:1.0];
theLabel.backgroundColor = [UIColor clearColor];
theLabel.shadowColor = [UIColor whiteColor];
theLabel.shadowOffset = CGSizeMake(0.0, 1.0);
theLabel.font = [UIFont boldSystemFontOfSize:18];
theLabel.textAlignment = UITextAlignmentCenter;


[code snippet] ABAddressBook on the iPhone - add entry to contacts

Core Foundation Plumbing:

ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef person = ABPersonCreate();


ABRecordSetValue(person, kABPersonFirstNameProperty, @"First" , nil);
ABRecordSetValue(person, kABPersonLastNameProperty, @"Last", nil);
ABAddressBookAddRecord(addressBook, person, nil);
ABAddressBookSave(addressBook, nil);

CFRelease(person);

You need to import ‘AddressBook/AddressBook.h’ and ‘AddressBook/ABPerson.h’.
Happy coding!