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;
}
source
share