Encrypting / Decrypting / Base64 Encode / Decode in iPhone Objective-C

I went through websites to find good tricks to send encrypted data to my server. Here is encryption / decryption functions by Jeff and Base 64 functions by Cyrus

Include following headers:

#import "NSData-AES.h"
#import "Base64.h"

Implementation:

	NSString *password = @"mypassword";
	NSString *str = @"hello world 123"; 

	// 1) Encrypt
	NSLog(@"encrypting string = %@",str);

	NSData *data = [str dataUsingEncoding: NSASCIIStringEncoding];
	NSData *encryptedData = [data AESEncryptWithPassphrase:password];

	// 2) Encode Base 64
	// If you need to send over internet, encode NSData -> Base64 encoded string
	[Base64 initialize];
	NSString *b64EncStr = [Base64 encode:encryptedData];

	NSLog(@"Base 64 encoded = %@",b64EncStr);

	//////////////////// Send this data over network /////////////////////////////////////	

	// 3) Decode Base 64
	// Then you can put that back like this
	NSData	*b64DecData = [Base64 decode:b64EncStr];

	// 4) Decrypt
	// This should be same before encode -> decode base 64
	//NSData *decryptedData = [encryptedData AESDecryptWithPassphrase:password];
	NSData *decryptedData = [b64DecData AESDecryptWithPassphrase:password];

	NSString* decryptedStr = [[NSString alloc] initWithData:decryptedData encoding:NSASCIIStringEncoding];

	NSLog(@"decrypted string = %@",decryptedStr);

Download Sample Code : CryptTest.

By: kiichi on: