Generate random bytes Cocoa?
Asked Answered
M

2

6

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

Marvin answered 24/9, 2011 at 17:29 Comment(1)
How will you know what bytes are the random addition and which are part of the original plaintext when you decrypt? There are already a number of different cryptographic padding schemes for use in different circumstances, most of which are easier to chop off afterwards than a bunch of random bytes.Antemortem
A
15

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.

Androecium answered 24/9, 2011 at 17:31 Comment(6)
Yes; you can use [NSData initWithBytes: length:] to get to the data into an NSData object.Androecium
Could you be a bit more specific?Androecium
You could save some work by creating an NSMutableData object of the desired length and passing its mutableBytes pointer as the buffer for SecRandomCopyBytes to write into.Schappe
@PeterHosey Agreed. See robnapier.net/blog/aes-commoncrypto-564 for an example of this. Search for randomDataOfLength:. This is a very convenient way to manage buffers.Despondent
I believe you need to link Security.framework to get SecRandomCopyBytes(). That may be what's causing the trouble for the OP.Despondent
@RobNapier: One avenue of improvement there: You can use the strerror function to get a description of the errno value.Schappe
C
1

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.

Cyruscyst answered 26/1, 2014 at 17:49 Comment(2)
Note this is very easy but it fails if your app is in the App Sandbox, where it can't get at /devHostler
/dev/random is accessible from an unplugged iOS device. Is it sandboxed on macOS?Cyruscyst

© 2022 - 2024 — McMap. All rights reserved.