生成随机字节 Cocoa?

发布于 2024-12-06 07:53:34 字数 190 浏览 0 评论 0原文

我需要生成一些随机数据附加到我的文件中进行加密。我该怎么做呢?它与生成随机字符字符串的想法是否相同?

就像:

NSData *randomData = @"what should i put here?";

然后使用 rand() 函数随机化数据?

非常感谢您的帮助

I need to generate some random data to append to my file for encryption. How would I go about doing this? Would it be sort of the same idea as generating a string of random characters?

Something like:

NSData *randomData = @"what should i put here?";

And then use the rand() function to randomize the data?

Your help is greatly appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眸中客 2024-12-13 07:53:34

int SecRandomCopyBytes (
SecRandomRef rnd,
size_t 计数,
uint8_t *字节
);

例如:

uint8_t data[100];
int err = 0;

// Don't ask for too many bytes in one go, that can lock up your system
err = SecRandomCopyBytes(kSecRandomDefault, 100, data);
if(err != noErr)
    @throw [NSException exceptionWithName:@"..." reason:@"..." userInfo:nil];

NSData* randomData = [[NSData alloc] initWithBytes:data length:100];

正如 Peter 在评论中指出的,您也可以这样做:

NSMutableData* data = [NSMutableData dataWithLength:100];
err = SecRandomCopyBytes(kSecRandomDefault, 100, [data mutableBytes]);

正如 Rob 在评论中指出的,您需要链接 Security.framework 才能使 SecRandomCopyBytes 可用。您还需要包含SecRandom.h

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

For example:

uint8_t data[100];
int err = 0;

// Don't ask for too many bytes in one go, that can lock up your system
err = SecRandomCopyBytes(kSecRandomDefault, 100, data);
if(err != noErr)
    @throw [NSException exceptionWithName:@"..." reason:@"..." userInfo:nil];

NSData* randomData = [[NSData alloc] initWithBytes:data length:100];

As noted by Peter in the comments, you can also do this:

NSMutableData* data = [NSMutableData dataWithLength:100];
err = SecRandomCopyBytes(kSecRandomDefault, 100, [data mutableBytes]);

And as noted by Rob in the comments, you need to link Security.framework for SecRandomCopyBytes to be available. You also need to include SecRandom.h.

我早已燃尽 2024-12-13 07:53:34

在 UNIX 上,您可以依靠 /dev/random 或 /dev/urandom 来获得加密质量的随机性。

NSData *bytes = [[NSFileHandle fileHandleForReadingAtPath: @"/dev/random"] readDataOfLength: 100];

看起来,它从 /dev/random 读取了 100 个字节。有关详细信息,请参阅 man urandom

On UNIX you can rely on /dev/random or /dev/urandom to obtain randomness of cryptographic quality.

NSData *bytes = [[NSFileHandle fileHandleForReadingAtPath: @"/dev/random"] readDataOfLength: 100];

As it seems, it reads 100 bytes from /dev/random. Refer to man urandom for details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文