2014-09-01 127 views
1

我目前正在与Coverity的玩弄它大叫约兰特()调用兰特(),srand()函数使用urandom的

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. 

1to1更换是否有使用urandom来返回在号码更换容易降和rand()一样的范围?

+0

我想答案取决于rand()在你的系统上返回的范围。你会比我们更了解......(如果你想告诉我们,这是RAND_MAX)。 – indiv 2014-09-01 22:14:34

+0

您是否在安全相关的应用程序中使用它,如果rand函数(不一定是线性同余算法,但几乎肯定不是密码安全的)很容易被破坏? – 2014-09-01 23:15:51

+7

在您购买符合您要求的实施之前,您需要确定您的要求。 – 2014-09-01 23:32:53

回答

0

可能会尝试这样的事情: 我已经使用过很多次了,似乎工作得很好。

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); 
} 

编辑:如果你想摆脱调用随机()这个link提供了一个实现随机()的行为与随机的()。

+0

thx这看起来不错 - 但它仍然最终使用随机()和覆盖的警告不会消失 - 任何其他的想法? - 或者可能是一种抑制警告的方法 – 2014-09-05 08:27:27

+0

注意:'int divisor = RAND_MAX /(limit + 1);'当limit == INT_MAX'或'limit> RAND_MAX'时出现问题。 – chux 2014-09-05 16:46:42

1

为了抑制在我的代码,在其使用不是rand()的Coverity的警告安全相关的,我提供了一个modeling.c Coverity公司modeling file到Coverity公司,告诉Coverity公司忽略的功能,例如

/* libc functions. */ 

int rand(void) { 
    /* ignore */ 
} 

long random(void) { 
    /* ignore */ 
} 

void srand(unsigned int seed) { 
    /* ignore */ 
} 

对于沿着这些线路镇压的其他例子,我经常看Python的Coverity文档。

希望这有助于!