iphone cbc encryption returning null - iphone

I have the following code inside the NSData+AES256 class. I am trying AES CBC encryption to a NSString with the following code. I have a key and a iv. But getting null in result. Can not find out what's wrong. This is what I tried-
NSString *initV= #"somekey*********";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCModeCBC,
keyPtr, kCCKeySizeAES256,
[input bytes] /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);

This is the code that worked for me finally-
-(NSData *)AES256EncryptWithKey:(NSString *)key {
NSUInteger dataLength = [self length];
NSData *keyGiven= [key dataUsingEncoding:NSUTF8StringEncoding];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
NSString *initV= #"***************";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];
size_t numBytesEncrypted = 0;
CCCryptorRef ccRef;
CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, 0, (const void *)[keyGiven bytes], kCCKeySizeAES256, (const void *)[input bytes], &ccRef);
CCCryptorStatus cryptStatus = CCCryptorUpdate(ccRef, [self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);
CCCryptorRelease(ccRef);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
I am converting an NSString to NSData and passing it for encryption. The NSString must be of 16 characters. If it is of less than 16 characters I make it 16 by appending spaces.
I don't know if this is going to help anybody. But I just thought I should share. Thanks.

Related

Unable to decrypt the video file on iPhone

I need to decrypt a video file on the iPhone.
Server is using Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
In iPhone I am using the following code (pastie link), but I am not able to decrypt the file successfully.
#import <CommonCrypto/CommonCryptor.h>
#implementation NSData (AES256)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+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, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* 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 *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+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, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* 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 dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
#end
I have found the solution. changing below line worked for me as an alternative to "AES/ECB/NoPadding" mode in java.
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);

Sqlite database Protection in iPhone

I am devloping an application which stores a huge amount of data in the sqlite database. But I want to keep the data safe so that no one hacks my database and see the data in my database.
Now how can I encrypt and decrypt my sqlite database?
Pls help me.
Thanks.
I was developed an app that require and I've used this way
First of all, I've initiated a class, called it ConstantMethods.h+m
ConstantMethods.h
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h>
static NSString *keyEncryption = #"YourPrivateKey";
#interface ConstantMethods : NSObject {
}
+ (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key;
+ (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key;
#end
ConstantMethods.m
#import "ConstantMethods.h"
#implementation NSData (AES256)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+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, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* 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 *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+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, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* 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 dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
#end
#implementation ConstantMethods
+ (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}
+ (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
encoding:NSUTF8StringEncoding] autorelease];
}
#end
Then, in your class, import the ConstantMethods.h and use the class as the following:
[ConstantMethods encryptString:#"yourString"];
and when you want to decrypt, use the following:
[ConstantMethods decryptData:#"yourString" withKey:keyEncryption];
After the encryption, insert the encrypted data to the database, and when retrieving the data from database, decrypt it.
I hope that this can help you.

Objective-C decrypt AES 128 cbc hex string

I am developing an application for iPhone on Snow Leopard with Xcode 3.1 that receives from a restful web service an encrypted text in hexadecimal format with the algorithm AES 128-bit (CBC). The algorithm uses an initialization vector + secret key. How do I decrypt this text? Thanks to everyone for the tips that I will succeed in giving.
EDIT:
I get response from REST Server in hex AND crypted format,I try with this code but i receive always bad param error. Can you help me to find the error?
Is it possible that i firstly convert the string response into binary format?
NSString *response = [request responseString];
NSData *encryptedData = [response dataUsingEncoding: NSASCIIStringEncoding];
NSString *key = #"32charlength";
NSString *iv = #"16charlength";
NSData *unencryptedData = NULL;
size_t unencryptedLength = [unencryptedData length];
CCCryptorStatus ccStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key, kCCKeySizeAES128, iv, [encryptedData bytes], [encryptedData length], unencryptedData, [encryptedData length], &unencryptedLength);
NSString *output = [[NSString alloc] initWithBytes:unencryptedData length:unencryptedLength encoding:NSUTF8StringEncoding];
if (ccStatus == kCCSuccess) risultato.text = #"SUCCESS";
else if (ccStatus == kCCParamError) risultato.text = #"BAD PARAM";
else if (ccStatus == kCCBufferTooSmall) risultato.text = #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) risultato.text = #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) risultato.text = #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) risultato.text = #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) risultato.text = #"UNIMPLEMENTED";
EDIT2:
this function return BAD PARAM because haven't the right buffer size where allocate decrypted data. I edit the function in this working way:
NSData *encryptedData = [response dataUsingEncoding: NSASCIIStringEncoding];
const void *key = #"32charlength;
uint8_t *iv = #"16charlength";
char buffer[4*4096];
memset(buffer, '\0', sizeof(buffer));
size_t size = sizeof(buffer);
CCCryptorStatus ccStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
0,
key,
kCCKeySizeAES128,
iv,
[encryptedData bytes],
[encryptedData length],
buffer,
sizeof(buffer),
&size);
This function working for me.. thanks so much.
EDIT 23 MARCH------
Now the system work form me with 16 byte key size. Now i have a question, what i can do to implement 32 byte key size ? thanks so much.
This is possible using the CCCryptor functions included in the <CommonCrypto/CommonCryptor.h> header. Check man CCCryptor for the gory details, in your case it sounds like you can use a single call to CCCrypt() to decode the received data:
CCCryptorStatus
CCCrypt(CCOperation op, CCAlgorithm alg, CCOptions options, const void *key, size_t keyLength,
const void *iv, const void *dataIn, size_t dataInLength, void *dataOut, size_t dataOutAvailable,
size_t *dataOutMoved);
Assuming you have the data to be decrypted in NSData *encryptedData you could try something like:
char * key = "shouldbe16chars.";
NSUInteger dataLength = [encryptedData length];
uint8_t unencryptedData[dataLength + kCCKeySizeAES128];
size_t unencryptedLength;
CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key, kCCKeySizeAES128, NULL, [encryptedData bytes], dataLength, unencryptedData, dataLength, &unencryptedLength);
NSString *output = [[NSString alloc] initWithBytes:unencryptedData length:unencryptedLength encoding:NSUTF8StringEncoding];
This is untested, make sure you check the return value of CCCrypt for errors. Check the header file for details, it is well documented.

iPhone AES encryption issue

I use following code to encrypt using AES.
- (NSData*)AES256EncryptWithKey:(NSString*)key theMsg:(NSData *)myMessage {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 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 = [myMessage 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, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[myMessage 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;
}
However the following code chunk returns null if I tried to print the encryptmessage variable. Same thing applies to decryption as well. What am I doing wrong here?
NSData *encrData = [self AES256EncryptWithKey:theKey theMsg:myMessage];
NSString *encryptmessage = [[NSString alloc] initWithData:encrData encoding:NSUTF8StringEncoding];
Thank you
try using
size_t bufferSize= dataLength + kCCBlockSizeAES256;
instead of
size_t bufferSize = dataLength + kCCBlockSizeAES128;

iPhone SDK CCCrypt 3DES and ECB mode always returns PARAM ERROR

I've seen quite a lot of posts about CCCrypt and 3DES on the iPhone at various places around the Net, but there does not seem to be a working example of using it with ECB mode, always with PKCS7Padding.
Does anyone have any working code to encrypt and decrypt a passed string using 3DES and ECB mode using the CCCrypt function?
Currently my code (which I admit came from a site somewhere, I think it was Apple's own developer forums) is as follows:
+ (NSString*)doCipher:(NSString*)plainText action:(CCOperation)encryptOrDecrypt {
const void *vplainText;
size_t plainTextBufferSize;
if (encryptOrDecrypt == kCCDecrypt) {
NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:plainText];
plainTextBufferSize = [EncryptData length];
vplainText = [EncryptData bytes];
}
else {
//plainTextBufferSize = [plainText length];
//vplainText = (const void *)[plainText UTF8String];
NSData *plainTextData = [plainText dataUsingEncoding: NSUTF8StringEncoding];
plainTextBufferSize = [plainTextData length];
vplainText = [plainTextData 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,
kCCOptionECBMode,
vkey, //"123456789012345678901234", //key
kCCKeySize3DES,
nil, //"init Vec", //iv,
vplainText, //"Your Name", //plainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
//if (ccStatus == kCCSuccess) NSLog(#"SUCCESS");
/*else*/ if (ccStatus == kCCParamError) 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";
NSString *result;
if (encryptOrDecrypt == kCCDecrypt) {
result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding] autorelease];
}
else {
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [myData base64EncodingWithLineLength:movedBytes];
}
return result; }
The above ALWAYS fails with PARAM ERROR.
- (NSData *) encrypt:(NSString *) dataToEncrypt{
NSUInteger data_length= [dataToEncrypt length];
uint8_t input_raw_data[data_length];
//The [dataToEncrypt length] gives the number of chars present in the string.So say there are 10 chars.
//Now,the getBytes needs to get the raw bytes from this i.e. binary NSData.But suppose the encoding was
//full 16 bit encoding then the number of bytes needed wd have been double- 20.But as we are using the
//NSUTF8StringEncoding,the number of byes needed is 1 per char as the chars(even if originally unicode are
//compressed into an 8 bit UTF8 encoding.)
[dataToEncrypt getBytes:&input_raw_data maxLength:data_length usedLength:NULL encoding:NSUTF8StringEncoding options:0 range:NSMakeRange(0,data_length) remainingRange:NULL];
//According to 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 buffer_size = data_length + kCCBlockSizeAES128;
void* buffer = malloc(buffer_size);
size_t num_bytes_encrypted = 0;
CCCryptorStatus crypt_status = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[self.symmetricKey bytes], kCCKeySizeAES256,
NULL,
input_raw_data, data_length,
buffer, buffer_size,
&num_bytes_encrypted);
NSLog(#"~~num bytes encrypted: %d",num_bytes_encrypted);
if (crypt_status == kCCSuccess){
NSLog(#"~~Data encoded successfully...");
return [NSData dataWithBytesNoCopy:buffer length:num_bytes_encrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData *) decrypt:(NSData *) dataToDecrypt{
NSUInteger data_length= [dataToDecrypt 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 buffer_size = data_length + kCCBlockSizeAES128;
void* buffer = malloc(buffer_size);
size_t num_bytes_decrypted = 0;
CCCryptorStatus crypt_status = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[self.symmetricKey bytes], kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[dataToDecrypt bytes], data_length, /* input */
buffer, buffer_size, /* output */
&num_bytes_decrypted);
NSLog(#"~~num bytes decrypted: %d",num_bytes_decrypted);
if (crypt_status == kCCSuccess){
NSLog(#"~~Data decoded successfully...");
return [NSData dataWithBytesNoCopy:buffer length:num_bytes_decrypted];
}
free(buffer); //free the buffer;
return nil;
}
The above code worked for me, with some changes. The changes are i decelare the moveBytes and bufferPtf as instance variable and did following chandge.
if (encryptOrDecrypt == kCCDecrypt) {
plainTextBufferSize = movedBytes;
vplainText = bufferPtr;
}
else {
plainTextBufferSize = [plainText length];
vplainText = (const void *)[plainText UTF8String];
}
instead base64encoding use nsasciiencoding.