I need t开发者_C百科o 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
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
.
On UNIX you can rely on /dev/random or /dev/urandom to obtain randomness of cryptographic quality.
NSData *bytes = [[NSFileHandle fileHandleForReadingAtPath: @"/dev/random"] readDataOfLength: 100];
As it seems, it reads 100 bytes from /dev/random. Refer to man urandom
for details.
精彩评论