我现在在和Coverity玩,它对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()相同范围内的数字是否容易替换?

最佳答案

可能会尝试这样的方法:
我用过很多次了,似乎效果很好。

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()的调用,这个link提供了random()的一个实现,其行为与random()相同。

关于c - 使用urandom替换Rand(),srand()1至1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25613072/

10-12 02:47