Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random 256bit key using SecRandomCopyBytes( ) in iOS

I have been using UUIDString as an encrption key for the files stored on my iPAD, but the security review done on my app by a third party suggested the following.

With the launch of the application, a global database key is generated and stored in the keychain. During generation, the method UUIDString of the class NSUUID provided by the iOS is used. This function generates a random string composed of letters A to F, numbers and hyphens and unnecessarily restricts the key space, resulting in a weakening of the entropy. Since the key is used only by application logic and does not have to be read, understood or processed by an individual, there is no need to restrict the key space to readable characters. Therefore, a random 256-bit key generated via SecRandomCopyBytes () should be used as the master key.

Now I have searched a lot and tried some code implementation but havent found the exact thing. What I have tried:

NSMutableData* data = [NSMutableData dataWithLength:32];
int result = SecRandomCopyBytes(kSecRandomDefault, 32, data.mutableBytes);
NSLog(@"Description %d",result);

My understanding is that this should give me an integer and I should convert it to an NSString and use this as my key, but I am pretty sure that this is not what is required here and also the above method always gives the result as 0. I am completely lost here and any help is appreciated.

Thanks.

like image 731
Ankit Srivastava Avatar asked Nov 19 '14 08:11

Ankit Srivastava


3 Answers

The result of SecRandomCopyBytes should always be 0, unless there is some error (which I can't imagine why that might happen) and then the result would be -1. You're not going to convert that into a NSString.

The thing you're trying to get are the random bytes which are being written into the mutable bytes section, and that's what you'll be using as your "master key" instead of the UUID string.

The way I would do it would be:

uint8_t randomBytes[16];
int result = SecRandomCopyBytes(kSecRandomDefault, 16, randomBytes);
if(result == 0) {
    NSMutableString *uuidStringReplacement = [[NSMutableString alloc] initWithCapacity:16*2];
    for(NSInteger index = 0; index < 16; index++)
    {
        [uuidStringReplacement appendFormat: @"%02x", randomBytes[index]];
    }
    NSLog(@"uuidStringReplacement is %@", uuidStringReplacement);
} else {
    NSLog(@"SecRandomCopyBytes failed for some reason");
}

Using a UUIDString feels secure enough to me, but it sounds like your third party security audit firm is trying really hard to justify their fees.

EDITED: since I'm now starting to collect downvotes because of Vlad's alternative answer and I can't delete mine (as it still has the accepted checkmark), here's another version of my code. I'm doing it with 16 random bytes (which gets doubled in converting to Hex).

like image 61
Michael Dautermann Avatar answered Oct 31 '22 21:10

Michael Dautermann


The NSData generated does not guarantee UTF16 chars.

This method will generate 32byte UTF string which is equivalent to 256bit. (Advantage is this is plain text and can be sent in GET requests ext.)

Since the length of Base64 hash is = (3/4) x (length of input string) we can work out input length required to generate 32byte hash is 24 bytes long. Note: Base64 may pad end with one, two or no '=' chars if not divisible.

With OSX 10.9 & iOS 7 you can use:

-[NSData base64EncodedDataWithOptions:]

This method can be used to generate your UUID:

+ (NSString*)generateSecureUUID {
    NSMutableData *data = [NSMutableData dataWithLength:24];

    int result = SecRandomCopyBytes(NULL, 24, data.mutableBytes);

    NSAssert(result == 0, @"Error generating random bytes: %d", result);

    NSString *base64EncodedData = [data base64EncodedStringWithOptions:0];

    return base64EncodedData;
}
like image 43
Vlad Avatar answered Oct 31 '22 21:10

Vlad


A UUID is a 16 bytes (128 bits) unique identifier, so you aren't using a 256 bits key here. Also, as @zaph pointed out, UUIDs use hardware identifiers and other inputs to guarantee uniqueness. These factors being predictable are definitely not cryptographically secure.

You don't have to use a UUID as an encryption key, instead I would go for a base 64 or hexadecimal encoded data of 32 bytes, so you'll have your 256 bit cryptographically secure key:

/** Generates a 256 bits cryptographically secure key.
 * The output will be a 44 characters base 64 string (32 bytes data
 * before the base 64 encoding).
 * @return A base 64 encoded 256 bits secure key.
 */
+ (NSString*)generateSecureKey
{
    NSMutableData *data = [NSMutableData dataWithLength:32];
    int result = SecRandomCopyBytes(kSecRandomDefault, 32, data.mutableBytes);
    if (result != noErr) {
        return nil;
    }
    return [data base64EncodedStringWithOptions:kNilOptions];
}

To answer the part about generate UUID-like (secure) random numbers, here's a good way, but remember these will be 128 bits only keys:

/** Generates a 128 bits cryptographically secure key, formatted as a UUID.
 * Keep that you won't have the same guarantee for uniqueness
 * as you have with regular UUIDs.
 * @return A cryptographically secure UUID.
 */
+ (NSString*)generateCryptoSecureUUID
{
    unsigned char bytes[16];
    int result = SecRandomCopyBytes(kSecRandomDefault, 16, bytes);
    if (result != noErr) {
        return nil;
    }
    return [[NSUUID alloc] initWithUUIDBytes:bytes].UUIDString;
}

Cryptography is great, but doing it right is really hard (it's easy to leave security breaches). I cannot recommend you more the use of RNCryptor, which will push you through the use of good encryption standards, will make sure you're not unsafely reusing the same keys, will derivate encryption keys from passwords correctly, etc.

like image 2
Micha Mazaheri Avatar answered Oct 31 '22 21:10

Micha Mazaheri