...
The C Standard function rand() makes no guarantees as to the quality of the random sequence produced. The numbers generated by some implementations of rand() have a comparatively short cycle, and the numbers can be predictable. Applications which that have strong pseudorandom number requirements should use a generator that is known to be sufficient for their needs.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
#include <stdlib.h>
void func(void) {
enum { len = 12 };
char id[len]; /*
* id will hold the ID, starting with
* the characters "ID" followed by a
* random integer.
*/
int r;
int num;
/* ... */
r = rand(); /* Generate a random integer */
num = snprintf(id, len, "ID%-d", r); /* Generate the ID */
/* ... */
} |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void func(void) {
enum { len = 12 };
char id[len]; /*
* id will hold the ID, starting with
* the characters "ID" followed by a
* random integer.
*/
int r;
int num;
/* ... */
time_t now = time(NULL);
if (now == (time_t)-1) {
/* handleHandle error */
}
srandom(now); /* Seed the PRNG with the current time */
/* ... */
r = random(); /* Generate a random integer */
num = snprintf(id, len, "ID%-d", r); /* Generate the ID */
/* ... */
} |
...
Although not specified by POSIX, arc4random() is an option on systems that support it. From the arc4random(3) manual page [OpenBSD]:
arc4random()fits into a middle ground not covered by other subsystems such as the strong, slow, and resource expensive random devices described inrandom(4)versus the fast but poor quality interfaces described inrand(3),random(3), anddrand48(3).
To achieve the best random numbers possible, an implementation-specific function must be used. When unpredictability really matters and speed is not an issue, as in the creation of strong cryptographic keys, use a true entropy source, such as /dev/random, or a hardware device capable of generating random numbers. Note that the /dev/random device can block for a long time if there are not enough events going on to generate sufficient entropy.
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
|
|
| |||||||
| CC2.MSC30 | Fully implemented | |||||||
5.0 |
|
| |||||||
|
|
| |||||||
| PRQA QA-C |
| Warncall -wc rand | Fully implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
...