我目前正在玩掩护,它对 rand() 调用大喊大叫
CID 52583 (#1 of 1): Don't call (DC.WEAK_CRYPTO)
dont_call: rand() should not be used for security related applications, as linear congruential algorithms are too easy to break.
使用 urandom 返回与 rand() 相同范围内的数字是否可以轻松替换?
为了抑制rand()在我的代码中使用与安全性无关的 Coverity 警告,我向 Coverity 提供了一个Coveritymodeling.c建模文件,以告诉 Coverity 忽略该功能,例如:
/* libc functions. */
int rand(void) {
/* ignore */
}
long random(void) {
/* ignore */
}
void srand(unsigned int seed) {
/* ignore */
}
对于这些方面的其他抑制示例,我经常查看 Python 的Coverity文档。
希望这可以帮助!
可能会尝试这样的事情:我已经使用了很多次,并且似乎工作得很好。
void SeedRandomNumGenerator()
{
unsigned int seed;
int fd;
fd = open("/dev/urandom", O_RDONLY);
if( fd )
{
read(fd, &seed, sizeof(seed));
close(fd);
srandom( seed );
}
}
/*
return a proper random number that uses the uniform distribution
of numbers returned by random() -- this is far better than
simply doing random() % limit
According to calculations, random() will at most be called twice
and usually only once per call to random_lim()
returns int between 0 and limit
so if you want a random number between 1-10 inclusive the call would
look like this: random_lim(9)+1
*/
int random_lim(int limit)
{
int divisor = RAND_MAX/(limit+1);
int retval;
do
{
retval = random() / divisor;
}while (retval > limit);
return( retval );
}
编辑:如果您想摆脱对 random() 的调用,此链接提供了 random() 的实现,其行为与 random() 相同。