I am in development of a header file that has multiple functions
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX 1024
void int2str(int num, char *s)
{
sprintf(s, "%d", num);
}
// takes a pointer to an integer
void randNum(int *ptr)
{
char str[MAX];
srand(time(0));
int tmp = rand();
int2str(tmp, str);
printf("%d [%c]\n", tmp, str[strlen(str)-1]);
const char c = str[strlen(str)-1];
*ptr = atoi(&c);
}
My question is how do I make sure that my function returns random numbers with enough randomness so that I am able to use it for different stuff including encryption
When I used the header file to generate a 100 random numbers I got the same number for more than one time and sometimes for more than three times is this normal or is the implementation for such a function poor
>Solution :
how do I make sure that my function returns random numbers with enough randomness
You can run statistical tests. This is sufficient for some applications, but not all.
different stuff including encryption
If your code fails statistical tests, it’s definitely bad for encryption, or pretty much any purpose related to cryptography or more generally to security. But even if your code passes statistical tests, it can be very bad for cryptography.
It is impossible to determine whether a random generator is good for encryption by looking only at its output. For example, if you take a good cryptographic-strength random generator and you don’t protect its internal state from snooping, that makes it unsuitable. You can’t tell whether the internal state is protected by looking only at the outputs. You have to review its code, understand the algorithms that it uses, and also understand the context in which it runs.
srand(time(0)); int tmp = rand();
rand() in the C standard library is not suitable for cryptography. Just this snippet has three catastrophic defects.
rand()on all the platforms I’ve ever seen is an algorithm chosen for speed, not for security. Given a moderate number of outputs, it’s possible to calculate the others.- Even if a platform used a cryptographic random generator algorithm for
rand(), the seed set bysrand(time())is easy to find (you just need to know when the generator was seeded), so an adversary could simply reproduce the calculation. - Even if the adversary was not able to guess the seed,
intis typically no more than 32 bits, so it’s easy to brute-force all possible seeds.
For any purpose that might be related to cryptography or security, use the random generator provided by your operating system or by a cryptographic library, for example BCryptGenRandom on Windows, /dev/urandom on most Unix variants including Linux and macOS, etc.