Getting cryptographically secure random numbers in C ++ on iOS

I am working on an iOS application written in Objective-C and C ++. In the C ++ part, I need cryptographically secure random numbers.

  • As far as I understand the iOS security model, there is no direct access to /dev/random. It is right?

  • The official way to get SecRandomCopyBytes safe random numbers . Unfortunately, this is an Objective-C interface. Is there a way to use this interface from C ++, ideally, without resorting to Objective-C ++?

There's also arc4random , but I don't want to use anything based on RC4 these days ...

+4
source share
2 answers

The official way to get safe random numbers is SecRandomCopyBytes. Unfortunately, this is an Objective-C interface. Is there a way to use this interface from C ++, ideally, without resorting to Objective-C ++?

SecRandomCopyBytes is API C. There is no problem using it from C ++.

Here is a complete example. No ObjC ++ is required, even using fancy vectorand something else to show all C ++. Obviously you could just use malloc.

#include <iostream>
#include <Security/Security.h>
#include <vector>

int main(int argc, const char * argv[]) {
    const int length = 20;
    std::vector<uint8_t> randomBytes(length, 0);

    int rc = SecRandomCopyBytes(kSecRandomDefault, randomBytes.size(), &(randomBytes[0]));
    if (rc != 0) {
        std::cout << "Failed: " << rc << std::endl;
        return 1;
    }

    for (int i = 0; i < randomBytes.size(); ++i) {
        std::cout << std::hex << +randomBytes[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}
+4
source

One way to get cryptographically secure random numbers in any C language, including Swift, is to use the "C" arc4random functions .

For integers of random numbers (u_int32_t) use arc4random()and arc4random_uniform().

arc4random_buf() nbytes , ARC4.

RC4 arc4random, - :

arc4random() 32- . arc4random() , (4).

arc4random . , () , /dev/urandom. RC4. , , .

. , /dev/random , OS X, /dev/urandom.

+6

Source: https://habr.com/ru/post/1608865/


All Articles