Generating Random Numbers Securely in Objective-C

2020-03-03 05:31发布

问题:

Where can I find an industry-accepted secure pseudo-random number generator for Objective-C? Is there one built in to the OS X SDK?

My question is basically the same as this one, except that I'm looking for a secure PRNG.

EDIT:

Thanks everyone for the help. Here's a simple one-liner to implement the /dev/random method:

-(NSData *)getRandomBytes:(NSUInteger)length {
    return [[NSFileHandle fileHandleForReadingAtPath:@"/dev/random"] readDataOfLength:length];
}

回答1:

Security.framework has a facility for doing this, called SecRandomCopyBytes(). Although it's really basically just copying from /dev/random.



回答2:

You can use

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

This function is available in Security/Security.h Framework. This function reads from /dev/random to obtain an array of cryptographically-secure random bytes.

/dev/random is a blocking interface that only returns as much random data as the system possesses at any particular time. Once the system runs out of randomness, no more can be fetched until more is generated (by listening to the user bang on the keyboard, or however the OS gathers true randomness). /dev/urandom is a non-blocking interface that always returns the requested amount of data, by using a pseudorandom generator even when true randomness is exhausted.OS X has both of these as well, however they both act like /dev/urandom does on Linux.

Random Numbers
random(4) Mac OS X Manual Page
How good is SecRandomCopyBytes?