Karim Fikani
Karim Fikani

Reputation: 356

NSString initWithBytes with openssl encrypted data returns nil with NSUTF8StringEncoding

I'm having an issue where I'm trying to create an NSString from encrypted data created by OpenSSL and I keep getting nil for the string.

The code that I'm using to encrypt and decrypt the data is taken from the following link http://saju.net.in/code/misc/openssl_aes.c.txt

Now here is the code where I'm calling to encrypt my data ("aes_init" is of course called on my application init):

//-- encrypt saved data
int textLen = str.size();
char* buff = const_cast<char*>(str.c_str());

EVP_CIPHER_CTX encryptCtx;
unsigned char *ciphertext = aes_encrypt(&encryptCtx,
                                    reinterpret_cast<unsigned char*>(buff),
                                    &textLen);

NSString * nsstring = [[NSString alloc] initWithBytes:reinterpret_cast<const char*>(ciphertext)
                                    length:strlen(reinterpret_cast<const char*>(ciphertext))
                                        encoding:NSUTF8StringEncoding];
[nsstring autorelease];

UIApplication* clientApp = [UIApplication sharedApplication];
AppController* appController = ((AppController *)clientApp.delegate);
[appController saveData:nsstring]; //--> crash at this line

I've tried different Encoding (NSASCIIStringEncoding and NSUnicodeStringEncoding) and they don't crash but the data is completely wrong after I decode.

Any ideas on how to solve this issue?

Thanks :)

Upvotes: 0

Views: 146

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93978

Ciphertext, the output of an encryption function, should be indistinguishable from random. Meaning that any byte value can be generated, including byte values that do not map to characters. Hence it is needed to encode the ciphertext, for instance using base 64 encoding.

Upvotes: 1

Related Questions