Generate random Cocoa bytes?

I need to generate some random data to add to my file for encryption. How can I do it? Would it be the same idea as generating a string of random characters?

Sort of:

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

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

Your help is greatly appreciated

+6
source share
2 answers

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

For instance:

 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 Rob noted in the comments, you need to set the Security.framework link for SecRandomCopyBytes. You also need to enable SecRandom.h .

+14
source

On UNIX, you can rely on / dev / random or / dev / urandom to get cryptographic quality randomness.

 NSData *bytes = [[NSFileHandle fileHandleForReadingAtPath: @"/dev/random"] readDataOfLength: 100]; 

It seems to read 100 bytes from / dev / random. See man urandom more details.

+1
source

Source: https://habr.com/ru/post/897980/


All Articles