Random Numbers

What is the approved method of getting a random number in macOS in Objective C? Presently I'm using:



	srandomdev();
    randomDevice = fopen("/dev/random", "r");
//
//
//

-(uint64)random64
{
    uint64_t    value = 0;
    int         i;

   for (i = 0 ; i < sizeof(value); i++)
    {
        value <<= 8;
        value |= fgetc(randomDevice);
    }

    return value;
}

However, this method no longer appears in the documentation. Is there a more modern implementation?

Answered by Bruce D M in 694452022

I found the docs I needed: [https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc). The core foundation security services api contains the appropriate system call. The modern implementation of the above would be:

-(uint64)random64
{
    uint64_t    value = 0;
    uint8       randomByte;
    int         i, err;

   for (i = 0 ; i < sizeof(value); i++)
    {
        value <<= 8;
        err = SecRandomCopyBytes( kSecRandomDefault ,  1 ,  &randomByte );
        value |= randomByte;
    }

    return value;
}

Check out the arc4random_uniform function.

  uint32_t randomNumber = arc4random_uniform(25);
Accepted Answer

I found the docs I needed: [https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc). The core foundation security services api contains the appropriate system call. The modern implementation of the above would be:

-(uint64)random64
{
    uint64_t    value = 0;
    uint8       randomByte;
    int         i, err;

   for (i = 0 ; i < sizeof(value); i++)
    {
        value <<= 8;
        err = SecRandomCopyBytes( kSecRandomDefault ,  1 ,  &randomByte );
        value |= randomByte;
    }

    return value;
}

There’s two cases here:

  • Cryptographically sound random numbers

  • Pseudo random numbers

It sounds like you want the former, in which case I agree that SecRandomCopyBytes is a good option. However, you can get all eight bytes at once:

- (uint64)random64 {
    uint64_t result;
    OSStatus err = SecRandomCopyBytes(kSecRandomDefault, sizeof(result), &result);
    assert(err == errSecSuccess);
    return result;
}

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Random Numbers
 
 
Q