在iOS上使用C ++获取加密安全随机数 [英] Getting cryptographically secure random numbers in C++ on iOS
问题描述
我正在开发一个用Objective-C和C ++编写的iOS应用程序。在C ++部分,我需要加密安全随机数。
I'm working on an iOS app that is written in Objective-C and C++. In the C++ part, I need cryptographically secure random numbers.
-
据我了解iOS安全模型,没有办法直接访问
/ dev / random
。这是正确的吗?
获取安全随机数的官方方法是 SecRandomCopyBytes 。遗憾的是,这是一个Objective-C接口。有没有办法从C ++使用这个接口,理想情况下不使用Objective-C ++?
The official way to get secure random numbers is SecRandomCopyBytes. Sadly, this is an Objective-C interface. Is there a way to use this interface from C++, ideally without resorting to Objective-C++?
还有 arc4random ,但我不情愿现在使用任何基于RC4的东西...
There's also arc4random, but I'm reluctant to use anything that's based on RC4 nowadays...
推荐答案
获得安全随机的官方方法数字是SecRandomCopyBytes。遗憾的是,这是一个Objective-C接口。有没有办法从C ++使用这个接口,理想情况下不使用Objective-C ++?
The official way to get secure random numbers is SecRandomCopyBytes. Sadly, this is an Objective-C interface. Is there a way to use this interface from C++, ideally without resorting to Objective-C++?
SecRandomCopyBytes
是一个C API。从C ++中使用它没有问题。
SecRandomCopyBytes
is a C API. There is no problem using it from C++.
这是一个完整的例子。不需要ObjC ++,即使使用花哨的 vector
,还有什么可以展示它的全部C ++。显然你可以使用 malloc
。
Here's a full example. No ObjC++ required, even using fancy vector
and whatnot to show it's 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;
}
这篇关于在iOS上使用C ++获取加密安全随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!