0

I want to generate a key with Salt for AES 256 encryption.I am using BBASE lib, referred this link: Create random 128 bit AES Encryption key in iOS

My code is:

    NSData* salt = [BBAES randomDataWithLength:BBAESSaltDefaultLength];
            NSData *key = [BBAES keyBySaltingPassword:@"password" salt:salt         keySize:BBAESKeySize256 numberOfIterations:BBAESPBKDF2DefaultIterationsCount];
            NSLog(@"Data ASE Key %@",key);
            NSString *aString  = [[NSString alloc] initWithData:key encoding:NSUTF8StringEncoding];

I want to use this 'key' into the following code:(here I am using RNCryptor lib)

    NSData *encryptedData = [ RNEncryptor encryptData:bodyData withSettings:kRNCryptorAES256Settings password:aString error:&error];

    NSData *decryptedData = [RNDecryptor decryptData:encryptedData withSettings:kRNCryptorAES256Settings password:aString error:&error];

I need to pass key of type NSString,But when I am converting NSData to NSString it gives NULL value and my application crashes. What should I do?? Is there any solution for this ??

Community
  • 1
  • 1
  • 1
    RNCryptor will perform the key derivation for you, using a random salt. Is there any reason you want to do this derivation yourself? – Duncan Jones Sep 25 '14 at 07:36

2 Answers2

2

Not all data is a valid UTF-8 string, most random data is not. Basically that is why Base64 exists, to convert 8-bit data to an ASCII string--and back. There are of course other methods.

But as Duncan states, why? Read the RNCryptor code, it already handles converting a password (string) to a secure key.

zaph
  • 111,848
  • 21
  • 189
  • 228
-2

Thank you @Duncan & @Zaph :) I found a solution!!

Instead of

    NSString *aString  = [[NSString alloc] initWithData:key encoding:NSUTF8StringEncoding];

I used this:

    NSString *aString  = [[NSString alloc] initWithData:key encoding:NSASCIIStringEncoding];