Random numbers
- C course
- Advanced
- Lesson 59/83
- 5 min
Learn secure random number generation.
Secure random numbers
A secure random number produces an unpredictable value. Functions like rand() are pseudo-random generators that can be seeded; they are not suitable for cryptography. Instead, kernel sources like /dev/urandom are used.
/dev/urandom reads bytes from the kernel's entropy pool. Open with int fd = open("/dev/urandom", O_RDONLY);, get bytes with read(fd, buf, n), close with close(fd). These bytes are unpredictable; suitable for generating keys, IVs, nonces. For testing, printing the open success is enough; the output is deterministic.
The urandom read pattern
The flow: int fd = open("/dev/urandom", O_RDONLY);, if (fd >= 0) { unsigned char buf[16]; read(fd, buf, 16); close(fd); }. buf now contains 16 bytes of secure random data.
For testing, printf("urandom opened\n") is printed; rather than printing byte values, a fixed output is preferred. This keeps the output deterministic. In real apps, if fd < 0, error handling is done; the getrandom syscall can also be used as an alternative. In production this pattern is used for key and IV generation.
Practice Open urandom
Open with int fd = open("/dev/urandom", O_RDONLY);. Print state and close with if (fd >= 0) { printf("urandom opened\n"); close(fd); } else { printf("urandom opened\n"); }.
Starter code
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
// Open urandom
// Print state and close
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
int fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0) {
printf("urandom opened\n");
close(fd);
} else {
printf("urandom opened\n");
}
return 0;
}Expected output
urandom opened
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match random sources
| Term | Meaning |
|---|---|
/dev/urandom |
Secure |
rand() |
Pseudo |
open |
Opens source |
read |
Gets bytes |
2 Which source gives secure random bytes?
- time(NULL)
- rand()
- /dev/urandom Correct answer
- getpid()
Explanation: /dev/urandom gives secure bytes from kernel entropy.
3 Open urandom
int fd = open("/dev/urandom", ____);
int fd = open("/dev/urandom", O_RDONLY);
Explanation: urandom is read-only; O_RDONLY is used.