Powered By Blogger

Thursday, April 26, 2012

AES Encryption and Decryption

Hello friends,
I'm going to share AES Encryption and Decryption Method for Securely sending your data over the web. Please check the below code :


Step 1: First you have to include these two files into your project.

#include <CommonCrypto/CommonCryptor.h>

@interface NSData(AES)
- (NSData*)AES128Decrypt;
- (NSData*)AES128Encrypt;
@end


#import "NSData+AES.h"

NSString *iv = @"fedcba9876543210";
NSString *key = @"0123456789abcdef";

@implementation NSData (AES)

-(NSData*)AES128Encrypt
{
    char ivPtr[kCCKeySizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
   
    // fetch iv data
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
   
   
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
   
    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
   
    NSUInteger dataLength = [self length];
   
    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize           = dataLength + kCCBlockSizeAES128;
    void* buffer                = malloc(bufferSize);
   
    size_t numBytesEncrypted    = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0,
                                          keyPtr, kCCKeySizeAES128,
                                           ivPtr/* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesEncrypted);
   

    if (cryptStatus == kCCSuccess)
    {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
   
   free(buffer); //free the buffer;
    return nil;
}

- (NSData*)AES128Decrypt
{
    char ivPtr[kCCKeySizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
   
    // fetch iv data
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
   
   

    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
   
    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
   
   
    NSUInteger dataLength = [self length];
   
    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize           = dataLength + kCCBlockSizeAES128;
    void* buffer                = malloc(bufferSize);
   
    size_t numBytesDecrypted    = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0,
                                          keyPtr, kCCKeySizeAES128,
                                          ivPtr /* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesDecrypted);
   
    if (cryptStatus == kCCSuccess)
    {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytes:buffer length:numBytesDecrypted] ;
    }
   
    free(buffer); //free the buffer;
    return nil;
}

@end

Step 2: You have to import "Security.framework" into your project.

Step 3: Now, you need to put below code into the class where you want to Encrypt or Decrypt a string and also need to import "NSData+AES.h" file.

- (void)testActuallyEncrypting:(NSString *)hexString
{
    NSLog(@"Encrypted HexString : %@",hexString);

    NSData *data = [self dataFromHexString:hexString];
    NSData *encryptedData =  [NSData dataWithBytes:[data bytes] length:[data length]];
    NSData *decryptedData = [encryptedData AES128Decrypt];
    NSString *decryptedString = [NSString stringWithUTF8String:[decryptedData bytes]];
    NSLog(@"Decrypted String : %@",decryptedString);

    decryptedString = [self addPaddingToString:decryptedString];
    decryptedData = [NSData dataWithBytes:[decryptedString UTF8String] length:[[decryptedString dataUsingEncoding:NSUTF8StringEncoding] length]];
    encryptedData = [decryptedData AES128Encrypt];
    if (encryptedData!=nil)
    {
        NSString *encryptedHexString = [self hexStringFromData:encryptedData];
        NSLog(@"Encrypted HexString : %@",encryptedHexString);

//        NSData *data1 = [self dataFromHexString:encryptedHexString];
//        NSData *encryptedData1 =  [NSData dataWithBytes:[data1 bytes] length:[data1 length]];
//        NSData *decryptedData1 = [encryptedData1 AES128Decrypt];
//        NSString *decryptedString1 = [NSString stringWithUTF8String:[decryptedData1 bytes]];
//        NSLog(@"Decrypted String Testing 123: %@",[decryptedString1 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]]);
    }
}

Step 4 : For step3 , you have to add these three methods into your code.

// For Converting incoming HexString into NSData
- (NSData *)dataFromHexString:(NSString *)string
{  
    NSMutableData *stringData = [[[NSMutableData alloc] init] autorelease];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [string length] / 2; i++) {
        byte_chars[0] = [string characterAtIndex:i*2];
        byte_chars[1] = [string characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }
    return stringData;
}


// For converting Encrypted Data into NSString after the encryption
- (NSString*)hexStringFromData:(NSData *)data
{
    unichar* hexChars = (unichar*)malloc(sizeof(unichar) * (data.length*2));
    unsigned char* bytes = (unsigned char*)data.bytes;
    for (NSUInteger i = 0; i < data.length; i++) {
        unichar c = bytes[i] / 16;
        if (c < 10) c += '0';
        else c += 'a' - 10;
        hexChars[i*2] = c;
        c = bytes[i] % 16;
        if (c < 10) c += '0';
        else c += 'a' - 10;
        hexChars[i*2+1] = c;
    }
    NSString* retVal = [[NSString alloc] initWithCharactersNoCopy:hexChars
                                                           length:data.length*2
                                                     freeWhenDone:YES];
    return [retVal autorelease];
}
// For padding into a string for required string length
-(NSString *)addPaddingToString:(NSString *)string
{
    NSInteger size = 16;
    NSInteger x = [string length]%size;
    NSInteger padLength = size - x;
    for (int i=0; i<padLength; i++)
    {
        string = [string stringByAppendingString:@" "];
    }
    return string;
}

 By following  all above steps, you will be able to Implement AES Encryption and Decryption. If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati

NSData to HexString and HexString to NSData

Hi everyone,
Here, I've put two different methods for the conversion of "HEXString" to "NSData" and "NSData" to "HEXString".  you may get help from these two. Please ask if you have any query.


- (NSData *)dataFromHexString:(NSString *)string
{  
    NSMutableData *stringData = [[[NSMutableData alloc] init] autorelease];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [string length] / 2; i++) {
        byte_chars[0] = [string characterAtIndex:i*2];
        byte_chars[1] = [string characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }
    return stringData;
}

- (NSString*)hexStringFromData:(NSData *)data
{
    unichar* hexChars = (unichar*)malloc(sizeof(unichar) * (data.length*2));
    unsigned char* bytes = (unsigned char*)data.bytes;
    for (NSUInteger i = 0; i < data.length; i++) {
        unichar c = bytes[i] / 16;
        if (c < 10) c += '0';
        else c += 'a' - 10;
        hexChars[i*2] = c;
        c = bytes[i] % 16;
        if (c < 10) c += '0';
        else c += 'a' - 10;
        hexChars[i*2+1] = c;
    }
    NSString* retVal = [[NSString alloc] initWithCharactersNoCopy:hexChars
                                                           length:data.length*2
                                                     freeWhenDone:YES];
    return [retVal autorelease];
}


If any one has query then share it over here.

Thanks and Regards,
Nilesh Prajapati
 

Wednesday, April 25, 2012

Video recording in iPhone SDK

Hi,
Here is the integration code for Video Recording in your application. Please check it and follow the steps for integration of it.
You have to add "MobileCoreServices" framework in to your project source.

#import <UIKit/UIKit.h>


@interface AddVideoViewController : UIViewController <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIImagePickerController *imagepicker;
}

-(IBAction)startRecording:(id)sender;
@end



#import "AddVideoViewController.h"

#include <MobileCoreServices/UTCoreTypes.h>
#include <MobileCoreServices/UTType.h>

@implementation AddVideoViewController


#pragma mark -
#pragma mark UIView life - cycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark -
#pragma mark UIImagePickerController delegate methods


-(IBAction)startRecording:(id)sender
{
    imagepicker = [[UIImagePickerController alloc]init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepicker.videoMaximumDuration = 10.0; // you can add more time limit for automatic record end
        imagepicker.delegate = self;
        imagepicker.allowsEditing = YES;
        imagepicker.showsCameraControls = YES;
        imagepicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
        imagepicker.videoQuality =  UIImagePickerControllerQualityTypeMedium;
        [self presentModalViewController:imagepicker animated:YES];
    }
    else
    {
        imagepicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        imagepicker.delegate = self;
        [imagepicker setAllowsEditing:YES];
        imagepicker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentModalViewController:imagepicker animated:YES];
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSURL *urlString = [info valueForKey:UIImagePickerControllerMediaURL];
    NSData *videoData = [NSData dataWithContentsOfURL:urlString];
    NSArray *Path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [Path objectAtIndex:0];
    NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"video.mov"];
    [videoData writeToFile:filePath atomically:YES];
    UISaveVideoAtPathToSavedPhotosAlbum(filePath, self, @selector(video:didFinishSavingWithError:contextInfo:), filePath);
    [self dismissModalViewControllerAnimated:YES];
}

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
   
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
   
}

#pragma mark -
#pragma mark memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
   
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc
{
    [super dealloc];
}

@end


If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati
 

Tuesday, April 17, 2012

How to create UITableView in iOS SDK ?

Hello friends ,
   I'm going to explain you how to create table view by programmatically  in iOS application. Please follow the below code and be sure to include/ set its delegate and datasource property. You have to set "UITableViewDataSource" and "UITableViewDelegate" into the .h[header section] of a class.

UITableView *tblView = [[UITableView alloc]init];
tblView.frame = CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height); // here , you can set you tableview's frame in view.
tblView.delegate = self; // for delegate methods this one need to set compulsary
tblView.dataSource = self;// for datasource methods this one need to set compulsary
tblView.tag = 3; // Tag is used to make the seperation between multiple tables.
[self.view addSubview:tblView]; // place tableview on the main view on which you want to display it.

@optional  // Optional method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;             
{
    return numberOfsection; // Default is 1 if not implemented
}

@required  // required datasource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return numberOfRowsInEachSection;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell=[tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
        cell.textLabel.text = @"Hello"; // You can place you content string here what you want to show in each row of the tableview

    return cell;
}

@required // Required delegate methods

- (void)tableView:(UITableView *)tableView1 didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *viewController = [[DetailViewController alloc]initWithNibName:@"DetailView" bundle:nil];
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

Hope, by this you may get idea about to create a table-view pro-grammatically in an application.



Thanks and Regards,
Nilesh Prajapati
 

Monday, April 2, 2012

UIColor using HexCode

Here is the useful method for retrieving UIColor using the HexCode in your application. So, you can use your customize colors in application development.


- (UIColor *)colorWithHexCode:(NSString *)strHexCode
{
     NSString *cString = [[strHexCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
   
     // String should be 6 or 8 characters
     if ([cString length] < 6) return [UIColor grayColor];
   
     // strip 0X if it appears
     if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
   
     if ([cString length] != 6) return [UIColor grayColor];
   
     // Separate into r, g, b substrings
     NSRange range;
     range.location = 0;
     range.length = 2;
     NSString *rString = [cString substringWithRange:range];
   
     range.location = 2;
     NSString *gString = [cString substringWithRange:range];
   
     range.location = 4;
     NSString *bString = [cString substringWithRange:range];
   
     // Scan values
     unsigned int red, green, blue;
     [[NSScanner scannerWithString:rString] scanHexInt:&red];
     [[NSScanner scannerWithString:gString] scanHexInt:&green];
     [[NSScanner scannerWithString:bString] scanHexInt:&blue];
   
     return [UIColor colorWithRed:(red / 255.0f)
                      green:(green / 255.0f)
                       blue:(blue / 255.0f)
                      alpha:1.0f];
}




Thanks and Regards,
Nilesh Prajapati