Generates an array of cryptographically secure random bytes.


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



The random number generator object to use. Specify kSecRandomDefault to use the default random number generator.


The number of random bytes to return in the array pointed to by the bytes parameter.


A pointer to an array that the function fills with cryptographically secure random bytes. Use an array that is large enough to hold at least count bytes.

Return Value

A result code set to errSecSuccess or some other value on failure.


Always test the returned status to make sure that the array has been updated with new, random data before trying to use the values. For example, to create 10 random bytes:

SInt8 bytes[10];
int status = SecRandomCopyBytes(kSecRandomDefault, (sizeof bytes)/(sizeof bytes[0]), &bytes);
if (status == errSecSuccess) { // Always test the status.
    for (int i = 0; i < (sizeof bytes)/(sizeof bytes[0]); i++) {
        NSLog(@"%d", bytes[i]);
    // Prints something different every time you run.

See Also

Random Numbers


An abstract Core Foundation-type object containing information about a random number generator.


An alias for the default random number generator.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software