Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create random 128 bit AES Encryption key in iOS

I want to create random AES Encryption key (128 bit) in ios. I have searched in SO but I cannot find a good answer. Please give me some advice. thanks in advance.

UPDATE:

I have used BBAES lib. I used the below code to generate the encryption key but when I convert from NSData to NSString, it shows NULL

  -(NSData*)randomDataWithLength{
    NSData* salt = [BBAES randomDataWithLength:BBAESSaltDefaultLength];
    NSData *key = [BBAES keyBySaltingPassword:@"password" salt:salt keySize:BBAESKeySize128 numberOfIterations:BBAESPBKDF2DefaultIterationsCount];
    NSLog(@"Data ASE Key %@",key);
    NSString *aString  = [[NSString alloc] initWithData:key encoding:NSUTF8StringEncoding];
}
like image 332
user3214941 Avatar asked May 08 '14 02:05

user3214941


People also ask

Can AES 128 be hacked?

Is 128-bit AES secure? AES has never been cracked yet and is safe against any brute force attacks contrary to belief and arguments.

Is AES key random?

An attacker would be able to narrow down the key search space, robbing the strength of AES. Hence, it's of utmost importance that the keys are truly random.

How many rounds of AES do you get with a 128-bit key?

128-bit AES encryption undergoes 10 transformation rounds; 192-bit AES encryption undergoes 12 transformation rounds; and 256-bit AES encryption undergoes 14 transformation rounds.


2 Answers

Woah, that's complicated code for a simple task!

- (NSData *)random128BitAESKey {
    unsigned char buf[16];
    arc4random_buf(buf, sizeof(buf));
    return [NSData dataWithBytes:buf length:sizeof(buf)];
}

You probably heard somewhere that you should use salt and hash your passwords. It looks like you took this advice a little too far: there are no passwords here and yet your code still salts and hashes the data! This is completely useless when the input comes from a secure random number generator like arc4random.

Of course it won't convert to an NSString because random data is unlikely to be valid UTF-8 string.

like image 156
Dietrich Epp Avatar answered Oct 01 '22 19:10

Dietrich Epp


You might want to use Apple's random byte generator for this which is considered more secure than arc4random.

int SecRandomCopyBytes ( SecRandomRef rnd, size_t count, uint8_t *bytes ); 

https://developer.apple.com/library/ios/documentation/Security/Reference/RandomizationReference/index.html#//apple_ref/c/func/SecRandomCopyBytes

A good explanation for this can be found on a blog post by James Carroll:

http://jamescarroll.xyz/2015/09/09/safely-generating-cryptographically-secure-random-numbers-with-swift/

Open Whisper Systems use this for the iOS version of their popular secure chat app Signal

like image 43
Patrick Domegan Avatar answered Oct 01 '22 19:10

Patrick Domegan