OAuth signature with RSA-SHA1 on iOS - iphone

I need help creating an RSA-SHA1 signature to be used in a 3-legged OAuth implementation on iOS.
I was able to do this using HMAC-SHA1 using CommonCrypto.h, but this library doesn't seem to support RSA-SHA1.
Have any of you implemented OAuth signatures with RSA? Could you point me to some resources where I can find more information?
Thanks.

The answer by Erik Villegas was also the solution for me. But there is a bug in the posted code which I encountered when using this solution: secretFile was opened with fopen(), so it must be closed with fclose()
- (NSString *)RSASHA1HashForString:(NSString *)source {
NSLog(#"encrypting %#", source);
if (source == nil) return nil;
OpenSSL_add_all_algorithms();
NSString *signature = nil;
// make a SHA-1 digest of the source string
const char* sourceChars = [source UTF8String];
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1((const unsigned char *)sourceChars, strlen(sourceChars), digest);
NSString *path = [[NSBundle mainBundle] pathForResource:#"privatekey" ofType:#"pem"];
const char *pathCString = [path cStringUsingEncoding:NSUTF8StringEncoding];
FILE *secretFile = fopen(pathCString, "r");
RSA *rsa = NULL;
PEM_read_RSAPrivateKey(secretFile, &rsa, NULL, NULL);
if (rsa != NULL) {
unsigned int sigLen = 0;
unsigned char *sigBuff = malloc(RSA_size(rsa));
int result = RSA_sign(NID_sha1, digest, (unsigned int) sizeof(digest),
sigBuff, &sigLen, rsa);
if (result != 0) {
NSData *sigData = [NSData dataWithBytes:sigBuff length:sigLen];
signature = [self base64forData:sigData];
}
free(sigBuff);
RSA_free(rsa);
}
fclose(secretFile);
NSLog(#"generated signature: %#", signature);
return signature;
}

I finally found the solution. Here is a method that will look for a privatekey.pem file in your bundle and create a RSA-SHA1 signature using the string that is passed in. You will need to add the openssl library. You can use this project as a reference: https://github.com/x2on/OpenSSL-for-iPhone
- (NSString *)RSASHA1HashForString:(NSString *)source {
NSLog(#"encrypting %#", source);
if (source == nil) return nil;
OpenSSL_add_all_algorithms();
NSString *signature = nil;
// make a SHA-1 digest of the source string
const char* sourceChars = [source UTF8String];
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1((const unsigned char *)sourceChars, strlen(sourceChars), digest);
NSString *path = [[NSBundle mainBundle] pathForResource:#"privatekey" ofType:#"pem"];
const char *pathCString = [path cStringUsingEncoding:NSUTF8StringEncoding];
FILE *secretFile = fopen(pathCString, "r");
RSA *rsa = NULL;
PEM_read_RSAPrivateKey(secretFile, &rsa, NULL, NULL);
if (rsa != NULL) {
unsigned int sigLen = 0;
unsigned char *sigBuff = malloc(RSA_size(rsa));
int result = RSA_sign(NID_sha1, digest, (unsigned int) sizeof(digest),
sigBuff, &sigLen, rsa);
if (result != 0) {
NSData *sigData = [NSData dataWithBytes:sigBuff length:sigLen];
signature = [self base64forData:sigData];
}
free(sigBuff);
RSA_free(rsa);
}
NSLog(#"generated signature: %#", signature);
return signature;
}
If you are implementing OAuth you'll need to pass the signature base into this method. More info can be found here: http://oauth.net/core/1.0a/#anchor13

Here is implementation using core security iOS framework.
Key should be converted to pkcs12 format.
Algorythm name is "kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA1"
- (NSString *)getStringSHA1RSASignature:(NSString *)str
{
NSString *path = [[NSBundle bundleForClass:[self class]]
pathForResource:#"rsaPrivate.pfx" ofType:#"pkcs12"];
NSData *p12data = [NSData dataWithContentsOfFile:path];
NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
[options setObject:#" your password " forKey:(id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((CFDataRef)p12data, (CFDictionaryRef)options, &items);
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp =
(SecIdentityRef)CFDictionaryGetValue(identityDict,
kSecImportItemIdentity);
assert(securityError == noErr);
SecKeyRef privateKeyRef;
SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
/// have a key
NSData *input = [str dataUsingEncoding:NSUTF8StringEncoding];
CFErrorRef error = nil;
///////////////////////////////// "SHA1withRSA" java
CFDataRef signature = SecKeyCreateSignature(privateKeyRef, kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA1, (CFDataRef)input, &error);
NSAssert(signature != nil, #"");
NSString *result = [(__bridge NSData *)signature base64EncodedStringWithOptions:0];
CFRelease(signature);
NSAssert(result != nil, #"");
NSLog(#"generated signature: %#", result);
return result;
}

Related

SecPKCS12Import leak under arc?

I was found memory leaks by iOS instruments on all SecPKCS12Import lines of that code under arc:
SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, 0);
CFStringRef certSummary = SecCertificateCopySubjectSummary(certRef);
NSData *data = (__bridge_transfer NSData *) SecCertificateCopyData(certRef);
NSURL *indexURL = [[NSBundle mainBundle] URLForResource:#"cert1" withExtension:#"p12"];
NSData *localP12 = [NSData dataWithContentsOfURL:indexURL];
NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
NSString *password = ///
[options setObject:password forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) localP12,(__bridge CFDictionaryRef)options, &items);
if (securityError == noErr) { };/// good } else { //bad }
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
CFArrayRef certificates =
(CFArrayRef)CFDictionaryGetValue(identityDict,kSecImportItemCertChain);
SecCertificateRef localCert = (SecCertificateRef)CFArrayGetValueAtIndex(certificates,0);
CFDataRef dataLocal = SecCertificateCopyData(localCert);
NSData *local = (__bridge NSData *)dataLocal;
//NSLog(#"local:%#",local);
NSURL *indexURLmac3 = [[NSBundle mainBundle] URLForResource:#"cert2" withExtension:#"p12"];
NSData *localP12mac3 = [NSData dataWithContentsOfURL:indexURLmac3];
NSMutableDictionary * optionsMac3 = [[NSMutableDictionary alloc] init];
NSString *passwordMac3 = //
[optionsMac3 setObject:passwordMac3 forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef itemsMac3 = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import((__bridge CFDataRef) localP12mac3, (__bridge CFDictionaryRef)optionsMac3, &itemsMac3);
if (securityError == noErr) { };/// good } else { //bad }
CFDictionaryRef identityDictMac3 = CFArrayGetValueAtIndex(itemsMac3, 0);
CFArrayRef certificatesMac3 =
(CFArrayRef)CFDictionaryGetValue(identityDictMac3, kSecImportItemCertChain);
SecCertificateRef localCertMac3 = (SecCertificateRef)CFArrayGetValueAtIndex(certificatesMac3,0);
CFDataRef dataLocalMac3 = SecCertificateCopyData(localCertMac3);
NSData *localMac3 = (__bridge NSData *)dataLocalMac3;
NSURL *indexURLwebcob3 = [[NSBundle mainBundle] URLForResource:#"cert3" withExtension:#"p12"];
NSData *localP12wwebcob3 = [NSData dataWithContentsOfURL:indexURLwebcob3];
NSMutableDictionary * optionsWebcob3 = [[NSMutableDictionary alloc] init];
NSString *passwordWebcob3 = //
[optionsWebcob3 setObject:passwordWebcob3 forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef itemsWebcob3 = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import((__bridge CFDataRef) localP12wwebcob3, (__bridge CFDictionaryRef)optionsWebcob3, &itemsWebcob3);
if (securityError == noErr) { };/// good } else { //bad }
CFDictionaryRef identityDictWebcob3 = CFArrayGetValueAtIndex(itemsWebcob3, 0);
CFArrayRef certificatesWebcob3 =
(CFArrayRef)CFDictionaryGetValue(identityDictWebcob3,
kSecImportItemCertChain);
SecCertificateRef localCertWebcob3 = (SecCertificateRef)CFArrayGetValueAtIndex(certificatesWebcob3,0);
CFDataRef dataLocalWebcob3 = SecCertificateCopyData(localCertWebcob3);
NSData *localWebcob3 = (__bridge NSData *)dataLocalWebcob3;
if ([data isEqualToData:local] || [data isEqualToData:localMac3] || [data isEqualToData:localWebcob3]) trust = YES;
CFRelease(certSummary);
CFRelease((CFDataRef) dataLocal);
CFRelease((CFDataRef) dataLocalMac3);
CFRelease((CFDataRef) dataLocalWebcob3);
where i'm wrong?
Wow. That code is really hard to follow. You seem to be doing three different PKCS12 imports, you may want to make that a single method that's called three times. Just saying.
Anyway, without even following your code I know what the issue may be - because I have seen this before. The Security methods you are using follow the CoreFoundation memory management patterns defined here. More than once I have found the PKCS12 identity import process leaking because someone did not realize that, or thought that bridge casts to ARC would just make it work.
But here is what you should look at - in addition to whatever Instruments is trying to tell you, of course:
You need to release the items passed as the last argument to SecPKCS12Import (the CFArrayRef in the documentation). Look at Apple's example for guidance.
I see something even more obvious - you are calling CFArrayCreate without a corresponding release.

RSA decryption with openSSL

I have a problem with RSA encrypted and Base 64 encoded text decryption. When i decrypt directly encrypted text(unsigned char *) then everything is okay and I get correct result. But when I do base64 encoding, than openssl fails to decrypt data, although base64 decoded data is exactly same as was encrypted data:
For example(first is encryption result and second base 64 decoding result. Decoding first char * directly works pretty well.)
encrypted - ßÁ¨£®Òz>Ô‹n.€Ö∫BÔ–∂ü∏ÕD⁄UÖáµ)ûKufi wÆ&_è”eëõ~gK∂¶$kŸƒ∫ª`ÔfΩ˙˛{∆_MªÔëbP Q¶fl±Ü;!ü•◊s>ħ∆◊⁄≤ò˙ˇCWôVÂzôzíö≤ÙU¶?⁄l[*H?o\ñ>ƒ<‘4mœ“Lr
Íhh
decoded string - ßÁ¨£®Òz>Ô‹n.€Ö∫BÔ–∂ü∏ÕD⁄UÖáµ)ûKufi wÆ&_è”eëõ~gK∂¶$kŸƒ∫ª`ÔfΩ˙˛{∆_MªÔëbP Q¶fl±Ü;!ü•◊s>ħ∆◊⁄≤ò˙ˇCWôVÂzôzíö≤ÙU¶?⁄l[*H?o\ñ>ƒ<‘4mœ“Lr
Íhh
Code:
+(NSString *) rsaEncryptedStringFromText: (NSString *) text
{
const char *message = [text UTF8String];
NSLog(#"message - %s", message);
int bufSize;
NSString *keyFilePath = [[NSBundle mainBundle] pathForResource:#"publicKey" ofType:#"pem"];
FILE *keyfile = fopen([keyFilePath UTF8String], "r");
RSA *rsa = PEM_read_RSA_PUBKEY(keyfile, NULL, NULL, NULL);
if (rsa == NULL)
{
return nil;
}
int key_size = RSA_size(rsa);
unsigned char *encrypted = (unsigned char *) malloc(key_size);
bufSize = RSA_public_encrypt(strlen(message), (unsigned char *) message, encrypted, rsa, RSA_PKCS1_PADDING);
if (bufSize == -1)
{
RSA_free(rsa);
return nil;
}
NSLog(#"encrypted - %s", encrypted);
NSData *encryptedData = [NSData dataWithBytes:encrypted length:strlen((const char *)encrypted)];
NSString *base64 = [encryptedData base64Encoding];
RSA_free(rsa);
return base64;
}
+(NSString *) rsaDecryptToStringFromText: (NSString *) text
{
//NSLog(#"text - %#", text);
NSData *decodedData = [NSData dataWithBase64EncodedString: text];
unsigned char* message = (unsigned char*) [decodedData bytes];
NSLog(#"decoded string - %s", message);
RSA *privKey = NULL;
FILE *priv_key_file;
unsigned char *ptext;
NSString *keyFilePath = [[NSBundle mainBundle] pathForResource:#"privateKeyPair" ofType:#"pem"];
priv_key_file = fopen([keyFilePath UTF8String], "rb");
ERR_print_errors_fp(priv_key_file);
privKey = PEM_read_RSAPrivateKey(priv_key_file, NULL, NULL, NULL);
int key_size = RSA_size(privKey);
ptext = malloc(key_size);
int outlen = RSA_private_decrypt(key_size, (const unsigned char*)message, ptext, privKey, RSA_PKCS1_PADDING);
if(outlen < 0) return nil;
RSA_free(privKey);
return [NSString stringWithUTF8String: (const char *)ptext];
}
Base 64 encoding-decoding is done with this:
http://www.iphonedevsdk.com/forum/iphone-sdk-development/21689-base-64-string-help.html#post98080
Main problem was in base64 encoding+decoding class. Switched to QSutilities and everything works.

iOS zip with gzipDeflate

I'm using the NSData+compression.h and the Base64Transcoder.h elements to be able to zip and unzip content.
Basically to unzip the server responses.
The unzip method works perfectly
+ (NSString *) unzip: (NSString*) stringValue{
Byte inputData[[stringValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[[stringValue dataUsingEncoding:NSUTF8StringEncoding] getBytes:inputData];
size_t inputDataSize = (size_t)[stringValue length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);
Byte outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64DecodeData(inputData, inputDataSize, outputData, &outputDataSize);
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];
//And now we gunzip:
NSData* result = [theData gzipInflate];//make bigger==gunzip
NSString *temp = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
return temp;
}
But when I try to zip a content, using the simetric way, the gzipDeflate fails, and return an empty or nil value.
This is my zip code
+ (NSData *) zip:(NSData *) theSourceData {
// And now we zip:
NSData *result = [theSourceData gzipDeflate];
Byte inputData[[result length]];
[result getBytes:inputData];
size_t inputDataSize = (size_t)[result length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);
char outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64EncodeData(inputData, inputDataSize, outputData, &outputDataSize, NO);
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];
return theData;
}
Any suggestions?
Thanks
The problem was on the Base64 encoder.
+ (NSString *) zip:(NSData *) theSourceData {
// And now we zip:
NSData *result = [theSourceData gzipDeflate];
NSString *source = [NSString base64StringFromData:result length:[result length]];
return source;
}
We've integrated the base64StringFromData:length: method to solve it.
Thanks,
Ivan

How to decrypt a file in Objective C/IOS that is encrypted in php?

I have googled too much for this error but found nothing useful.
I am getting a file that is encrypted in php using the following code:
mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateencryptkey, base64_encode(file), MCRYPT_MODE_CBC, $hardvector);
I am unable to decrypt it in IOS. I had tried many libraries like NSDATA+CommonCrypto, NSFileManager-AES, NSDATA-aes but i have not got success in decrypting the file.
Following is the objective-C code used:
- (NSData *)AESDecryptWithPassphrase:(NSString *)pass
{
NSMutableData *ret = [NSMutableData dataWithCapacity:[self length]];
unsigned long rk[RKLENGTH(KEYBITS)];
unsigned char key[KEYLENGTH(KEYBITS)];
const char *password = [pass UTF8String];
for (int i = 0; i < sizeof(key); i++)
key[i] = password != 0 ? *password++ : 0;
int nrounds = rijndaelSetupDecrypt(rk, key, KEYBITS);
unsigned char *srcBytes = (unsigned char *)[self bytes];
int index = 0;
while (index < [self length])
{
unsigned char plaintext[16];
unsigned char ciphertext[16];
int j;
for (j = 0; j < sizeof(ciphertext); j++)
{
if (index >= [self length])
break;
ciphertext[j] = srcBytes[index++];
}
rijndaelDecrypt(rk, nrounds, ciphertext, plaintext);
[ret appendBytes:plaintext length:sizeof(plaintext)];
}
return ret;
}
This code works well for text but unable to decrypt files.
When i save the decrypted files then it says the file system error. Those decrypted files cannot be opened on any system, i think the file format is disturbed in the process.
I also tried the following code but no success:
- (NSData *) decryptedDataUsingAlgorithm: (CCAlgorithm) algorithm
key: (id) key // data or string
initializationVector: (id) iv // data or string
options: (CCOptions) options
error: (CCCryptorStatus *) error
{
CCCryptorRef cryptor = NULL;
CCCryptorStatus status = kCCSuccess;
NSParameterAssert([key isKindOfClass: [NSData class]] || [key isKindOfClass: [NSString class]]);
NSParameterAssert(iv == nil || [iv isKindOfClass: [NSData class]] || [iv isKindOfClass: [NSString class]]);
NSMutableData * keyData, * ivData;
if ( [key isKindOfClass: [NSData class]] )
keyData = (NSMutableData *) [key mutableCopy];
else
keyData = [[key dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
if ( [iv isKindOfClass: [NSString class]] )
ivData = [[iv dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
else
ivData = (NSMutableData *) [iv mutableCopy]; // data or nil
[keyData autorelease];
[ivData autorelease];
// ensure correct lengths for key and iv data, based on algorithms
FixKeyLengths( algorithm, keyData, ivData );
status = CCCryptorCreate( kCCDecrypt, algorithm, options,
[keyData bytes], [keyData length], [ivData bytes],
&cryptor );
if ( status != kCCSuccess )
{
if ( error != NULL )
*error = status;
return ( nil );
}
NSData * result = [self _runCryptor: cryptor result: &status];
if ( (result == nil) && (error != NULL) )
*error = status;
CCCryptorRelease( cryptor );
return ( result );
}
2nd function from above code:
- (NSData *) _runCryptor: (CCCryptorRef) cryptor result: (CCCryptorStatus *) status
{
size_t bufsize = CCCryptorGetOutputLength( cryptor, (size_t)[self length], true );
void * buf = malloc( bufsize );
size_t bufused = 0;
size_t bytesTotal = 0;
*status = CCCryptorUpdate( cryptor, [self bytes], (size_t)[self length],
buf, bufsize, &bufused );
if ( *status != kCCSuccess )
{
free( buf );
return ( nil );
}
bytesTotal += bufused;
// From Brent Royal-Gordon (Twitter: architechies):
// Need to update buf ptr past used bytes when calling CCCryptorFinal()
*status = CCCryptorFinal( cryptor, buf + bufused, bufsize - bufused, &bufused );
if ( *status != kCCSuccess )
{
free( buf );
return ( nil );
}
bytesTotal += bufused;
return ( [NSData dataWithBytesNoCopy: buf length: bytesTotal] );
}
I haven't been able to solve this for a week...
One thing to note is the file parameter to mcrypt_encrypt, it appears that the file is being base64 encoded prior to encryption (not that it makes any sense), that would imply you would have to base64 decode after decryption.
The other parameters are straight forward:
MCRYPT_RIJNDAEL_128 is AES, 128 with a 128 bit key
MCRYPT_MODE_CBC is cbc mode, the default for CommonCrypto.
The padding to block size is with null characters, rather nonstandard so the non-padded length may be a problem.
Not that you need yet another AES method, this is the one I use:
#import <CommonCrypto/CommonCryptor.h>
+ (NSData *)doCipher:(NSData *)dataIn
iv:(NSData *)iv
key:(NSData *)symmetricKey
context:(CCOperation)encryptOrDecrypt
{
CCCryptorStatus ccStatus = kCCSuccess;
size_t cryptBytes = 0; // Number of bytes moved to buffer.
NSMutableData *dataOut = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];
ccStatus = CCCrypt( encryptOrDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
symmetricKey.bytes,
kCCKeySizeAES128,
iv.bytes,
dataIn.bytes,
dataIn.length,
dataOut.mutableBytes,
dataOut.length,
&cryptBytes);
if (ccStatus != kCCSuccess) {
NSLog(#"CCCrypt status: %d", ccStatus);
}
dataOut.length = cryptBytes;
return dataOut;
}
// Also add Security.framework to your project.
Note that it expects NSData input and the padding is specified as standard PKCS.
See CommonCryptor.h

What is best available data encryption algorithm in IOS

i am trying to encrypt my data using before sending it to server, is there any highly secure two way encryption algorithm ? which one is best for this purpose.
Check ths once
Here, key is string variable, declare as a global variable.
add sequrity framework for your code and import
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
- (void)viewDidLoad
{
[super viewDidLoad];
key=#"Your own key";
// encoding
NSString *encodingString=[[self encrypt:[#"Your String"
dataUsingEncoding:NSUTF8StringEncoding]
base64EncodedString];;
//decoding
NSData *data=[self decrypt:[NSData dataFromBase64String:encryptString]];
NSString *decodingString = [[NSString alloc] initWithBytes:[data bytes] length:
[data length] encoding: NSASCIIStringEncoding];
}
- (NSData *) encrypt:(NSData *) plainText {
return [self transform:kCCEncrypt data:plainText];
}
- (NSData *) decrypt:(NSData *) cipherText {
return [self transform:kCCDecrypt data:cipherText];
}
- (NSData *) transform:(CCOperation) encryptOrDecrypt data:(NSData *) inputData {
// kCCKeySizeAES128 = 16 bytes
// CC_MD5_DIGEST_LENGTH = 16 bytes
NSData* secretKey = [ChipperObject md5:Key];
CCCryptorRef cryptor = NULL;
CCCryptorStatus status = kCCSuccess;
uint8_t iv[kCCBlockSizeAES128];
memset((void *) iv, 0x0, (size_t) sizeof(iv));
status = CCCryptorCreate(encryptOrDecrypt,
kCCAlgorithmAES128,kCCOptionPKCS7Padding,
[secretKey bytes], kCCKeySizeAES128, iv, &cryptor);
if (status != kCCSuccess) {
return nil;
}
size_t bufsize = CCCryptorGetOutputLength(cryptor, (size_t)[inputData length],
true);
void * buf = malloc(bufsize * sizeof(uint8_t));
memset(buf, 0x0, bufsize);
size_t bufused = 0;
size_t bytesTotal = 0;
status = CCCryptorUpdate(cryptor, [inputData bytes], (size_t)[inputData length],
buf, bufsize, &bufused);
if (status != kCCSuccess) {
free(buf);
CCCryptorRelease(cryptor);
return nil;
}
bytesTotal += bufused;
status = CCCryptorFinal(cryptor, buf + bufused, bufsize - bufused, &bufused);
if (status != kCCSuccess) {
free(buf);
CCCryptorRelease(cryptor);
return nil;
}
bytesTotal += bufused;
CCCryptorRelease(cryptor);
return [NSData dataWithBytesNoCopy:buf length:bytesTotal];
}
Here is my code using 3des CCCrypt Method,Find GTMBase64.h from googlecode, https://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/GTMBase64.h?r=87
#import <CommonCrypto/CommonCryptor.h>
#import "GTMBase64.h"
- (NSData*)TripleDES:(NSData*)plainData encryptOrDecrypt:(CCOperation)encryptOrDecrypt key:(NSString*)key {
const void *vplainText;
size_t plainTextBufferSize;
if (encryptOrDecrypt == kCCDecrypt)
{
NSData *EncryptData = [GTMBase64 decodeData:plainData];
plainTextBufferSize = [EncryptData length];
vplainText = [EncryptData bytes];
}
else
{
plainTextBufferSize = [plainData length];
vplainText = (const void *)[plainData bytes];
}
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
// uint8_t ivkCCBlockSize3DES;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// memset((void *) iv, 0x0, (size_t) sizeof(iv));
// NSString *key = #"123456789012345678901234";
NSString *initVec = #"init Vec";
const void *vkey = (const void *) [key UTF8String];
const void *vinitVec = (const void *) [initVec UTF8String];
ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
vkey, //"123456789012345678901234", //key
kCCKeySize3DES,
vinitVec, //"init Vec", //iv,
vplainText, //"Your Name", //plainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
//if (ccStatus == kCCSuccess) NSLog(#"SUCCESS");
/*else if (ccStatus == kCC ParamError) return #"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return #"UNIMPLEMENTED"; */
NSData *result;
if (encryptOrDecrypt == kCCDecrypt)
{
result = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
}
else
{
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [GTMBase64 encodeData:myData];
}
return result;
}
Usage
NSString *inputString = #"good";
//encode
NSData *inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
NSData *encriptdata = [self TripleDES:inputData encryptOrDecrypt:kCCEncrypt key:#"ff68f8e82961489a8b14b345"];
NSString *encodeString = [GTMBase64 stringByEncodingData:encriptdata];
NSLog(#"encodeString : %#" ,encodeString);
//decode
NSData *encodeData = [GTMBase64 decodeString:encodeString];
NSData *decodeData = [self TripleDES:encodeData encryptOrDecrypt:kCCDecrypt key:#"ff68f8e82961489a8b14b345"];
NSString *decodeString = [[NSString alloc] initWithBytes:[decodeData bytes] length:[decodeData length] encoding:NSUTF8StringEncoding];
NSLog(#"decodeString : %#" ,decodeString);
Public Key Infrastructure (PKI) offers you a trustworthy way to encrypt data between 2 machines. You can give it a try.
You can use HTTPS, or you can also use RC6 to encrypt your data.