Create random 128 bit AES Encryption key in iOS

跟風遠走 提交于 2019-11-29 10:14:56

问题


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];
}

回答1:


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.




回答2:


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




回答3:


This might help

- (NSString *)getRandomKey{
    NSString *alphabet  = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789/=+";
    NSMutableString *s = [NSMutableString stringWithCapacity:20];
    for (NSUInteger i = 0; i < 20; i++) {
        u_int32_t r = arc4random() % [alphabet length];
        unichar c = [alphabet characterAtIndex:r];
        [s appendFormat:@"%C", c];
    }
    NSLog(@"%@", s);
    NSString *key = s;
    return key;
}


来源:https://stackoverflow.com/questions/23531515/create-random-128-bit-aes-encryption-key-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!