Wednesday, July 27, 2011

MD5 with JSON KIT in iOS

// Header File NSString+MD5.h
#import "NSString+MD5.h"



@interface NSString(MD5)
- (NSString *)MD5;
@end


// Implementation File NSString+MD5.m#import <CommonCrypto/CommonDigest.h>
@implementation NSString(MD5)

- (NSString*)MD5
{
        // Create pointer to the string as UTF8
  const char *ptr = [self UTF8String];

        // Create byte array of unsigned chars
  unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];

        // Create 16 bytes MD5 hash value, store in buffer
  CC_MD5(ptr, strlen(ptr), 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

JSON KIT :

Download JSON KIT from here JSON KIT

Example :

//Import necessary header
#import "NSString+MD5.h" 

#import <CommonCrypto/CommonDigest.h>
#import "JSONKit.h"//Code example
NSMutableDictionary *jsonEncode = [NSMutableDictionary dictionary];
    [jsonEncode setValue:emailField.text forKey:@"email"];
    [jsonEncode setValue:[passwordField.text MD5] forKey:@"password"];
NSString *jsonString = [jsonEncode JSONString];

No comments: