Hi everyone I'm working with symmetric encryption in my app to encrypt messages that users send to each other. Now I'm trying to create a fairly secure key to decrypt this data (decryption key) using an NSMutableData. Currently I have two questions:
Is a 256-bit key for decryption safe enough?
I have some problems with NSString. When I want to retrieve the string value of the NSMutableData my NSLog always returns me a null value
Where am I doing wrong?
NSMutableData *masterKey = [NSMutableData dataWithLength:32];
int result = SecRandomCopyBytes(kSecRandomDefault, 32, masterKey.mutableBytes);
if (result != noErr) {
NSLog(FAILED_MASTERKEY);
return;
}
NSLog(@"MASTER %@",[[NSString alloc] initWithData:masterKey encoding:NSUTF32StringEncoding]);
2018-11-28 16:06:31.803868+0100 [41860:9341804] MASTER (null)
You cannot create NSString
directly from arbitrary binary data. Alternatives range from displaying hexadecimal representation (e.g. from the description
method) or using some other text representation of binary data (e.g. base-64). But you can't just pass random binary data to -[NSString initWithData:encoding:]
.
NSLog(@"Hex: %@", [masterKey description]);
NSLog(@"Hex: %@", masterKey); // directly logging the `NSData` will also use its `description`
NSLog(@"Base 64: %@", [masterKey base64EncodedStringWithOptions:0]);
The common technique for exchanging binary data via web service is base-64. But if the intent was merely to log the value so that you could see that, indeed, a value was generated, then just logging its description
is simplest.