0

I am trying to encrypt/decrypt one field of SQLite3 database stored in iPhone app.

I am using this category mentioned in this question.

While encrypting, I am using following code:

NSString *key = @"pass123";
NSString *secret = webNote.note;

NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256EncryptWithKey:key];

sqlite3_bind_text(statement, 1, [[cipher description] UTF8String], -1, SQLITE_TRANSIENT);    

It does save data into the field in 74657874 20746f20 656e6372 797074 format.

But while decrypting, I get blank field (tried everything I knew). I am using following code for decrypting:

char *noteDet = (char *)sqlite3_column_text(statement, 1);

NSString *key = @"pass123";
NSString *secret = [NSString stringWithUTF8String:noteDet];

NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];

NSData *clean = [secretData AES256DecryptWithKey:key];
aNote.note = ([[NSString alloc] initWithData:clean encoding:NSUTF8StringEncoding])?[[NSString alloc] initWithData:clean encoding:NSUTF8StringEncoding]:@"";

I think, I am unable to convert types. Please guide!

Thanks!

Community
  • 1
  • 1
BufferStack
  • 549
  • 9
  • 20

1 Answers1

1

The description of NSData returns something like "" => if you were to read that again you would get different overall data ( and of a higher length ), also you are right that you are not converting the data types correctly.

Try saving the NSData object directly, by saving the bytes themselves rather than the description of the NSData object.

void *bytes = [dataObject bytes];
size_t length = [dataObject length];
Antwan van Houdt
  • 6,989
  • 1
  • 29
  • 52
  • Yes.. converting data type to BLOB, and then saving as bytes did help - but data is being decrypted with random success. Some rows get blank null data (display nothing), but gets on reloading. Any idea why this is happening? – BufferStack Nov 13 '11 at 17:57
  • not sure.. try dumping your variables through logging or using the debugger to check each value. You could also check using a SQLite browser or the command line to see what the contents of your database are. – Antwan van Houdt Nov 13 '11 at 18:06
  • I checked.. there is content before `NSData *clean = [secretData AES256DecryptWithKey:key];`, but in some cases.. it results null after that.. and on reloading these get it.. and some other not! Anyhow thanks for the answer. – BufferStack Nov 13 '11 at 18:15