Symmetric Encryption for Windows and iPhone (part 2)
Previous post describes how to implement Windows-part solution for encrypting files on Windows and decrypting these files on Apple iPhone.
This post contains the implementation details of Apple iPhone platform.
There is a Security.framework in iPhone SDK with the CommonCryptor.h library which contain all needed functions for encrypting/decrypting procedures.
There is already implemented solutions for symmetric encrypting/decrypting: implementation of symmetric encryption for iPhone is one of these implementations.
All I need is to update this solution for decrypting RC4-128 algorythm.
Let’s start from the very begging and focus on the input parameters of the CCCryptorCreate function:
// Create and Initialize the crypto reference.
ccStatus = CCCryptorCreate(encryptOrDecrypt, kCCAlgorithmRC4, *pkcs7, (const void *)[aSymmetricKey bytes], kChosenCipherKeySize, (const void *)iv, &thisEncipher);
Things to mention: the 1st parameter is (CCOperation)encryptOrDecrypt; the 2nd is the algorithm type – kCCAlgorithmRC4 in our case; the 3d – (CCOptions *)pkcs7 I leaved as is – there is no need to updated these options; the 4th – (const void *) key – symmetric key data – there is a description below how to create this kind of key; the 5th parameter kChosenCipherKeySize – key size should 16 bytes in this case; the 6th parameter – vector – should be empty; the last – the 7th – reference to Cryptor.
There are to defines that should be the same – we are going to use 128bit-length (16 byte) key.
#define kChosenCipherBlockSize 16
#define kChosenCipherKeySize 16
Symmetric Key in our case this is (NSData *) class and it contains has “secret word”, there is a code below how to create the key using md5 algorithm:
// char presentation of (NSString *) secretWord
const char * cStr = [secretWord UTF8String];
// length of the Secret Word
int iLength = [str length];
// preparing data for CC_MD5 result
unsigned char result[iLength];
memset(result, 0x0, iLength);
// creating data
CC_MD5( cStr, iLength, result);
// data we return
NSData * dataToReturn = [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH];
Things to mention: the Secret Word comes as (NSString *); we use only CC_MD5_DIGEST_LENGTH bytes to present key as NSData – all other things is done by CC_MD5; the key as (NSData *) is created and can be used to decrypt anything.
That’s all – these solutions can be used for symmetric encryption and decryption any kind of data on MS Windows and Apple iPhone platforms.