Search code examples
cocoaencryptionbyteinitialization-vector

Generate random bytes Cocoa?


I need to generate some random data to append to my file for encryption. How would I go about doing this? Would it be sort of the same idea as generating a string of random characters?

Something like:

NSData *randomData = @"what should i put here?";

And then use the rand() function to randomize the data?

Your help is greatly appreciated


Solution

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

    For example:

    uint8_t data[100];
    int err = 0;
    
    // Don't ask for too many bytes in one go, that can lock up your system
    err = SecRandomCopyBytes(kSecRandomDefault, 100, data);
    if(err != noErr)
        @throw [NSException exceptionWithName:@"..." reason:@"..." userInfo:nil];
    
    NSData* randomData = [[NSData alloc] initWithBytes:data length:100];
    

    As noted by Peter in the comments, you can also do this:

    NSMutableData* data = [NSMutableData dataWithLength:100];
    err = SecRandomCopyBytes(kSecRandomDefault, 100, [data mutableBytes]);
    

    And as noted by Rob in the comments, you need to link Security.framework for SecRandomCopyBytes to be available. You also need to include SecRandom.h.