CCKeyDerivationPBKDF on iOS5 - iphone

I'm trying to write a password encryption function into my app, following this article.
I wrote a function that runs the CCCalibratePBKDF function and outputs the number of rounds.
const uint32_t oneSecond = 1000;
uint rounds = CCCalibratePBKDF(kCCPBKDF2,
predictedPasswordLength,
predictedSaltLength,
kCCPRFHmacAlgSHA256,
kCCKeySizeAES128,
oneSecond);
This works perfectly, but when I try to implement the next part it all goes wrong.
I can start writing the CCKeyDerivationPBKDF function call and it auto-completes the function and all the parameters. As I go through filling it in all the parameters are also auto-completed.
- (NSData *)authenticationDataForPassword: (NSString *)password salt: (NSData *)salt rounds: (uint) rounds
{
const NSString *plainData = #"Fuzzy Aliens";
uint8_t key[kCCKeySizeAES128] = {0};
int keyDerivationResult = CCKeyDerivationPBKDF(kCCPBKDF2,
[password UTF8String],
[password lengthOfBytesUsingEncoding: NSUTF8StringEncoding],
[salt bytes],
[salt length],
kCCPRFHmacAlgSHA256,
rounds,
key,
kCCKeySizeAES128);
if (keyDerivationResult == kCCParamError) {
//you shouldn't get here with the parameters as above
return nil;
}
uint8_t hmac[CC_SHA256_DIGEST_LENGTH] = {0};
CCHmac(kCCHmacAlgSHA256,
key,
kCCKeySizeAES128,
[plainData UTF8String],
[plainData lengthOfBytesUsingEncoding: NSUTF8StringEncoding],
hmac);
NSData *hmacData = [NSData dataWithBytes: hmac length: CC_SHA256_DIGEST_LENGTH];
return hmacData;
}
But as soon as I hit ; it marks an error saying "No matching function for call to 'CCKeyDerivationPBKDF'" and it won't build or anything.
I've imported CommonCrypto/CommonKeyDerivation.h and CommonCrypto/CommonCryptor.h as both of these were necessary for the enum names.

First, make sure that you haven't done anything funny with your include path (in particular, I do not recommend #HachiEthan's solution, which just confuses things). In general, leave this alone, and specifically don't add things like /usr/include to it. Make sure you've added Security.framework to your link step. This is the usual cause of problems.
The biggest thing you want to be sure of is that you're getting the iOS 5 Security.framework (rather than some other version like the OS X 10.6 or iOS 4 versions). But my suspicion is that you have a problem with your build settings.
If you want to see a framework that does all of this for reference, take a look at RNCryptor.

Right, I've found the problem (and solution).
Because I was using ZXing I had to rename the .m file to .mm so it could run the C++ stuff in the ZXing library.
I don't know why but renaming the file this way broke the CCKeyDerivationPBKDF function.
I've now moved the crypto code into it's own class and left it as .m and all I need now is to include the two imports as I did in the original post.
I didn't have to include any frameworks or anything.

Related

how to determine how much time needed when calling moveItemAtURL:toURL: or replaceItemAtURL:WithItemAtURL:

When moving file from one place to another, or when replacing file, I always use the methods moveItemAtURL:toURL: or replaceItemAtURL:WithItemAtURL: from NSFileManager.
When calling these methods, I want to determine how much time needed, so that I can use the NSProgressIndicator to tell users how long it's going to take. Just like when you are moving file using OSX, it tells u how much time remaining.
I have looked at the apple doc but couldn't find any information regarding this.
Wondering if this can be implemented, please advise.
You can't know in advance haw long it going to take. What you can do is compute the "percent complete" while you are copying the file. But to do that you need to use lower level APIs. You can use NSFileManagers attributesOfItemAtPath:error to get the file size and NSStreams for doing the copying (there are so many way to do this). Percent complete is bytesWritten / totalBytesInFile.
--- Edit: added sample code as a category on NSURL with a callback block passing the total number of bytes written, percen complete and estimated time left in seconds.
#import <mach/mach_time.h>
#interface NSURL(CopyWithProgress)<NSObject>
- (void) copyFileURLToURL:(NSURL*)destURL withProgressBlock:(void(^)(double, double, double))block;
#end
#implementation NSURL(CopyWithProgress)
- (void) copyFileURLToURL:(NSURL*)destURL
withProgressBlock:(void(^)(double, double, double))block
{
///
// NOTE: error handling has been left out in favor of simplicity
// real production code should obviously handle errors.
NSUInteger fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:self.path error:nil].fileSize;
NSInputStream *fileInput = [NSInputStream inputStreamWithURL:self];
NSOutputStream *copyOutput = [NSOutputStream outputStreamWithURL:destURL append:NO];
static size_t bufferSize = 4096;
uint8_t *buffer = malloc(bufferSize);
size_t bytesToWrite;
size_t bytesWritten;
size_t copySize = 0;
size_t counter = 0;
[fileInput open];
[copyOutput open];
uint64_t time0 = mach_absolute_time();
while (fileInput.hasBytesAvailable) {
do {
bytesToWrite = [fileInput read:buffer maxLength:bufferSize];
bytesWritten = [copyOutput write:buffer maxLength:bytesToWrite];
bytesToWrite -= bytesWritten;
copySize += bytesWritten;
if (bytesToWrite > 0)
memmove(buffer, buffer + bytesWritten, bytesToWrite);
}
while (bytesToWrite > 0);
if (block != nil && ++counter % 10 == 0) {
double percent = (double)copySize / fileSize;
uint64_t time1 = mach_absolute_time();
double elapsed = (double)(time1 - time0)/NSEC_PER_SEC;
double estTimeLeft = ((1 - percent) / percent) * elapsed;
block(copySize, percent, estTimeLeft);
}
}
if (block != nil)
block(copySize, 1, 0);
}
#end
int main (int argc, const char * argv[])
{
#autoreleasepool {
NSURL *fileURL = [NSURL URLWithString:#"file:///Users/eric/bin/data/english-words.txt"];
NSURL *destURL = [NSURL URLWithString:#"file:///Users/eric/Desktop/english-words.txt"];
[fileURL copyFileURLToURL:destURL withProgressBlock:^(double bytes, double pct, double estSecs) {
NSLog(#"Bytes=%f, Pct=%f, time left:%f s",bytes,pct,estSecs);
}];
}
return 0;
}
Sample Output:
Bytes=40960.000000, Pct=0.183890, time left:0.000753 s
Bytes=81920.000000, Pct=0.367780, time left:0.004336 s
Bytes=122880.000000, Pct=0.551670, time left:0.002672 s
Bytes=163840.000000, Pct=0.735560, time left:0.001396 s
Bytes=204800.000000, Pct=0.919449, time left:0.000391 s
Bytes=222742.000000, Pct=1.000000, time left:0.000000 s
I mostly concur with CRD. I just want to note that under certain common circumstances, both -moveItemAtURL:toURL: and -replaceItemAtURL:WithItemAtURL:... are very fast. When the source and destination are on the same volume, no data has to be copied or moved, only metadata. When the volume is local (as opposed to network-mounted), this typically takes negligible time. That said, it is appropriate to plan for the possibility that they could take significant time.
Also, he mentioned the copyfile() routine for moving files. A copy followed by deleting the original is the necessary approach when moving a file between volumes, but the rename() system call will perform a move within a volume without needing to copy anything. So, a reasonable approach would be to try rename() first and, if it fails with EXDEV, fall back to copyfile().
Finally, the exchangedata() system call can be used as part of a reimplementation of -replaceItemAtURL:WithItemAtURL:....
I don't recommend the approach suggested by aLevelOfIndirection because there are a lot of fiddly details about copying files. It's much better to rely on system libraries than trying to roll your own. His example completely ignores file metadata (file dates, extended attributes, etc.), for example.
The methods moveItemAtURL:toURL: and replaceItemAtURL:WithItemAtURL: are high-level operations. While they provide the semantics you want for the move/replace, as you've found out, they don't provide the kind of feedback you wish during those operations.
Apple is in the process of changing lower-level file handling routines, many are now marked as deprecated in 10.8, so you'll want to pick carefully what you choose to use. However at the lowest levels, system calls (manual section 2) and library functions (manual section 3), there are functions that you can use that are not being deprecated.
One option, there are others, is the function copyfile (manual section 3) which will copy a file or folder hierarchy and provides for a progress callback. That should give you most of the semantics of moveItemAtURL:toURL: along with progress, but you'll need to do more work for replaceItemAtURL:WithItemAtURL: to preserve safety (no data loss in case of error).
If that doesn't meet all your needs you can also look additionally at the low-evel stat and friends to find out file sizes etc.
HTH

iOS - libical / const char * - memory usage

I am using the libical library to parse the iCalendar format and read the information I need out of it. It is working absolutely fine so far, but there is one odd thing concerning ical.
This is my code:
icalcomponent *root = icalparser_parse_string([iCalData cStringUsingEncoding:NSUTF8StringEncoding]);
if (root)
{
icalcomponent *currentEvent = icalcomponent_get_first_component(root, ICAL_VEVENT_COMPONENT);
while (currentEvent)
{
while(currentProperty)
{
icalvalue *value = icalproperty_get_value(currentProperty);
char *icalString = icalvalue_as_ical_string_r(value); //seems to leak
NSString *currentValueAsString = [NSString stringWithCString:icalString
encoding:NSUTF8StringEncoding];
icalvalue_free(value);
//...
//import data
//...
icalString = nil;
currentValueAsString = nil;
icalproperty_free(currentProperty);
currentProperty = icalcomponent_get_next_property(currentEvent, ICAL_ANY_PROPERTY);
} //end while
} //end while
icalcomponent_free(currentEvent);
}
icalcomponent_free(root);
//...
I did use instruments to check my memory usage and were able to find out, that this line seems to leak:
char *icalString = icalvalue_as_ical_string_r(value); //seems to leak
If I'd copy and paste this line 5 or six times my memory usage would grow about 400kb and never get released anymore.
There is no free method for the icalvalue_as_ical_string_r method because it's returning a char *..
Any suggestions how to solve this issue? I would appreciate any help!
EDIT
Taking a look at the apple doc says the following:
To get a C string from a string object, you are recommended to use UTF8String. This returns a const char * using UTF8 string encoding.
const char *cString = [#"Hello, world" UTF8String];
The C string you receive is owned by a temporary object, and will become invalid when automatic deallocation takes place. If you want to get a permanent C string, you must create a buffer and copy the contents of the const char * returned by the method.
But how to release a char * string properly now if using arc?
I tried to add #autorelease {...} in front of my while-loop but without any effort. Still increasing memory usage...
Careful with the statement "no free method...because it's returning a char*"; that is never something you can just assume.
In the absence of documentation you can look at the source code of the library to see what it does; for example:
http://libical.sourcearchive.com/documentation/0.44-2/icalvalue_8c-source.html
Unfortunately this function can do a lot of different things. There are certainly some cases where calling free() on the returned buffer would be right but maybe that hasn't been ensured in every case.
I think it would be best to request a proper deallocation method from the maintainers of the library. They need to clean up their own mess; the icalvalue_as_ical_string_r() function has at least a dozen cases in a switch that might have different deallocation requirements.
icalvalue_as_ical_string_r returns a char * because it has done a malloc() for your result string. If your pointer is non-NULL, you have to free() it after use.

iPhone - Decrypting an AES-encrypted message with a different key than the one used to encrypt

I'm just coding basic "encrypt" and "decrypt" methods for AES on iPhone, using CCrypt.
I've been running a few tests and I was really struck about finding that, sometimes, if you try to decrypt an encrypted text using a key different than the one that was used to encrypt the plain text CCrypt would not return any errors.
Here is an example:
- (void) testDecryptTextWithTheWrongKey {
NSData *encryptKey = [Base64 decodeBase64WithString:#"+LtNYThpgIlQs2CaL00R6AuG2C/i6U1Vt1+6wfFeFMk="];
NSData *decryptKey = [Base64 decodeBase64WithString:#"yg7BvhM8npVGpAFpAESDn3IRWpe6qeQWaa1rwHiTsyU="];
NSString *plainText = #"The text to be encrypted";
NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *encrypted = [LocalCrypto encryptText:plainTextData key:encryptKey error:&error];
assertThat(error, nilValue());
assertThat(encrypted, notNilValue());
error = nil;
NSData *decrypted = [LocalCrypto decryptText:encrypted key:decryptKey error:&error];
assertThat(error, notNilValue());
assertThat(decrypted, nilValue());
}
My encrypt and decrypt methods defined in LocalCrypto simply call an internal "executeCryptoOperation" method indicating that they want to encrypt or decrypt:
+ (NSData *) executeCryptoOperation:(CCOperation)op key:(NSData *) key input:(NSData *) input error:(NSError **)error {
size_t outLength;
NSMutableData *output = [NSMutableData dataWithLength:input.length + kCCBlockSizeAES128];
CCCryptorStatus result = CCCrypt(op, // operation
kCCAlgorithmAES128, // Algorithm
kCCOptionPKCS7Padding | kCCOptionECBMode, // options
key.bytes, // key
key.length, // keylength
nil, // iv
input.bytes, // dataIn
input.length, // dataInLength,
output.mutableBytes, // dataOut
output.length, // dataOutAvailable
&outLength); // dataOutMoved
if (result == kCCSuccess) {
output.length = outLength;
} else {
*error = [NSError errorWithDomain:kCryptoErrorDomain code:result userInfo:nil];
return nil;
}
return output;
}
Well, my question is: is it normal that CCrypt returns kCCSuccess when we try to decrypt the encrypted text with a different key than the one used during the encrpytion? Am I missing something or doing something wrong?
It is true that even when CCrypt returns success for the decryption, I can't get a proper NSString out of the resulting data but I would certainly expect CCrypt to return some sort of error in this situation (as Java would probably do).
If this is the normal behavior, how am I supposed to know if the decrypt operation returned the real plain text or just a bunch of bytes that don't make any sense?
There is a similar question here, but the answer doesn't really convince me: Returning wrong decryption text when using invalid key
Thanks!
There are cipher algorithms which include padding (like the PKCS#5 padding in your Java implementation), and there are ones which don't.
If your encryption algorithm used padding, the corresponding decryption algorithm expects that there will be well-formed padding in the decrypted plaintext, too. This serves as a cheap partial integrity check, since with a wrong key the output likely will not have a right padding. (The chance that a random n-byte block (n=16 for AES) has a valid PKCS#5 padding is 1/256 + 1/(256^2) + ... + 1/(256^n), which is only slightly more than 1/256.)
It might be that your objective-C CCCrypt function does not check that the padding is valid, only its last byte (or even only some bits of this last byte), to see how many bytes were padded (and are now to be cut off).
If you want to make sure that the key is right, encrypt some known part of the plaintext, and error out if it is not in the decrypted part. (But don't do this with ECB mode, see below.)
If you also want to make sure that the data was not modified, also use a MAC, or use a combined authenticated encryption mode of operation for your block cipher.
Another note: You should not use ECB mode, but instead a secure mode of operation (about any other mode indicated in this article and supported by your implementation will do - standard nowadays is CBC or CTR mode). Some modes (like CFB, OFB and CTR) don't need padding at all.
You're missing the fact that the decryption function has no idea whatsoever what the plaintext (decrypted data) is supposed to look like.
As far as the decryption function is concerned, it got a key and a ciphertext from you, applied the decryption routine to the ciphertext using the key you provided, and no errors arose. Hence, success.
It's your job to verify that the plaintext you got was actually correct/on the format you expected it to be.

How to get locale on iPhone in C++?

Everything I see about iPhone localization is, unsurprisingly, in Objective-C. The project I'm working on is already written and working on iPhone using almost entirely C++, and we have a few complete translations already. All we need now, is a way to find out the locale/language code. On the computer, this is done using getenv, checking "LANG", or if that's not set "LC_ALL". This doesn't seem to work on the iPhone (neither is set to anything), so I need some other method.
As far as I can tell, the best way to do it with Objective-C is:
NSString* languageCode = [[NSLocale preferredLanguages] objectAtIndex:0];
But then I'd have to convert from NSString* to char*/std::string (which can be done, but it's generally annoying/messy). So I'm wondering, is there an easier way to get the locale from C++ directly?
Here's what I ended up doing:
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#include <CoreFoundation/CoreFoundation.h>
#endif
/* ... */
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
CFArrayRef localeIDs = CFLocaleCopyPreferredLanguages();
if (localeIDs)
{
CFStringRef localeID = (CFStringRef)CFArrayGetValueAtIndex(localeIDs, 0);
char tmp[16];
if (CFStringGetCString(localeID, tmp, 16, kCFStringEncodingUTF8))
locale = std::string(tmp); //this is the std::string
CFRelease(localeIDs);
}
#endif
Probably you want to use CFLocaleGetValue()

Encrypting streaming content onto persistent storage and decrypting it to the stream on iPhone

My app "streams" content (fixed sized files, hence quotation marks) from an HTTP server into a local file. Then there is another component of the app that opens that same file and displays it (plays it).
This is done for caching purposes, so that when the same file is requested next time, it will no longer need to be downloaded from the server.
App's spec requires that all local content is encrypted (even with the most light weight encryption)
Question: has there been done any work, allowing one to simply redirect the stream to a library which will then save the stream encrypted into a file? And then, when I request the stream from the local file, the library returns an on the fly decrypted stream?
I've been searching for a solution with no results so far
Thanks
I ended up writing a custom solution that uses RC4 encryption from the built in Crypt library. It was surprisingly straight forward. Basically it involved creating a function that encrypts/decrypts chunks of NSData and then read/write those chunks to files... Here's the function that does the encryption in case someone else is interested:
- (NSData*)RC4EncryptDecryptWithKey:(NSString *)key operation:(CCOperation)operation
{
// convert to C string..
int keySize = [key length];
char keyPtr[keySize];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr
maxLength:sizeof(keyPtr)
encoding:NSUTF8StringEncoding];
// encode/decode
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength;
void *buffer = malloc(bufferSize);
size_t numBytesOut = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmRC4,
kCCOptionECBMode,
keyPtr,
8,
NULL,
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesOut);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer
length:numBytesOut
freeWhenDone:YES];
}
free(buffer);
return nil;
}
- (NSData*)RC4EncryptWithKey:(NSString*)key {
return [self RC4EncryptDecryptWithKey:key operation:kCCEncrypt];
}
- (NSData*)RC4DecryptWithKey:(NSString*)key {
return [self RC4EncryptDecryptWithKey:key operation:kCCDecrypt];
}
Obviously one could create something more secure (eg AES) or whatever (in fact I used examples of other encryption wrappers to write this one)
I wouldn't worry about encryption just because Apple says so.
Make this work how you want it (without encryption, it sounds like) and submit it for approval. If approved, you're good. If not, worry about it then. If your design requires you to make a decision now, your design might be flawed.