我需要将一些软件移植到只有标准 ANSI C 运行时和一些 POSIX 函数的平台上。该软件通过读取 /dev/urandom
生成用于密码加密 ZIP 文件的随机数。在 Windows 上,该软件使用 CryptGenRandom()
生成随机数。由于这两个功能在我的目标平台上不可用,因此我必须寻找替代方案。
我想出了这个来用 length
随机字节填充 buffer
:
bool zip_random(zip_uint8_t *buffer, zip_uint16_t length)
{
srand(time(NULL));
while(length--) *buffer++ = rand() % 256;
return true;
}
这可以完成工作,但由于该函数是在加密上下文中使用的,我不知道使用旧的 srand 和 rand 函数是否是一个好主意。这就是为什么我想问一下我的方法是否可以接受或者是否有更好的解决方案。
最佳答案
rand
不应用于任何需要实际安全性的事情。
关于 C11 standard 7.22.2.1 中的兰特的脚注
There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits. Applications with particular requirements should use a generator that is known to be sufficient for their needs.
关于c - 将从/dev/urandom读取的内容移植到非Unix平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47224964/